blob: 47528810fdbf3f6497701ce71210cd28cdb33269 [file] [log] [blame]
Harald Welte468b6432014-09-11 13:05:51 +08001/*
Harald Welte48f55832017-01-26 00:03:10 +01002 * (C) 2011-2017 by Harald Welte <laforge@gnumonks.org>
Harald Welte468b6432014-09-11 13:05:51 +08003 *
4 * All Rights Reserved
5 *
Harald Weltee08da972017-11-13 01:00:26 +09006 * SPDX-License-Identifier: GPL-2.0+
7 *
Harald Welte468b6432014-09-11 13:05:51 +08008 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 */
23
Harald Welte33cb71a2011-05-21 18:54:32 +020024#include "../config.h"
25
Harald Welteba6988b2011-08-17 12:46:48 +020026/*! \addtogroup socket
27 * @{
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020028 * Osmocom socket convenience functions.
29 *
30 * \file socket.c */
Harald Welte96e2a002017-06-12 21:44:18 +020031
Harald Weltee4764422011-05-22 12:25:57 +020032#ifdef HAVE_SYS_SOCKET_H
33
Harald Welte33cb71a2011-05-21 18:54:32 +020034#include <osmocom/core/logging.h>
35#include <osmocom/core/select.h>
36#include <osmocom/core/socket.h>
Harald Welte48f55832017-01-26 00:03:10 +010037#include <osmocom/core/talloc.h>
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +020038#include <osmocom/core/utils.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020039
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +020040#include <sys/ioctl.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020041#include <sys/socket.h>
42#include <sys/types.h>
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +010043#include <sys/un.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020044
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010045#include <netinet/in.h>
Harald Weltee30d7e62017-07-13 16:02:50 +020046#include <arpa/inet.h>
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010047
Harald Welte33cb71a2011-05-21 18:54:32 +020048#include <stdio.h>
49#include <unistd.h>
50#include <stdint.h>
51#include <string.h>
52#include <errno.h>
53#include <netdb.h>
54#include <ifaddrs.h>
55
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +020056#ifdef HAVE_LIBSCTP
57#include <netinet/sctp.h>
58#endif
59
Harald Weltedda70fc2017-04-08 20:52:33 +020060static struct addrinfo *addrinfo_helper(uint16_t family, uint16_t type, uint8_t proto,
61 const char *host, uint16_t port, bool passive)
62{
Pau Espin Pedrolff428522019-10-10 17:38:16 +020063 struct addrinfo hints, *result, *rp;
Oliver Smith860651e2018-10-30 14:31:57 +010064 char portbuf[6];
Harald Weltedda70fc2017-04-08 20:52:33 +020065 int rc;
66
67 snprintf(portbuf, sizeof(portbuf), "%u", port);
68 memset(&hints, 0, sizeof(struct addrinfo));
69 hints.ai_family = family;
70 if (type == SOCK_RAW) {
71 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
72 * SOCK_RAW and IPPROTO_GRE is used.
Pau Espin Pedrolff428522019-10-10 17:38:16 +020073 * http://sourceware.org/bugzilla/show_bug.cgi?id=15015
Harald Weltedda70fc2017-04-08 20:52:33 +020074 */
75 hints.ai_socktype = SOCK_DGRAM;
76 hints.ai_protocol = IPPROTO_UDP;
77 } else {
78 hints.ai_socktype = type;
79 hints.ai_protocol = proto;
80 }
81
82 if (passive)
83 hints.ai_flags |= AI_PASSIVE;
84
85 rc = getaddrinfo(host, portbuf, &hints, &result);
86 if (rc != 0) {
87 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo returned NULL: %s:%u: %s\n",
88 host, port, strerror(errno));
89 return NULL;
90 }
91
Pau Espin Pedrolff428522019-10-10 17:38:16 +020092 for (rp = result; rp != NULL; rp = rp->ai_next) {
93 /* Workaround for glibc again */
94 if (type == SOCK_RAW) {
95 rp->ai_socktype = SOCK_RAW;
96 rp->ai_protocol = proto;
97 }
98 }
99
Harald Weltedda70fc2017-04-08 20:52:33 +0200100 return result;
101}
102
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200103/*! Retrieve an array of addrinfo with specified hints, one for each host in the hosts array.
104 * \param[out] addrinfo array of addrinfo pointers, will be filled by the function on success.
105 * Its size must be at least the one of hosts.
106 * \param[in] family Socket family like AF_INET, AF_INET6.
107 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM.
108 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP.
109 * \param[in] hosts array of char pointers (strings) containing the addresses to query.
110 * \param[in] host_cnt length of the hosts array (in items).
111 * \param[in] port port number in host byte order.
112 * \param[in] passive whether to include the AI_PASSIVE flag in getaddrinfo() hints.
113 * \returns 0 is returned on success together with a filled addrinfo array; negative on error
114 */
115static int addrinfo_helper_multi(struct addrinfo **addrinfo, uint16_t family, uint16_t type, uint8_t proto,
116 const char **hosts, size_t host_cnt, uint16_t port, bool passive)
117{
118 int i, j;
119
120 for (i = 0; i < host_cnt; i++) {
121 addrinfo[i] = addrinfo_helper(family, type, proto, hosts[i], port, passive);
122 if (!addrinfo[i]) {
123 for (j = 0; j < i; j++)
124 freeaddrinfo(addrinfo[j]);
125 return -EINVAL;
126 }
127 }
128 return 0;
129}
130
Harald Weltedda70fc2017-04-08 20:52:33 +0200131static int socket_helper(const struct addrinfo *rp, unsigned int flags)
132{
133 int sfd, on = 1;
134
135 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200136 if (sfd == -1) {
137 LOGP(DLGLOBAL, LOGL_ERROR,
138 "unable to create socket: %s\n", strerror(errno));
Harald Weltedda70fc2017-04-08 20:52:33 +0200139 return sfd;
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200140 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200141 if (flags & OSMO_SOCK_F_NONBLOCK) {
142 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
143 LOGP(DLGLOBAL, LOGL_ERROR,
144 "cannot set this socket unblocking: %s\n",
145 strerror(errno));
146 close(sfd);
147 sfd = -EINVAL;
148 }
149 }
150 return sfd;
151}
152
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200153/* Fill buf with a string representation of the address set, in the form:
154 * buf_len == 0: "()"
155 * buf_len == 1: "hostA"
156 * buf_len >= 2: (hostA|hostB|...|...)
157 */
158static int multiaddr_snprintf(char* buf, size_t buf_len, const char **hosts, size_t host_cnt)
159{
160 int len = 0, offset = 0, rem = buf_len;
161 int ret, i;
162 char *after;
163
164 if (buf_len < 3)
165 return -EINVAL;
166
167 if (host_cnt != 1) {
168 ret = snprintf(buf, rem, "(");
169 if (ret < 0)
170 return ret;
171 OSMO_SNPRINTF_RET(ret, rem, offset, len);
172 }
173 for (i = 0; i < host_cnt; i++) {
174 if (host_cnt == 1)
175 after = "";
176 else
177 after = (i == (host_cnt - 1)) ? ")" : "|";
178 ret = snprintf(buf + offset, rem, "%s%s", hosts[i] ? : "0.0.0.0", after);
179 OSMO_SNPRINTF_RET(ret, rem, offset, len);
180 }
181
182 return len;
183}
Harald Weltedda70fc2017-04-08 20:52:33 +0200184
Harald Weltec47bbda2017-07-13 16:13:26 +0200185static int osmo_sock_init_tail(int fd, uint16_t type, unsigned int flags)
186{
Harald Weltebc43a622017-07-13 16:20:21 +0200187 int rc;
Harald Weltec47bbda2017-07-13 16:13:26 +0200188
189 /* Make sure to call 'listen' on a bound, connection-oriented sock */
190 if ((flags & (OSMO_SOCK_F_BIND|OSMO_SOCK_F_CONNECT)) == OSMO_SOCK_F_BIND) {
191 switch (type) {
192 case SOCK_STREAM:
193 case SOCK_SEQPACKET:
194 rc = listen(fd, 10);
Harald Weltebc43a622017-07-13 16:20:21 +0200195 if (rc < 0) {
196 LOGP(DLGLOBAL, LOGL_ERROR, "unable to listen on socket: %s\n",
197 strerror(errno));
198 return rc;
199 }
200 break;
Harald Weltec47bbda2017-07-13 16:13:26 +0200201 }
202 }
203
Harald Weltebc43a622017-07-13 16:20:21 +0200204 if (flags & OSMO_SOCK_F_NO_MCAST_LOOP) {
205 rc = osmo_sock_mcast_loop_set(fd, false);
206 if (rc < 0) {
207 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable multicast loop: %s\n",
208 strerror(errno));
209 return rc;
210 }
211 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200212
Harald Welte37d204a2017-07-13 16:33:16 +0200213 if (flags & OSMO_SOCK_F_NO_MCAST_ALL) {
214 rc = osmo_sock_mcast_all_set(fd, false);
215 if (rc < 0) {
216 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable receive of all multicast: %s\n",
217 strerror(errno));
218 /* do not abort here, as this is just an
219 * optional additional optimization that only
220 * exists on Linux only */
221 }
222 }
Harald Weltebc43a622017-07-13 16:20:21 +0200223 return 0;
Harald Weltec47bbda2017-07-13 16:13:26 +0200224}
225
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200226/*! Initialize a socket (including bind and/or connect)
Harald Weltedda70fc2017-04-08 20:52:33 +0200227 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
228 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
229 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
230 * \param[in] local_host local host name or IP address in string form
231 * \param[in] local_port local port number in host byte order
232 * \param[in] remote_host remote host name or IP address in string form
233 * \param[in] remote_port remote port number in host byte order
234 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
235 * \returns socket file descriptor on success; negative on error
236 *
237 * This function creates a new socket of the designated \a family, \a
238 * type and \a proto and optionally binds it to the \a local_host and \a
239 * local_port as well as optionally connects it to the \a remote_host
240 * and \q remote_port, depending on the value * of \a flags parameter.
241 *
242 * As opposed to \ref osmo_sock_init(), this function allows to combine
243 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
244 * is useful if you want to connect to a remote host/port, but still
245 * want to bind that socket to either a specific local alias IP and/or a
246 * specific local source port.
247 *
248 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
249 * OSMO_SOCK_F_CONNECT, or both.
250 *
251 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
252 * non-blocking mode.
253 */
254int osmo_sock_init2(uint16_t family, uint16_t type, uint8_t proto,
255 const char *local_host, uint16_t local_port,
256 const char *remote_host, uint16_t remote_port, unsigned int flags)
257{
258 struct addrinfo *result, *rp;
259 int sfd = -1, rc, on = 1;
260
261 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
262 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
263 "BIND or CONNECT flags\n");
264 return -EINVAL;
265 }
266
267 /* figure out local side of socket */
268 if (flags & OSMO_SOCK_F_BIND) {
269 result = addrinfo_helper(family, type, proto, local_host, local_port, true);
270 if (!result)
271 return -EINVAL;
272
273 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200274 sfd = socket_helper(rp, flags);
275 if (sfd < 0)
276 continue;
277
Philipp Maier73196e72018-08-23 20:11:50 +0200278 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200279 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
280 &on, sizeof(on));
281 if (rc < 0) {
282 LOGP(DLGLOBAL, LOGL_ERROR,
283 "cannot setsockopt socket:"
284 " %s:%u: %s\n",
285 local_host, local_port,
286 strerror(errno));
287 close(sfd);
288 continue;
289 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200290 }
Philipp Maier99f706d2018-08-01 12:40:36 +0200291
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200292 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
293 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
294 local_host, local_port, strerror(errno));
295 close(sfd);
296 continue;
297 }
298 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200299 }
300 freeaddrinfo(result);
301 if (rp == NULL) {
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200302 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
303 local_host, local_port);
Harald Weltedda70fc2017-04-08 20:52:33 +0200304 return -ENODEV;
305 }
306 }
307
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200308 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
309 was already closed and func returned. If OSMO_SOCK_F_BIND is not
310 set, then sfd = -1 */
311
Harald Weltedda70fc2017-04-08 20:52:33 +0200312 /* figure out remote side of socket */
313 if (flags & OSMO_SOCK_F_CONNECT) {
314 result = addrinfo_helper(family, type, proto, remote_host, remote_port, false);
315 if (!result) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200316 if (sfd >= 0)
317 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200318 return -EINVAL;
319 }
320
321 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Welte5cfa6dc2017-07-21 16:52:29 +0200322 if (sfd < 0) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200323 sfd = socket_helper(rp, flags);
324 if (sfd < 0)
325 continue;
326 }
327
328 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200329 if (rc != 0 && errno != EINPROGRESS) {
330 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
331 remote_host, remote_port, strerror(errno));
332 /* We want to maintain the bind socket if bind was enabled */
333 if (!(flags & OSMO_SOCK_F_BIND)) {
334 close(sfd);
335 sfd = -1;
336 }
337 continue;
338 }
339 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200340 }
341 freeaddrinfo(result);
342 if (rp == NULL) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200343 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable remote addr found for: %s:%u\n",
344 remote_host, remote_port);
345 if (sfd >= 0)
346 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200347 return -ENODEV;
348 }
349 }
350
Harald Weltec47bbda2017-07-13 16:13:26 +0200351 rc = osmo_sock_init_tail(sfd, type, flags);
352 if (rc < 0) {
353 close(sfd);
354 sfd = -1;
Harald Weltedda70fc2017-04-08 20:52:33 +0200355 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200356
Harald Weltedda70fc2017-04-08 20:52:33 +0200357 return sfd;
358}
359
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200360#ifdef HAVE_LIBSCTP
361
362
363/* Build array of addresses taking first addrinfo result of the requested family
364 * for each host in hosts. addrs4 or addrs6 are filled based on family type. */
365static int addrinfo_to_sockaddr(uint16_t family, const struct addrinfo **result,
366 const char **hosts, int host_cont,
367 struct sockaddr_in *addrs4, struct sockaddr_in6 *addrs6) {
368 size_t host_idx;
369 const struct addrinfo *rp;
370 OSMO_ASSERT(family == AF_INET || family == AF_INET6);
371
372 for (host_idx = 0; host_idx < host_cont; host_idx++) {
373 for (rp = result[host_idx]; rp != NULL; rp = rp->ai_next) {
374 if (rp->ai_family != family)
375 continue;
376 if (family == AF_INET)
377 memcpy(&addrs4[host_idx], rp->ai_addr, sizeof(addrs4[host_idx]));
378 else
379 memcpy(&addrs6[host_idx], rp->ai_addr, sizeof(addrs6[host_idx]));
380 break;
381 }
382 if (!rp) { /* No addr could be bound for this host! */
383 LOGP(DLGLOBAL, LOGL_ERROR, "No suitable remote address found for host: %s\n",
384 hosts[host_idx]);
385 return -ENODEV;
386 }
387 }
388 return 0;
389}
390
391/*! Initialize a socket (including bind and/or connect) with multiple local or remote addresses.
392 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
393 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
394 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
395 * \param[in] local_hosts array of char pointers (strings), each containing local host name or IP address in string form
396 * \param[in] local_hosts_cnt length of local_hosts (in items)
397 * \param[in] local_port local port number in host byte order
398 * \param[in] remote_host array of char pointers (strings), each containing remote host name or IP address in string form
399 * \param[in] remote_hosts_cnt length of remote_hosts (in items)
400 * \param[in] remote_port remote port number in host byte order
401 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
402 * \returns socket file descriptor on success; negative on error
403 *
404 * This function is similar to \ref osmo_sock_init2(), but can be passed an
405 * array of local or remote addresses for protocols supporting multiple
406 * addresses per socket, like SCTP (currently only one supported). This function
407 * should not be used by protocols not supporting this kind of features, but
408 * rather \ref osmo_sock_init2() should be used instead.
409 * See \ref osmo_sock_init2() for more information on flags and general behavior.
410 */
411int osmo_sock_init2_multiaddr(uint16_t family, uint16_t type, uint8_t proto,
412 const char **local_hosts, size_t local_hosts_cnt, uint16_t local_port,
413 const char **remote_hosts, size_t remote_hosts_cnt, uint16_t remote_port,
414 unsigned int flags)
415
416{
417 struct addrinfo *result[OSMO_SOCK_MAX_ADDRS];
418 int sfd = -1, rc, on = 1;
419 int i;
420 struct sockaddr_in addrs4[OSMO_SOCK_MAX_ADDRS];
421 struct sockaddr_in6 addrs6[OSMO_SOCK_MAX_ADDRS];
422 struct sockaddr *addrs;
423 char strbuf[512];
424
425 /* TODO: So far this function is only aimed for SCTP, but could be
426 reused in the future for other protocols with multi-addr support */
427 if (proto != IPPROTO_SCTP)
428 return -ENOTSUP;
429
430 /* TODO: Let's not support AF_UNSPEC for now. sctp_bindx() actually
431 supports binding both types of addresses on a AF_INET6 soscket, but
432 that would mean we could get both AF_INET and AF_INET6 addresses for
433 each host, and makes complexity of this function increase a lot since
434 we'd need to find out which subsets to use, use v4v6 mapped socket,
435 etc. */
436 if (family == AF_UNSPEC)
437 return -ENOTSUP;
438
439 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
440 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
441 "BIND or CONNECT flags\n");
442 return -EINVAL;
443 }
444
445 if (((flags & OSMO_SOCK_F_BIND) && !local_hosts_cnt) ||
446 ((flags & OSMO_SOCK_F_CONNECT) && !remote_hosts_cnt) ||
447 local_hosts_cnt > OSMO_SOCK_MAX_ADDRS ||
448 remote_hosts_cnt > OSMO_SOCK_MAX_ADDRS)
449 return -EINVAL;
450
451 /* figure out local side of socket */
452 if (flags & OSMO_SOCK_F_BIND) {
453 rc = addrinfo_helper_multi(result, family, type, proto, local_hosts,
454 local_hosts_cnt, local_port, true);
455 if (rc < 0)
456 return -EINVAL;
457
458 /* Since addrinfo_helper sets ai_family, socktype and
459 ai_protocol in hints, we know all results will use same
460 values, so simply pick the first one and pass it to create
461 the socket:
462 */
463 sfd = socket_helper(result[0], flags);
464 if (sfd < 0) {
465 for (i = 0; i < local_hosts_cnt; i++)
466 freeaddrinfo(result[i]);
467 return sfd;
468 }
469
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200470 /* Since so far we only allow IPPROTO_SCTP in this function,
471 no need to check below for "proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR" */
472 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
473 &on, sizeof(on));
474 if (rc < 0) {
475 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
476 LOGP(DLGLOBAL, LOGL_ERROR,
477 "cannot setsockopt socket:"
478 " %s:%u: %s\n",
479 strbuf, local_port,
480 strerror(errno));
481 for (i = 0; i < local_hosts_cnt; i++)
482 freeaddrinfo(result[i]);
483 close(sfd);
484 return rc;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200485 }
486
487 /* Build array of addresses taking first of same family for each host.
488 TODO: Ideally we should use backtracking storing last used
489 indexes and trying next combination if connect() fails .*/
490 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)result,
491 local_hosts, local_hosts_cnt, addrs4, addrs6);
492 if (rc < 0) {
493 for (i = 0; i < local_hosts_cnt; i++)
494 freeaddrinfo(result[i]);
495 close(sfd);
496 return -ENODEV;
497 }
498
499 if (family == AF_INET)
500 addrs = (struct sockaddr *)addrs4;
501 else
502 addrs = (struct sockaddr *)addrs6;
503 if (sctp_bindx(sfd, addrs, local_hosts_cnt, SCTP_BINDX_ADD_ADDR) == -1) {
504 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
505 LOGP(DLGLOBAL, LOGL_NOTICE, "unable to bind socket: %s:%u: %s\n",
506 strbuf, local_port, strerror(errno));
507 for (i = 0; i < local_hosts_cnt; i++)
508 freeaddrinfo(result[i]);
509 close(sfd);
510 return -ENODEV;
511 }
512 for (i = 0; i < local_hosts_cnt; i++)
513 freeaddrinfo(result[i]);
514 }
515
516 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
517 was already closed and func returned. If OSMO_SOCK_F_BIND is not
518 set, then sfd = -1 */
519
520 /* figure out remote side of socket */
521 if (flags & OSMO_SOCK_F_CONNECT) {
522 rc = addrinfo_helper_multi(result, family, type, proto, remote_hosts,
523 remote_hosts_cnt, remote_port, false);
524 if (rc < 0) {
525 if (sfd >= 0)
526 close(sfd);
527 return -EINVAL;
528 }
529
530 if (sfd < 0) {
531 /* Since addrinfo_helper sets ai_family, socktype and
532 ai_protocol in hints, we know all results will use same
533 values, so simply pick the first one and pass it to create
534 the socket:
535 */
536 sfd = socket_helper(result[0], flags);
537 if (sfd < 0) {
538 for (i = 0; i < remote_hosts_cnt; i++)
539 freeaddrinfo(result[i]);
540 return sfd;
541 }
542 }
543
544 /* Build array of addresses taking first of same family for each host.
545 TODO: Ideally we should use backtracking storing last used
546 indexes and trying next combination if connect() fails .*/
547 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)result,
548 remote_hosts, remote_hosts_cnt, addrs4, addrs6);
549 if (rc < 0) {
550 for (i = 0; i < remote_hosts_cnt; i++)
551 freeaddrinfo(result[i]);
552 close(sfd);
553 return -ENODEV;
554 }
555
556 if (family == AF_INET)
557 addrs = (struct sockaddr *)addrs4;
558 else
559 addrs = (struct sockaddr *)addrs6;
560 rc = sctp_connectx(sfd, addrs, remote_hosts_cnt, NULL);
561 if (rc != 0 && errno != EINPROGRESS) {
562 multiaddr_snprintf(strbuf, sizeof(strbuf), remote_hosts, remote_hosts_cnt);
563 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
564 strbuf, remote_port, strerror(errno));
565 for (i = 0; i < remote_hosts_cnt; i++)
566 freeaddrinfo(result[i]);
567 close(sfd);
568 return -ENODEV;
569 }
570 for (i = 0; i < remote_hosts_cnt; i++)
571 freeaddrinfo(result[i]);
572 }
573
574 rc = osmo_sock_init_tail(sfd, type, flags);
575 if (rc < 0) {
576 close(sfd);
577 sfd = -1;
578 }
579
580 return sfd;
581}
582#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200583
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200584/*! Initialize a socket (including bind/connect)
Harald Welteba6988b2011-08-17 12:46:48 +0200585 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
586 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
587 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
588 * \param[in] host remote host name or IP address in string form
589 * \param[in] port remote port number in host byte order
590 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200591 * \returns socket file descriptor on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200592 *
593 * This function creates a new socket of the designated \a family, \a
594 * type and \a proto and optionally binds or connects it, depending on
595 * the value of \a flags parameter.
596 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200597int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200598 const char *host, uint16_t port, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200599{
Harald Weltedda70fc2017-04-08 20:52:33 +0200600 struct addrinfo *result, *rp;
Harald Welte68b15742011-05-22 21:47:29 +0200601 int sfd, rc, on = 1;
Harald Welte33cb71a2011-05-21 18:54:32 +0200602
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200603 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200604 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100605 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: both bind and connect flags set:"
Neels Hofmeyrb7f191f2016-08-29 11:22:03 +0200606 " %s:%u\n", host, port);
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200607 return -EINVAL;
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200608 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200609
Harald Weltedda70fc2017-04-08 20:52:33 +0200610 result = addrinfo_helper(family, type, proto, host, port, flags & OSMO_SOCK_F_BIND);
611 if (!result) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100612 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo returned NULL: %s:%u: %s\n",
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200613 host, port, strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200614 return -EINVAL;
615 }
616
617 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200618 sfd = socket_helper(rp, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200619 if (sfd == -1)
620 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200621
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200622 if (flags & OSMO_SOCK_F_CONNECT) {
623 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200624 if (rc != 0 && errno != EINPROGRESS) {
625 close(sfd);
626 continue;
627 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200628 } else {
Philipp Maier73196e72018-08-23 20:11:50 +0200629 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200630 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
631 &on, sizeof(on));
632 if (rc < 0) {
633 LOGP(DLGLOBAL, LOGL_ERROR,
634 "cannot setsockopt socket:"
635 " %s:%u: %s\n",
636 host, port, strerror(errno));
637 close(sfd);
638 continue;
639 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200640 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200641 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
642 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket:"
643 "%s:%u: %s\n",
644 host, port, strerror(errno));
645 close(sfd);
646 continue;
647 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200648 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200649 break;
Harald Welte33cb71a2011-05-21 18:54:32 +0200650 }
651 freeaddrinfo(result);
652
653 if (rp == NULL) {
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200654 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable addr found for: %s:%u\n",
655 host, port);
Harald Welte33cb71a2011-05-21 18:54:32 +0200656 return -ENODEV;
657 }
Harald Welte68b15742011-05-22 21:47:29 +0200658
Philipp Maier73196e72018-08-23 20:11:50 +0200659 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200660 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
661 if (rc < 0) {
662 LOGP(DLGLOBAL, LOGL_ERROR,
663 "cannot setsockopt socket: %s:%u: %s\n", host,
664 port, strerror(errno));
665 close(sfd);
666 sfd = -1;
667 }
Philipp Maier0659c5d2018-08-01 12:43:08 +0200668 }
Harald Welte68b15742011-05-22 21:47:29 +0200669
Harald Weltec47bbda2017-07-13 16:13:26 +0200670 rc = osmo_sock_init_tail(sfd, type, flags);
671 if (rc < 0) {
672 close(sfd);
673 sfd = -1;
Harald Welte68b15742011-05-22 21:47:29 +0200674 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200675
Harald Welte68b15742011-05-22 21:47:29 +0200676 return sfd;
677}
678
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200679/*! fill \ref osmo_fd for a give sfd
Max862ba652014-10-13 14:54:25 +0200680 * \param[out] ofd file descriptor (will be filled in)
681 * \param[in] sfd socket file descriptor
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200682 * \returns socket fd on success; negative on error
Max862ba652014-10-13 14:54:25 +0200683 *
684 * This function fills the \a ofd structure.
685 */
686static inline int osmo_fd_init_ofd(struct osmo_fd *ofd, int sfd)
687{
688 int rc;
689
690 if (sfd < 0)
691 return sfd;
692
693 ofd->fd = sfd;
Harald Welte16886992019-03-20 10:26:39 +0100694 ofd->when = OSMO_FD_READ;
Max862ba652014-10-13 14:54:25 +0200695
696 rc = osmo_fd_register(ofd);
697 if (rc < 0) {
698 close(sfd);
699 return rc;
700 }
701
702 return sfd;
703}
704
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200705/*! Initialize a socket and fill \ref osmo_fd
Katerina Barone-Adesic28c6a02013-02-15 13:27:59 +0100706 * \param[out] ofd file descriptor (will be filled in)
Harald Welteba6988b2011-08-17 12:46:48 +0200707 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
708 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
709 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
710 * \param[in] host remote host name or IP address in string form
711 * \param[in] port remote port number in host byte order
712 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200713 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200714 *
715 * This function creates (and optionall binds/connects) a socket using
716 * \ref osmo_sock_init, but also fills the \a ofd structure.
717 */
Harald Welte68b15742011-05-22 21:47:29 +0200718int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200719 const char *host, uint16_t port, unsigned int flags)
Harald Welte68b15742011-05-22 21:47:29 +0200720{
Max862ba652014-10-13 14:54:25 +0200721 return osmo_fd_init_ofd(ofd, osmo_sock_init(family, type, proto, host, port, flags));
Harald Welte33cb71a2011-05-21 18:54:32 +0200722}
723
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200724/*! Initialize a socket and fill \ref osmo_fd
Pau Espin Pedrol75989e62017-05-26 12:39:53 +0200725 * \param[out] ofd file descriptor (will be filled in)
726 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
727 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
728 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
729 * \param[in] local_host local host name or IP address in string form
730 * \param[in] local_port local port number in host byte order
731 * \param[in] remote_host remote host name or IP address in string form
732 * \param[in] remote_port remote port number in host byte order
733 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
734 * \returns socket fd on success; negative on error
735 *
736 * This function creates (and optionall binds/connects) a socket using
737 * \ref osmo_sock_init2, but also fills the \a ofd structure.
738 */
739int osmo_sock_init2_ofd(struct osmo_fd *ofd, int family, int type, int proto,
740 const char *local_host, uint16_t local_port,
741 const char *remote_host, uint16_t remote_port, unsigned int flags)
742{
743 return osmo_fd_init_ofd(ofd, osmo_sock_init2(family, type, proto, local_host,
744 local_port, remote_host, remote_port, flags));
745}
746
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200747/*! Initialize a socket and fill \ref sockaddr
Harald Welteba6988b2011-08-17 12:46:48 +0200748 * \param[out] ss socket address (will be filled in)
749 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
750 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
751 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200752 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200753 *
754 * This function creates (and optionall binds/connects) a socket using
755 * \ref osmo_sock_init, but also fills the \a ss structure.
756 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200757int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200758 uint8_t proto, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200759{
760 char host[NI_MAXHOST];
761 uint16_t port;
762 struct sockaddr_in *sin;
763 struct sockaddr_in6 *sin6;
764 int s, sa_len;
765
766 /* determine port and host from ss */
767 switch (ss->sa_family) {
768 case AF_INET:
769 sin = (struct sockaddr_in *) ss;
770 sa_len = sizeof(struct sockaddr_in);
771 port = ntohs(sin->sin_port);
772 break;
773 case AF_INET6:
774 sin6 = (struct sockaddr_in6 *) ss;
775 sa_len = sizeof(struct sockaddr_in6);
776 port = ntohs(sin6->sin6_port);
777 break;
778 default:
779 return -EINVAL;
780 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200781
782 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
783 NULL, 0, NI_NUMERICHOST);
784 if (s != 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100785 LOGP(DLGLOBAL, LOGL_ERROR, "getnameinfo failed:"
786 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200787 return s;
788 }
789
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200790 return osmo_sock_init(ss->sa_family, type, proto, host, port, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200791}
792
793static int sockaddr_equal(const struct sockaddr *a,
Harald Weltee4764422011-05-22 12:25:57 +0200794 const struct sockaddr *b, unsigned int len)
Harald Welte33cb71a2011-05-21 18:54:32 +0200795{
796 struct sockaddr_in *sin_a, *sin_b;
797 struct sockaddr_in6 *sin6_a, *sin6_b;
798
799 if (a->sa_family != b->sa_family)
800 return 0;
801
802 switch (a->sa_family) {
803 case AF_INET:
804 sin_a = (struct sockaddr_in *)a;
805 sin_b = (struct sockaddr_in *)b;
806 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
807 sizeof(struct in_addr)))
808 return 1;
809 break;
810 case AF_INET6:
811 sin6_a = (struct sockaddr_in6 *)a;
812 sin6_b = (struct sockaddr_in6 *)b;
813 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
814 sizeof(struct in6_addr)))
815 return 1;
816 break;
817 }
818 return 0;
819}
820
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200821/*! Determine if the given address is a local address
Harald Welteba6988b2011-08-17 12:46:48 +0200822 * \param[in] addr Socket Address
823 * \param[in] addrlen Length of socket address in bytes
824 * \returns 1 if address is local, 0 otherwise.
825 */
Harald Weltebc32d052012-04-08 11:31:32 +0200826int osmo_sockaddr_is_local(struct sockaddr *addr, unsigned int addrlen)
Harald Welte33cb71a2011-05-21 18:54:32 +0200827{
828 struct ifaddrs *ifaddr, *ifa;
829
830 if (getifaddrs(&ifaddr) == -1) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100831 LOGP(DLGLOBAL, LOGL_ERROR, "getifaddrs:"
832 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200833 return -EIO;
834 }
835
836 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
Harald Welte4d3a7b12011-05-24 21:31:53 +0200837 if (!ifa->ifa_addr)
838 continue;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200839 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen)) {
840 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +0200841 return 1;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200842 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200843 }
844
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200845 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +0200846 return 0;
847}
Harald Weltee4764422011-05-22 12:25:57 +0200848
Max9d7a2472018-11-20 15:18:31 +0100849/*! Convert sockaddr_in to IP address as char string and port as uint16_t.
850 * \param[out] addr String buffer to write IP address to, or NULL.
851 * \param[out] addr_len Size of \a addr.
852 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
853 * \param[in] sin Sockaddr to convert.
854 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
855 */
856size_t osmo_sockaddr_in_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
857 const struct sockaddr_in *sin)
858{
859 if (port)
860 *port = ntohs(sin->sin_port);
861
862 if (addr)
863 return osmo_strlcpy(addr, inet_ntoa(sin->sin_addr), addr_len);
864
865 return 0;
866}
867
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +0200868/*! Convert sockaddr to IP address as char string and port as uint16_t.
869 * \param[out] addr String buffer to write IP address to, or NULL.
870 * \param[out] addr_len Size of \a addr.
871 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
872 * \param[in] sa Sockaddr to convert.
873 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
874 */
875unsigned int osmo_sockaddr_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
876 const struct sockaddr *sa)
877{
878 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
879
Max9d7a2472018-11-20 15:18:31 +0100880 return osmo_sockaddr_in_to_str_and_uint(addr, addr_len, port, sin);
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +0200881}
882
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200883/*! Initialize a unix domain socket (including bind/connect)
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100884 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
885 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
886 * \param[in] socket_path path to identify the socket
887 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200888 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100889 *
890 * This function creates a new unix domain socket, \a
891 * type and \a proto and optionally binds or connects it, depending on
892 * the value of \a flags parameter.
893 */
Eric Wildeb5769b2019-06-27 15:31:17 +0200894#if defined(__clang__) && defined(SUN_LEN)
895__attribute__((no_sanitize("undefined")))
896#endif
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100897int osmo_sock_unix_init(uint16_t type, uint8_t proto,
898 const char *socket_path, unsigned int flags)
899{
900 struct sockaddr_un local;
901 int sfd, rc, on = 1;
902 unsigned int namelen;
903
904 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
905 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT))
906 return -EINVAL;
907
908 local.sun_family = AF_UNIX;
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200909 /* When an AF_UNIX socket is bound, sun_path should be NUL-terminated. See unix(7) man page. */
910 if (osmo_strlcpy(local.sun_path, socket_path, sizeof(local.sun_path)) >= sizeof(local.sun_path)) {
Stefan Sperling896ff6d2018-08-28 14:34:17 +0200911 LOGP(DLGLOBAL, LOGL_ERROR, "Socket path exceeds maximum length of %zd bytes: %s\n",
912 sizeof(local.sun_path), socket_path);
913 return -ENOSPC;
914 }
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100915
916#if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200917 local.sun_len = strlen(local.sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100918#endif
919#if defined(BSD44SOCKETS) || defined(SUN_LEN)
920 namelen = SUN_LEN(&local);
921#else
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200922 namelen = strlen(local.sun_path) +
923 offsetof(struct sockaddr_un, sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100924#endif
925
926 sfd = socket(AF_UNIX, type, proto);
927 if (sfd < 0)
928 return -1;
929
930 if (flags & OSMO_SOCK_F_CONNECT) {
931 rc = connect(sfd, (struct sockaddr *)&local, namelen);
932 if (rc < 0)
933 goto err;
934 } else {
935 unlink(local.sun_path);
936 rc = bind(sfd, (struct sockaddr *)&local, namelen);
937 if (rc < 0)
938 goto err;
939 }
940
941 if (flags & OSMO_SOCK_F_NONBLOCK) {
942 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100943 LOGP(DLGLOBAL, LOGL_ERROR,
944 "cannot set this socket unblocking: %s\n",
945 strerror(errno));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100946 close(sfd);
947 return -EINVAL;
948 }
949 }
950
Harald Weltec47bbda2017-07-13 16:13:26 +0200951 rc = osmo_sock_init_tail(sfd, type, flags);
952 if (rc < 0) {
953 close(sfd);
954 sfd = -1;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100955 }
956
957 return sfd;
958err:
959 close(sfd);
960 return -1;
961}
962
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200963/*! Initialize a unix domain socket and fill \ref osmo_fd
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100964 * \param[out] ofd file descriptor (will be filled in)
965 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
966 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
967 * \param[in] socket_path path to identify the socket
968 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200969 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100970 *
Vadim Yanitskiyb606d762019-06-01 19:02:47 +0700971 * This function creates (and optionally binds/connects) a socket
972 * using osmo_sock_unix_init, but also fills the ofd structure.
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100973 */
974int osmo_sock_unix_init_ofd(struct osmo_fd *ofd, uint16_t type, uint8_t proto,
975 const char *socket_path, unsigned int flags)
976{
Max862ba652014-10-13 14:54:25 +0200977 return osmo_fd_init_ofd(ofd, osmo_sock_unix_init(type, proto, socket_path, flags));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100978}
979
Neels Hofmeyr01457512018-12-12 01:48:54 +0100980/*! Get the IP and/or port number on socket in separate string buffers.
Oliver Smith7acd5d02018-10-25 11:16:36 +0200981 * \param[in] fd file descriptor of socket
982 * \param[out] ip IP address (will be filled in when not NULL)
983 * \param[in] ip_len length of the ip buffer
984 * \param[out] port number (will be filled in when not NULL)
985 * \param[in] port_len length of the port buffer
986 * \param[in] local (true) or remote (false) name will get looked at
987 * \returns 0 on success; negative otherwise
988 */
Neels Hofmeyr01457512018-12-12 01:48:54 +0100989int osmo_sock_get_ip_and_port(int fd, char *ip, size_t ip_len, char *port, size_t port_len, bool local)
Oliver Smith7acd5d02018-10-25 11:16:36 +0200990{
991 struct sockaddr sa;
992 socklen_t len = sizeof(sa);
Oliver Smith860651e2018-10-30 14:31:57 +0100993 char ipbuf[INET6_ADDRSTRLEN], portbuf[6];
Oliver Smith7acd5d02018-10-25 11:16:36 +0200994 int rc;
995
996 rc = local ? getsockname(fd, &sa, &len) : getpeername(fd, &sa, &len);
997 if (rc < 0)
998 return rc;
999
1000 rc = getnameinfo(&sa, len, ipbuf, sizeof(ipbuf),
1001 portbuf, sizeof(portbuf),
1002 NI_NUMERICHOST | NI_NUMERICSERV);
1003 if (rc < 0)
1004 return rc;
1005
1006 if (ip)
1007 strncpy(ip, ipbuf, ip_len);
1008 if (port)
1009 strncpy(port, portbuf, port_len);
1010 return 0;
1011}
1012
1013/*! Get local IP address on socket
1014 * \param[in] fd file descriptor of socket
1015 * \param[out] ip IP address (will be filled in)
1016 * \param[in] len length of the output buffer
1017 * \returns 0 on success; negative otherwise
1018 */
1019int osmo_sock_get_local_ip(int fd, char *ip, size_t len)
1020{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001021 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001022}
1023
1024/*! Get local port on socket
1025 * \param[in] fd file descriptor of socket
1026 * \param[out] port number (will be filled in)
1027 * \param[in] len length of the output buffer
1028 * \returns 0 on success; negative otherwise
1029 */
1030int osmo_sock_get_local_ip_port(int fd, char *port, size_t len)
1031{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001032 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001033}
1034
1035/*! Get remote IP address on socket
1036 * \param[in] fd file descriptor of socket
1037 * \param[out] ip IP address (will be filled in)
1038 * \param[in] len length of the output buffer
1039 * \returns 0 on success; negative otherwise
1040 */
1041int osmo_sock_get_remote_ip(int fd, char *ip, size_t len)
1042{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001043 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001044}
1045
1046/*! Get remote port on socket
1047 * \param[in] fd file descriptor of socket
1048 * \param[out] port number (will be filled in)
1049 * \param[in] len length of the output buffer
1050 * \returns 0 on success; negative otherwise
1051 */
1052int osmo_sock_get_remote_ip_port(int fd, char *port, size_t len)
1053{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001054 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001055}
1056
Neels Hofmeyr01457512018-12-12 01:48:54 +01001057/*! Get address/port information on socket in dyn-alloc string like "(r=1.2.3.4:5<->l=6.7.8.9:10)".
1058 * Usually, it is better to use osmo_sock_get_name2() for a static string buffer or osmo_sock_get_name_buf() for a
1059 * caller provided string buffer, to avoid the dynamic talloc allocation.
Harald Welte48f55832017-01-26 00:03:10 +01001060 * \param[in] ctx talloc context from which to allocate string buffer
1061 * \param[in] fd file descriptor of socket
Neels Hofmeyr01457512018-12-12 01:48:54 +01001062 * \returns string identifying the connection of this socket, talloc'd from ctx.
Harald Welte48f55832017-01-26 00:03:10 +01001063 */
Harald Weltec0dfc9d2019-03-18 18:29:43 +01001064char *osmo_sock_get_name(const void *ctx, int fd)
Harald Welte48f55832017-01-26 00:03:10 +01001065{
Philipp Maier64b51eb2019-01-14 11:59:11 +01001066 char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001067 int rc;
1068 rc = osmo_sock_get_name_buf(str, sizeof(str), fd);
1069 if (rc <= 0)
1070 return NULL;
1071 return talloc_asprintf(ctx, "(%s)", str);
1072}
1073
1074/*! Get address/port information on socket in provided string buffer, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1075 * This does not include braces like osmo_sock_get_name().
1076 * \param[out] str Destination string buffer.
1077 * \param[in] str_len sizeof(str).
1078 * \param[in] fd File descriptor of socket.
1079 * \return String length as returned by snprintf(), or negative on error.
1080 */
1081int osmo_sock_get_name_buf(char *str, size_t str_len, int fd)
1082{
Oliver Smith860651e2018-10-30 14:31:57 +01001083 char hostbuf_l[INET6_ADDRSTRLEN], hostbuf_r[INET6_ADDRSTRLEN];
1084 char portbuf_l[6], portbuf_r[6];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001085 int rc;
Harald Welte48f55832017-01-26 00:03:10 +01001086
Oliver Smith7acd5d02018-10-25 11:16:36 +02001087 /* get local */
Harald Welteea9ea522019-05-10 09:28:24 +02001088 if ((rc = osmo_sock_get_ip_and_port(fd, hostbuf_l, sizeof(hostbuf_l), portbuf_l, sizeof(portbuf_l), true))) {
1089 osmo_strlcpy(str, "<error-in-getsockname>", str_len);
Neels Hofmeyr01457512018-12-12 01:48:54 +01001090 return rc;
Harald Welteea9ea522019-05-10 09:28:24 +02001091 }
Harald Welte48f55832017-01-26 00:03:10 +01001092
Oliver Smith7acd5d02018-10-25 11:16:36 +02001093 /* get remote */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001094 if (osmo_sock_get_ip_and_port(fd, hostbuf_r, sizeof(hostbuf_r), portbuf_r, sizeof(portbuf_r), false) != 0)
1095 return snprintf(str, str_len, "r=NULL<->l=%s:%s", hostbuf_l, portbuf_l);
Harald Welte48f55832017-01-26 00:03:10 +01001096
Neels Hofmeyr01457512018-12-12 01:48:54 +01001097 return snprintf(str, str_len, "r=%s:%s<->l=%s:%s", hostbuf_r, portbuf_r, hostbuf_l, portbuf_l);
1098}
1099
1100/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1101 * This does not include braces like osmo_sock_get_name().
1102 * \param[in] fd File descriptor of socket.
1103 * \return Static string buffer containing the result.
1104 */
1105const char *osmo_sock_get_name2(int fd)
1106{
Harald Welte171ef822019-03-28 10:49:05 +01001107 static __thread char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001108 osmo_sock_get_name_buf(str, sizeof(str), fd);
1109 return str;
Harald Welte48f55832017-01-26 00:03:10 +01001110}
1111
Harald Welte179f3572019-03-18 18:38:47 +01001112/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1113 * This does not include braces like osmo_sock_get_name().
1114 * \param[in] fd File descriptor of socket.
1115 * \return Static string buffer containing the result.
1116 */
1117char *osmo_sock_get_name2_c(const void *ctx, int fd)
1118{
1119 char *str = talloc_size(ctx, OSMO_SOCK_NAME_MAXLEN);
1120 if (!str)
1121 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001122 osmo_sock_get_name_buf(str, OSMO_SOCK_NAME_MAXLEN, fd);
Harald Welte179f3572019-03-18 18:38:47 +01001123 return str;
1124}
1125
Harald Weltee30d7e62017-07-13 16:02:50 +02001126static int sock_get_domain(int fd)
1127{
1128 int domain;
1129#ifdef SO_DOMAIN
1130 socklen_t dom_len = sizeof(domain);
1131 int rc;
1132
1133 rc = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &dom_len);
1134 if (rc < 0)
1135 return rc;
1136#else
1137 /* This of course sucks, but what shall we do on OSs like
1138 * FreeBSD that don't seem to expose a method by which one can
1139 * learn the address family of a socket? */
1140 domain = AF_INET;
1141#endif
1142 return domain;
1143}
1144
1145
1146/*! Activate or de-activate local loop-back of transmitted multicast packets
1147 * \param[in] fd file descriptor of related socket
1148 * \param[in] enable Enable (true) or disable (false) loop-back
1149 * \returns 0 on success; negative otherwise */
1150int osmo_sock_mcast_loop_set(int fd, bool enable)
1151{
1152 int domain, loop = 0;
1153
1154 if (enable)
1155 loop = 1;
1156
1157 domain = sock_get_domain(fd);
1158 if (domain < 0)
1159 return domain;
1160
1161 switch (domain) {
1162 case AF_INET:
1163 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1164 case AF_INET6:
1165 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop));
1166 default:
1167 return -EINVAL;
1168 }
1169}
1170
1171/*! Set the TTL of outbound multicast packets
1172 * \param[in] fd file descriptor of related socket
1173 * \param[in] ttl TTL of to-be-sent multicast packets
1174 * \returns 0 on success; negative otherwise */
1175int osmo_sock_mcast_ttl_set(int fd, uint8_t ttl)
1176{
1177 int domain, ttli = ttl;
1178
1179 domain = sock_get_domain(fd);
1180 if (domain < 0)
1181 return domain;
1182
1183 switch (domain) {
1184 case AF_INET:
1185 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttli, sizeof(ttli));
1186 case AF_INET6:
1187 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttli, sizeof(ttli));
1188 default:
1189 return -EINVAL;
1190 }
1191}
1192
1193/*! Enable/disable receiving all multicast packets, even for non-subscribed groups
1194 * \param[in] fd file descriptor of related socket
1195 * \param[in] enable Enable or Disable receiving of all packets
1196 * \returns 0 on success; negative otherwise */
1197int osmo_sock_mcast_all_set(int fd, bool enable)
1198{
1199 int domain, all = 0;
1200
1201 if (enable)
1202 all = 1;
1203
1204 domain = sock_get_domain(fd);
1205 if (domain < 0)
1206 return domain;
1207
1208 switch (domain) {
1209 case AF_INET:
1210#ifdef IP_MULTICAST_ALL
1211 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_ALL, &all, sizeof(all));
1212#endif
1213 case AF_INET6:
1214 /* there seems no equivalent ?!? */
1215 default:
1216 return -EINVAL;
1217 }
1218}
1219
1220/* FreeBSD calls the socket option differently */
1221#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
1222#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1223#endif
1224
1225/*! Subscribe to the given IP multicast group
1226 * \param[in] fd file descriptor of related scoket
1227 * \param[in] grp_addr ASCII representation of the multicast group address
1228 * \returns 0 on success; negative otherwise */
1229int osmo_sock_mcast_subscribe(int fd, const char *grp_addr)
1230{
1231 int rc, domain;
1232 struct ip_mreq mreq;
1233 struct ipv6_mreq mreq6;
1234 struct in6_addr i6a;
1235
1236 domain = sock_get_domain(fd);
1237 if (domain < 0)
1238 return domain;
1239
1240 switch (domain) {
1241 case AF_INET:
1242 memset(&mreq, 0, sizeof(mreq));
1243 mreq.imr_multiaddr.s_addr = inet_addr(grp_addr);
1244 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1245 return setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
1246#ifdef IPV6_ADD_MEMBERSHIP
1247 case AF_INET6:
1248 memset(&mreq6, 0, sizeof(mreq6));
1249 rc = inet_pton(AF_INET6, grp_addr, (void *)&i6a);
1250 if (rc < 0)
1251 return -EINVAL;
1252 mreq6.ipv6mr_multiaddr = i6a;
1253 return setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
1254#endif
1255 default:
1256 return -EINVAL;
1257 }
1258}
1259
Philipp Maier2d2490e2017-10-20 19:41:26 +02001260/*! Determine the matching local IP-address for a given remote IP-Address.
1261 * \param[out] local_ip caller provided memory for resulting local IP-address
1262 * \param[in] remote_ip remote IP-address
1263 * \param[in] fd file descriptor of related scoket
1264 * \returns 0 on success; negative otherwise
1265 *
1266 * The function accepts IPv4 and IPv6 address strings. The caller must provide
1267 * at least INET6_ADDRSTRLEN bytes for local_ip if an IPv6 is expected as
1268 * as result. For IPv4 addresses the required amount is INET_ADDRSTRLEN. */
1269int osmo_sock_local_ip(char *local_ip, const char *remote_ip)
1270{
1271 int sfd;
1272 int rc;
1273 struct addrinfo addrinfo_hint;
1274 struct addrinfo *addrinfo = NULL;
1275 struct sockaddr_in local_addr;
1276 socklen_t local_addr_len;
1277 uint16_t family;
1278
1279 /* Find out the address family (AF_INET or AF_INET6?) */
1280 memset(&addrinfo_hint, '\0', sizeof(addrinfo_hint));
1281 addrinfo_hint.ai_family = PF_UNSPEC;
1282 addrinfo_hint.ai_flags = AI_NUMERICHOST;
1283 rc = getaddrinfo(remote_ip, NULL, &addrinfo_hint, &addrinfo);
1284 if (rc)
1285 return -EINVAL;
1286 family = addrinfo->ai_family;
1287 freeaddrinfo(addrinfo);
1288
1289 /* Connect a dummy socket to trick the kernel into determining the
1290 * ip-address of the interface that would be used if we would send
1291 * out an actual packet */
1292 sfd = osmo_sock_init2(family, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, remote_ip, 0, OSMO_SOCK_F_CONNECT);
1293 if (sfd < 0)
1294 return -EINVAL;
1295
1296 /* Request the IP address of the interface that the kernel has
1297 * actually choosen. */
1298 memset(&local_addr, 0, sizeof(local_addr));
1299 local_addr_len = sizeof(local_addr);
1300 rc = getsockname(sfd, (struct sockaddr *)&local_addr, &local_addr_len);
Philipp Maier8b7975b2018-01-22 15:38:07 +01001301 close(sfd);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001302 if (rc < 0)
1303 return -EINVAL;
1304 if (local_addr.sin_family == AF_INET)
Philipp Maier91cfda82018-01-22 16:56:27 +01001305 inet_ntop(AF_INET, &local_addr.sin_addr, local_ip, INET_ADDRSTRLEN);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001306 else if (local_addr.sin_family == AF_INET6)
Philipp Maier91cfda82018-01-22 16:56:27 +01001307 inet_ntop(AF_INET6, &local_addr.sin_addr, local_ip, INET6_ADDRSTRLEN);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001308 else
1309 return -EINVAL;
1310
1311 return 0;
1312}
1313
Harald Weltee4764422011-05-22 12:25:57 +02001314#endif /* HAVE_SYS_SOCKET_H */
Harald Welteba6988b2011-08-17 12:46:48 +02001315
Sylvain Munautdca7d2c2012-04-18 21:53:23 +02001316/*! @} */