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