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