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