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