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