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