Hurd compat fixes. Mostly dealing with absent PATH_MAX
[oweals/busybox.git] / libbb / xconnect.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Connect to host at port using address resolution from getaddrinfo
6  *
7  * Licensed under GPLv2, see file LICENSE in this tarball for details.
8  */
9
10 #include <sys/socket.h> /* netinet/in.h needs it */
11 #include <netinet/in.h>
12 #include <net/if.h>
13 #include <sys/un.h>
14 #include "libbb.h"
15
16 void FAST_FUNC setsockopt_reuseaddr(int fd)
17 {
18         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &const_int_1, sizeof(const_int_1));
19 }
20 int FAST_FUNC setsockopt_broadcast(int fd)
21 {
22         return setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &const_int_1, sizeof(const_int_1));
23 }
24
25 #ifdef SO_BINDTODEVICE
26 int FAST_FUNC setsockopt_bindtodevice(int fd, const char *iface)
27 {
28         int r;
29         struct ifreq ifr;
30         strncpy_IFNAMSIZ(ifr.ifr_name, iface);
31         /* NB: passing (iface, strlen(iface) + 1) does not work!
32          * (maybe it works on _some_ kernels, but not on 2.6.26)
33          * Actually, ifr_name is at offset 0, and in practice
34          * just giving char[IFNAMSIZ] instead of struct ifreq works too.
35          * But just in case it's not true on some obscure arch... */
36         r = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
37         if (r)
38                 bb_perror_msg("can't bind to interface %s", iface);
39         return r;
40 }
41 #else
42 int FAST_FUNC setsockopt_bindtodevice(int fd UNUSED_PARAM,
43                 const char *iface UNUSED_PARAM)
44 {
45         bb_error_msg("SO_BINDTODEVICE is not supported on this system");
46         return -1;
47 }
48 #endif
49
50 len_and_sockaddr* FAST_FUNC get_sock_lsa(int fd)
51 {
52         len_and_sockaddr lsa;
53         len_and_sockaddr *lsa_ptr;
54
55         lsa.len = LSA_SIZEOF_SA;
56         if (getsockname(fd, &lsa.u.sa, &lsa.len) != 0)
57                 return NULL;
58
59         lsa_ptr = xzalloc(LSA_LEN_SIZE + lsa.len);
60         if (lsa.len > LSA_SIZEOF_SA) { /* rarely (if ever) happens */
61                 lsa_ptr->len = lsa.len;
62                 getsockname(fd, &lsa_ptr->u.sa, &lsa_ptr->len);
63         } else {
64                 memcpy(lsa_ptr, &lsa, LSA_LEN_SIZE + lsa.len);
65         }
66         return lsa_ptr;
67 }
68
69 void FAST_FUNC xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen)
70 {
71         if (connect(s, s_addr, addrlen) < 0) {
72                 if (ENABLE_FEATURE_CLEAN_UP)
73                         close(s);
74                 if (s_addr->sa_family == AF_INET)
75                         bb_perror_msg_and_die("%s (%s)",
76                                 "can't connect to remote host",
77                                 inet_ntoa(((struct sockaddr_in *)s_addr)->sin_addr));
78                 bb_perror_msg_and_die("can't connect to remote host");
79         }
80 }
81
82 /* Return port number for a service.
83  * If "port" is a number use it as the port.
84  * If "port" is a name it is looked up in /etc/services,
85  * if it isnt found return default_port
86  */
87 unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned default_port)
88 {
89         unsigned port_nr = default_port;
90         if (port) {
91                 int old_errno;
92
93                 /* Since this is a lib function, we're not allowed to reset errno to 0.
94                  * Doing so could break an app that is deferring checking of errno. */
95                 old_errno = errno;
96                 port_nr = bb_strtou(port, NULL, 10);
97                 if (errno || port_nr > 65535) {
98                         struct servent *tserv = getservbyname(port, protocol);
99                         port_nr = default_port;
100                         if (tserv)
101                                 port_nr = ntohs(tserv->s_port);
102                 }
103                 errno = old_errno;
104         }
105         return (uint16_t)port_nr;
106 }
107
108
109 /* "New" networking API */
110
111
112 int FAST_FUNC get_nport(const struct sockaddr *sa)
113 {
114 #if ENABLE_FEATURE_IPV6
115         if (sa->sa_family == AF_INET6) {
116                 return ((struct sockaddr_in6*)sa)->sin6_port;
117         }
118 #endif
119         if (sa->sa_family == AF_INET) {
120                 return ((struct sockaddr_in*)sa)->sin_port;
121         }
122         /* What? UNIX socket? IPX?? :) */
123         return -1;
124 }
125
126 void FAST_FUNC set_nport(len_and_sockaddr *lsa, unsigned port)
127 {
128 #if ENABLE_FEATURE_IPV6
129         if (lsa->u.sa.sa_family == AF_INET6) {
130                 lsa->u.sin6.sin6_port = port;
131                 return;
132         }
133 #endif
134         if (lsa->u.sa.sa_family == AF_INET) {
135                 lsa->u.sin.sin_port = port;
136                 return;
137         }
138         /* What? UNIX socket? IPX?? :) */
139 }
140
141 /* We hijack this constant to mean something else */
142 /* It doesn't hurt because we will remove this bit anyway */
143 #define DIE_ON_ERROR AI_CANONNAME
144
145 /* host: "1.2.3.4[:port]", "www.google.com[:port]"
146  * port: if neither of above specifies port # */
147 static len_and_sockaddr* str2sockaddr(
148                 const char *host, int port,
149 IF_FEATURE_IPV6(sa_family_t af,)
150                 int ai_flags)
151 {
152 IF_NOT_FEATURE_IPV6(sa_family_t af = AF_INET;)
153         int rc;
154         len_and_sockaddr *r;
155         struct addrinfo *result = NULL;
156         struct addrinfo *used_res;
157         const char *org_host = host; /* only for error msg */
158         const char *cp;
159         struct addrinfo hint;
160
161         if (ENABLE_FEATURE_UNIX_LOCAL && strncmp(host, "local:", 6) == 0) {
162                 struct sockaddr_un *sun;
163
164                 r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_un));
165                 r->len = sizeof(struct sockaddr_un);
166                 r->u.sa.sa_family = AF_UNIX;
167                 sun = (struct sockaddr_un *)&r->u.sa;
168                 safe_strncpy(sun->sun_path, host + 6, sizeof(sun->sun_path));
169                 return r;
170         }
171
172         r = NULL;
173
174         /* Ugly parsing of host:addr */
175         if (ENABLE_FEATURE_IPV6 && host[0] == '[') {
176                 /* Even uglier parsing of [xx]:nn */
177                 host++;
178                 cp = strchr(host, ']');
179                 if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
180                         /* Malformed: must be [xx]:nn or [xx] */
181                         bb_error_msg("bad address '%s'", org_host);
182                         if (ai_flags & DIE_ON_ERROR)
183                                 xfunc_die();
184                         return NULL;
185                 }
186         } else {
187                 cp = strrchr(host, ':');
188                 if (ENABLE_FEATURE_IPV6 && cp && strchr(host, ':') != cp) {
189                         /* There is more than one ':' (e.g. "::1") */
190                         cp = NULL; /* it's not a port spec */
191                 }
192         }
193         if (cp) { /* points to ":" or "]:" */
194                 int sz = cp - host + 1;
195
196                 host = safe_strncpy(alloca(sz), host, sz);
197                 if (ENABLE_FEATURE_IPV6 && *cp != ':') {
198                         cp++; /* skip ']' */
199                         if (*cp == '\0') /* [xx] without port */
200                                 goto skip;
201                 }
202                 cp++; /* skip ':' */
203                 port = bb_strtou(cp, NULL, 10);
204                 if (errno || (unsigned)port > 0xffff) {
205                         bb_error_msg("bad port spec '%s'", org_host);
206                         if (ai_flags & DIE_ON_ERROR)
207                                 xfunc_die();
208                         return NULL;
209                 }
210  skip: ;
211         }
212
213         /* Next two if blocks allow to skip getaddrinfo()
214          * in case host name is a numeric IP(v6) address.
215          * getaddrinfo() initializes DNS resolution machinery,
216          * scans network config and such - tens of syscalls.
217          */
218         /* If we were not asked specifically for IPv6,
219          * check whether this is a numeric IPv4 */
220         IF_FEATURE_IPV6(if(af != AF_INET6)) {
221                 struct in_addr in4;
222                 if (inet_aton(host, &in4) != 0) {
223                         r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_in));
224                         r->len = sizeof(struct sockaddr_in);
225                         r->u.sa.sa_family = AF_INET;
226                         r->u.sin.sin_addr = in4;
227                         goto set_port;
228                 }
229         }
230 #if ENABLE_FEATURE_IPV6
231         /* If we were not asked specifically for IPv4,
232          * check whether this is a numeric IPv6 */
233         if (af != AF_INET) {
234                 struct in6_addr in6;
235                 if (inet_pton(AF_INET6, host, &in6) > 0) {
236                         r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_in6));
237                         r->len = sizeof(struct sockaddr_in6);
238                         r->u.sa.sa_family = AF_INET6;
239                         r->u.sin6.sin6_addr = in6;
240                         goto set_port;
241                 }
242         }
243 #endif
244
245         memset(&hint, 0 , sizeof(hint));
246         hint.ai_family = af;
247         /* Needed. Or else we will get each address thrice (or more)
248          * for each possible socket type (tcp,udp,raw...): */
249         hint.ai_socktype = SOCK_STREAM;
250         hint.ai_flags = ai_flags & ~DIE_ON_ERROR;
251         rc = getaddrinfo(host, NULL, &hint, &result);
252         if (rc || !result) {
253                 bb_error_msg("bad address '%s'", org_host);
254                 if (ai_flags & DIE_ON_ERROR)
255                         xfunc_die();
256                 goto ret;
257         }
258         used_res = result;
259 #if ENABLE_FEATURE_PREFER_IPV4_ADDRESS
260         while (1) {
261                 if (used_res->ai_family == AF_INET)
262                         break;
263                 used_res = used_res->ai_next;
264                 if (!used_res) {
265                         used_res = result;
266                         break;
267                 }
268         }
269 #endif
270         r = xmalloc(LSA_LEN_SIZE + used_res->ai_addrlen);
271         r->len = used_res->ai_addrlen;
272         memcpy(&r->u.sa, used_res->ai_addr, used_res->ai_addrlen);
273
274  set_port:
275         set_nport(r, htons(port));
276  ret:
277         freeaddrinfo(result);
278         return r;
279 }
280 #if !ENABLE_FEATURE_IPV6
281 #define str2sockaddr(host, port, af, ai_flags) str2sockaddr(host, port, ai_flags)
282 #endif
283
284 #if ENABLE_FEATURE_IPV6
285 len_and_sockaddr* FAST_FUNC host_and_af2sockaddr(const char *host, int port, sa_family_t af)
286 {
287         return str2sockaddr(host, port, af, 0);
288 }
289
290 len_and_sockaddr* FAST_FUNC xhost_and_af2sockaddr(const char *host, int port, sa_family_t af)
291 {
292         return str2sockaddr(host, port, af, DIE_ON_ERROR);
293 }
294 #endif
295
296 len_and_sockaddr* FAST_FUNC host2sockaddr(const char *host, int port)
297 {
298         return str2sockaddr(host, port, AF_UNSPEC, 0);
299 }
300
301 len_and_sockaddr* FAST_FUNC xhost2sockaddr(const char *host, int port)
302 {
303         return str2sockaddr(host, port, AF_UNSPEC, DIE_ON_ERROR);
304 }
305
306 len_and_sockaddr* FAST_FUNC xdotted2sockaddr(const char *host, int port)
307 {
308         return str2sockaddr(host, port, AF_UNSPEC, AI_NUMERICHOST | DIE_ON_ERROR);
309 }
310
311 #undef xsocket_type
312 int FAST_FUNC xsocket_type(len_and_sockaddr **lsap, IF_FEATURE_IPV6(int family,) int sock_type)
313 {
314         IF_NOT_FEATURE_IPV6(enum { family = AF_INET };)
315         len_and_sockaddr *lsa;
316         int fd;
317         int len;
318
319 #if ENABLE_FEATURE_IPV6
320         if (family == AF_UNSPEC) {
321                 fd = socket(AF_INET6, sock_type, 0);
322                 if (fd >= 0) {
323                         family = AF_INET6;
324                         goto done;
325                 }
326                 family = AF_INET;
327         }
328 #endif
329         fd = xsocket(family, sock_type, 0);
330         len = sizeof(struct sockaddr_in);
331 #if ENABLE_FEATURE_IPV6
332         if (family == AF_INET6) {
333  done:
334                 len = sizeof(struct sockaddr_in6);
335         }
336 #endif
337         lsa = xzalloc(LSA_LEN_SIZE + len);
338         lsa->len = len;
339         lsa->u.sa.sa_family = family;
340         *lsap = lsa;
341         return fd;
342 }
343
344 int FAST_FUNC xsocket_stream(len_and_sockaddr **lsap)
345 {
346         return xsocket_type(lsap, IF_FEATURE_IPV6(AF_UNSPEC,) SOCK_STREAM);
347 }
348
349 static int create_and_bind_or_die(const char *bindaddr, int port, int sock_type)
350 {
351         int fd;
352         len_and_sockaddr *lsa;
353
354         if (bindaddr && bindaddr[0]) {
355                 lsa = xdotted2sockaddr(bindaddr, port);
356                 /* user specified bind addr dictates family */
357                 fd = xsocket(lsa->u.sa.sa_family, sock_type, 0);
358         } else {
359                 fd = xsocket_type(&lsa, IF_FEATURE_IPV6(AF_UNSPEC,) sock_type);
360                 set_nport(lsa, htons(port));
361         }
362         setsockopt_reuseaddr(fd);
363         xbind(fd, &lsa->u.sa, lsa->len);
364         free(lsa);
365         return fd;
366 }
367
368 int FAST_FUNC create_and_bind_stream_or_die(const char *bindaddr, int port)
369 {
370         return create_and_bind_or_die(bindaddr, port, SOCK_STREAM);
371 }
372
373 int FAST_FUNC create_and_bind_dgram_or_die(const char *bindaddr, int port)
374 {
375         return create_and_bind_or_die(bindaddr, port, SOCK_DGRAM);
376 }
377
378
379 int FAST_FUNC create_and_connect_stream_or_die(const char *peer, int port)
380 {
381         int fd;
382         len_and_sockaddr *lsa;
383
384         lsa = xhost2sockaddr(peer, port);
385         fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
386         setsockopt_reuseaddr(fd);
387         xconnect(fd, &lsa->u.sa, lsa->len);
388         free(lsa);
389         return fd;
390 }
391
392 int FAST_FUNC xconnect_stream(const len_and_sockaddr *lsa)
393 {
394         int fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
395         xconnect(fd, &lsa->u.sa, lsa->len);
396         return fd;
397 }
398
399 /* We hijack this constant to mean something else */
400 /* It doesn't hurt because we will add this bit anyway */
401 #define IGNORE_PORT NI_NUMERICSERV
402 static char* FAST_FUNC sockaddr2str(const struct sockaddr *sa, int flags)
403 {
404         char host[128];
405         char serv[16];
406         int rc;
407         socklen_t salen;
408
409         if (ENABLE_FEATURE_UNIX_LOCAL && sa->sa_family == AF_UNIX) {
410                 struct sockaddr_un *sun = (struct sockaddr_un *)sa;
411                 return xasprintf("local:%.*s",
412                                 (int) sizeof(sun->sun_path),
413                                 sun->sun_path);
414         }
415
416         salen = LSA_SIZEOF_SA;
417 #if ENABLE_FEATURE_IPV6
418         if (sa->sa_family == AF_INET)
419                 salen = sizeof(struct sockaddr_in);
420         if (sa->sa_family == AF_INET6)
421                 salen = sizeof(struct sockaddr_in6);
422 #endif
423         rc = getnameinfo(sa, salen,
424                         host, sizeof(host),
425         /* can do ((flags & IGNORE_PORT) ? NULL : serv) but why bother? */
426                         serv, sizeof(serv),
427                         /* do not resolve port# into service _name_ */
428                         flags | NI_NUMERICSERV
429         );
430         if (rc)
431                 return NULL;
432         if (flags & IGNORE_PORT)
433                 return xstrdup(host);
434 #if ENABLE_FEATURE_IPV6
435         if (sa->sa_family == AF_INET6) {
436                 if (strchr(host, ':')) /* heh, it's not a resolved hostname */
437                         return xasprintf("[%s]:%s", host, serv);
438                 /*return xasprintf("%s:%s", host, serv);*/
439                 /* - fall through instead */
440         }
441 #endif
442         /* For now we don't support anything else, so it has to be INET */
443         /*if (sa->sa_family == AF_INET)*/
444                 return xasprintf("%s:%s", host, serv);
445         /*return xstrdup(host);*/
446 }
447
448 char* FAST_FUNC xmalloc_sockaddr2host(const struct sockaddr *sa)
449 {
450         return sockaddr2str(sa, 0);
451 }
452
453 char* FAST_FUNC xmalloc_sockaddr2host_noport(const struct sockaddr *sa)
454 {
455         return sockaddr2str(sa, IGNORE_PORT);
456 }
457
458 char* FAST_FUNC xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa)
459 {
460         return sockaddr2str(sa, NI_NAMEREQD | IGNORE_PORT);
461 }
462 char* FAST_FUNC xmalloc_sockaddr2dotted(const struct sockaddr *sa)
463 {
464         return sockaddr2str(sa, NI_NUMERICHOST);
465 }
466
467 char* FAST_FUNC xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa)
468 {
469         return sockaddr2str(sa, NI_NUMERICHOST | IGNORE_PORT);
470 }