more C standard compat fixes from Dan Fandrich
[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                                 "cannot connect to remote host",
67                                 inet_ntoa(((struct sockaddr_in *)s_addr)->sin_addr));
68                 bb_perror_msg_and_die("cannot 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 /* "Old" networking API - only IPv4 */
100
101 /*
102 void FAST_FUNC bb_lookup_host(struct sockaddr_in *s_in, const char *host)
103 {
104         struct hostent *he;
105
106         memset(s_in, 0, sizeof(struct sockaddr_in));
107         s_in->sin_family = AF_INET;
108         he = xgethostbyname(host);
109         memcpy(&(s_in->sin_addr), he->h_addr_list[0], he->h_length);
110 }
111
112
113 int FAST_FUNC xconnect_tcp_v4(struct sockaddr_in *s_addr)
114 {
115         int s = xsocket(AF_INET, SOCK_STREAM, 0);
116         xconnect(s, (struct sockaddr*) s_addr, sizeof(*s_addr));
117         return s;
118 }
119 */
120
121 /* "New" networking API */
122
123
124 int FAST_FUNC get_nport(const struct sockaddr *sa)
125 {
126 #if ENABLE_FEATURE_IPV6
127         if (sa->sa_family == AF_INET6) {
128                 return ((struct sockaddr_in6*)sa)->sin6_port;
129         }
130 #endif
131         if (sa->sa_family == AF_INET) {
132                 return ((struct sockaddr_in*)sa)->sin_port;
133         }
134         /* What? UNIX socket? IPX?? :) */
135         return -1;
136 }
137
138 void FAST_FUNC set_nport(len_and_sockaddr *lsa, unsigned port)
139 {
140 #if ENABLE_FEATURE_IPV6
141         if (lsa->u.sa.sa_family == AF_INET6) {
142                 lsa->u.sin6.sin6_port = port;
143                 return;
144         }
145 #endif
146         if (lsa->u.sa.sa_family == AF_INET) {
147                 lsa->u.sin.sin_port = port;
148                 return;
149         }
150         /* What? UNIX socket? IPX?? :) */
151 }
152
153 /* We hijack this constant to mean something else */
154 /* It doesn't hurt because we will remove this bit anyway */
155 #define DIE_ON_ERROR AI_CANONNAME
156
157 /* host: "1.2.3.4[:port]", "www.google.com[:port]"
158  * port: if neither of above specifies port # */
159 static len_and_sockaddr* str2sockaddr(
160                 const char *host, int port,
161 IF_FEATURE_IPV6(sa_family_t af,)
162                 int ai_flags)
163 {
164         int rc;
165         len_and_sockaddr *r;
166         struct addrinfo *result = NULL;
167         struct addrinfo *used_res;
168         const char *org_host = host; /* only for error msg */
169         const char *cp;
170         struct addrinfo hint;
171
172         if (ENABLE_FEATURE_UNIX_LOCAL && strncmp(host, "local:", 6) == 0) {
173                 struct sockaddr_un *sun;
174
175                 r = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_un));
176                 r->len = sizeof(struct sockaddr_un);
177                 r->u.sa.sa_family = AF_UNIX;
178                 sun = (struct sockaddr_un *)&r->u.sa;
179                 safe_strncpy(sun->sun_path, host + 6, sizeof(sun->sun_path));
180                 return r;
181         }
182
183         r = NULL;
184
185         /* Ugly parsing of host:addr */
186         if (ENABLE_FEATURE_IPV6 && host[0] == '[') {
187                 /* Even uglier parsing of [xx]:nn */
188                 host++;
189                 cp = strchr(host, ']');
190                 if (!cp || (cp[1] != ':' && cp[1] != '\0')) {
191                         /* Malformed: must be [xx]:nn or [xx] */
192                         bb_error_msg("bad address '%s'", org_host);
193                         if (ai_flags & DIE_ON_ERROR)
194                                 xfunc_die();
195                         return NULL;
196                 }
197         } else {
198                 cp = strrchr(host, ':');
199                 if (ENABLE_FEATURE_IPV6 && cp && strchr(host, ':') != cp) {
200                         /* There is more than one ':' (e.g. "::1") */
201                         cp = NULL; /* it's not a port spec */
202                 }
203         }
204         if (cp) { /* points to ":" or "]:" */
205                 int sz = cp - host + 1;
206
207                 host = safe_strncpy(alloca(sz), host, sz);
208                 if (ENABLE_FEATURE_IPV6 && *cp != ':') {
209                         cp++; /* skip ']' */
210                         if (*cp == '\0') /* [xx] without port */
211                                 goto skip;
212                 }
213                 cp++; /* skip ':' */
214                 port = bb_strtou(cp, NULL, 10);
215                 if (errno || (unsigned)port > 0xffff) {
216                         bb_error_msg("bad port spec '%s'", org_host);
217                         if (ai_flags & DIE_ON_ERROR)
218                                 xfunc_die();
219                         return NULL;
220                 }
221  skip: ;
222         }
223
224         memset(&hint, 0 , sizeof(hint));
225 #if !ENABLE_FEATURE_IPV6
226         hint.ai_family = AF_INET; /* do not try to find IPv6 */
227 #else
228         hint.ai_family = af;
229 #endif
230         /* Needed. Or else we will get each address thrice (or more)
231          * for each possible socket type (tcp,udp,raw...): */
232         hint.ai_socktype = SOCK_STREAM;
233         hint.ai_flags = ai_flags & ~DIE_ON_ERROR;
234         rc = getaddrinfo(host, NULL, &hint, &result);
235         if (rc || !result) {
236                 bb_error_msg("bad address '%s'", org_host);
237                 if (ai_flags & DIE_ON_ERROR)
238                         xfunc_die();
239                 goto ret;
240         }
241         used_res = result;
242 #if ENABLE_FEATURE_PREFER_IPV4_ADDRESS
243         while (1) {
244                 if (used_res->ai_family == AF_INET)
245                         break;
246                 used_res = used_res->ai_next;
247                 if (!used_res) {
248                         used_res = result;
249                         break;
250                 }
251         }
252 #endif
253         r = xmalloc(offsetof(len_and_sockaddr, u.sa) + used_res->ai_addrlen);
254         r->len = used_res->ai_addrlen;
255         memcpy(&r->u.sa, used_res->ai_addr, used_res->ai_addrlen);
256         set_nport(r, htons(port));
257  ret:
258         freeaddrinfo(result);
259         return r;
260 }
261 #if !ENABLE_FEATURE_IPV6
262 #define str2sockaddr(host, port, af, ai_flags) str2sockaddr(host, port, ai_flags)
263 #endif
264
265 #if ENABLE_FEATURE_IPV6
266 len_and_sockaddr* FAST_FUNC host_and_af2sockaddr(const char *host, int port, sa_family_t af)
267 {
268         return str2sockaddr(host, port, af, 0);
269 }
270
271 len_and_sockaddr* FAST_FUNC xhost_and_af2sockaddr(const char *host, int port, sa_family_t af)
272 {
273         return str2sockaddr(host, port, af, DIE_ON_ERROR);
274 }
275 #endif
276
277 len_and_sockaddr* FAST_FUNC host2sockaddr(const char *host, int port)
278 {
279         return str2sockaddr(host, port, AF_UNSPEC, 0);
280 }
281
282 len_and_sockaddr* FAST_FUNC xhost2sockaddr(const char *host, int port)
283 {
284         return str2sockaddr(host, port, AF_UNSPEC, DIE_ON_ERROR);
285 }
286
287 len_and_sockaddr* FAST_FUNC xdotted2sockaddr(const char *host, int port)
288 {
289         return str2sockaddr(host, port, AF_UNSPEC, AI_NUMERICHOST | DIE_ON_ERROR);
290 }
291
292 #undef xsocket_type
293 int FAST_FUNC xsocket_type(len_and_sockaddr **lsap, IF_FEATURE_IPV6(int family,) int sock_type)
294 {
295         IF_NOT_FEATURE_IPV6(enum { family = AF_INET };)
296         len_and_sockaddr *lsa;
297         int fd;
298         int len;
299
300 #if ENABLE_FEATURE_IPV6
301         if (family == AF_UNSPEC) {
302                 fd = socket(AF_INET6, sock_type, 0);
303                 if (fd >= 0) {
304                         family = AF_INET6;
305                         goto done;
306                 }
307                 family = AF_INET;
308         }
309 #endif
310         fd = xsocket(family, sock_type, 0);
311         len = sizeof(struct sockaddr_in);
312 #if ENABLE_FEATURE_IPV6
313         if (family == AF_INET6) {
314  done:
315                 len = sizeof(struct sockaddr_in6);
316         }
317 #endif
318         lsa = xzalloc(offsetof(len_and_sockaddr, u.sa) + len);
319         lsa->len = len;
320         lsa->u.sa.sa_family = family;
321         *lsap = lsa;
322         return fd;
323 }
324
325 int FAST_FUNC xsocket_stream(len_and_sockaddr **lsap)
326 {
327         return xsocket_type(lsap, IF_FEATURE_IPV6(AF_UNSPEC,) SOCK_STREAM);
328 }
329
330 static int create_and_bind_or_die(const char *bindaddr, int port, int sock_type)
331 {
332         int fd;
333         len_and_sockaddr *lsa;
334
335         if (bindaddr && bindaddr[0]) {
336                 lsa = xdotted2sockaddr(bindaddr, port);
337                 /* user specified bind addr dictates family */
338                 fd = xsocket(lsa->u.sa.sa_family, sock_type, 0);
339         } else {
340                 fd = xsocket_type(&lsa, IF_FEATURE_IPV6(AF_UNSPEC,) sock_type);
341                 set_nport(lsa, htons(port));
342         }
343         setsockopt_reuseaddr(fd);
344         xbind(fd, &lsa->u.sa, lsa->len);
345         free(lsa);
346         return fd;
347 }
348
349 int FAST_FUNC create_and_bind_stream_or_die(const char *bindaddr, int port)
350 {
351         return create_and_bind_or_die(bindaddr, port, SOCK_STREAM);
352 }
353
354 int FAST_FUNC create_and_bind_dgram_or_die(const char *bindaddr, int port)
355 {
356         return create_and_bind_or_die(bindaddr, port, SOCK_DGRAM);
357 }
358
359
360 int FAST_FUNC create_and_connect_stream_or_die(const char *peer, int port)
361 {
362         int fd;
363         len_and_sockaddr *lsa;
364
365         lsa = xhost2sockaddr(peer, port);
366         fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
367         setsockopt_reuseaddr(fd);
368         xconnect(fd, &lsa->u.sa, lsa->len);
369         free(lsa);
370         return fd;
371 }
372
373 int FAST_FUNC xconnect_stream(const len_and_sockaddr *lsa)
374 {
375         int fd = xsocket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
376         xconnect(fd, &lsa->u.sa, lsa->len);
377         return fd;
378 }
379
380 /* We hijack this constant to mean something else */
381 /* It doesn't hurt because we will add this bit anyway */
382 #define IGNORE_PORT NI_NUMERICSERV
383 static char* FAST_FUNC sockaddr2str(const struct sockaddr *sa, int flags)
384 {
385         char host[128];
386         char serv[16];
387         int rc;
388         socklen_t salen;
389
390         if (ENABLE_FEATURE_UNIX_LOCAL && sa->sa_family == AF_UNIX) {
391                 struct sockaddr_un *sun = (struct sockaddr_un *)sa;
392                 return xasprintf("local:%.*s",
393                                 (int) sizeof(sun->sun_path),
394                                 sun->sun_path);
395         }
396
397         salen = LSA_SIZEOF_SA;
398 #if ENABLE_FEATURE_IPV6
399         if (sa->sa_family == AF_INET)
400                 salen = sizeof(struct sockaddr_in);
401         if (sa->sa_family == AF_INET6)
402                 salen = sizeof(struct sockaddr_in6);
403 #endif
404         rc = getnameinfo(sa, salen,
405                         host, sizeof(host),
406         /* can do ((flags & IGNORE_PORT) ? NULL : serv) but why bother? */
407                         serv, sizeof(serv),
408                         /* do not resolve port# into service _name_ */
409                         flags | NI_NUMERICSERV
410         );
411         if (rc)
412                 return NULL;
413         if (flags & IGNORE_PORT)
414                 return xstrdup(host);
415 #if ENABLE_FEATURE_IPV6
416         if (sa->sa_family == AF_INET6) {
417                 if (strchr(host, ':')) /* heh, it's not a resolved hostname */
418                         return xasprintf("[%s]:%s", host, serv);
419                 /*return xasprintf("%s:%s", host, serv);*/
420                 /* - fall through instead */
421         }
422 #endif
423         /* For now we don't support anything else, so it has to be INET */
424         /*if (sa->sa_family == AF_INET)*/
425                 return xasprintf("%s:%s", host, serv);
426         /*return xstrdup(host);*/
427 }
428
429 char* FAST_FUNC xmalloc_sockaddr2host(const struct sockaddr *sa)
430 {
431         return sockaddr2str(sa, 0);
432 }
433
434 char* FAST_FUNC xmalloc_sockaddr2host_noport(const struct sockaddr *sa)
435 {
436         return sockaddr2str(sa, IGNORE_PORT);
437 }
438
439 char* FAST_FUNC xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa)
440 {
441         return sockaddr2str(sa, NI_NAMEREQD | IGNORE_PORT);
442 }
443 char* FAST_FUNC xmalloc_sockaddr2dotted(const struct sockaddr *sa)
444 {
445         return sockaddr2str(sa, NI_NUMERICHOST);
446 }
447
448 char* FAST_FUNC xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa)
449 {
450         return sockaddr2str(sa, NI_NUMERICHOST | IGNORE_PORT);
451 }