blob: 3c2ba501d500005b4afcca9b58a3cdf7d92960f8 [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 *
Harald Welte468b6432014-09-11 13:05:51 +080018 */
19
Pau Espin Pedrol88955fb2023-01-18 18:54:00 +010020#include "config.h"
Harald Welte33cb71a2011-05-21 18:54:32 +020021
Harald Welteba6988b2011-08-17 12:46:48 +020022/*! \addtogroup socket
23 * @{
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020024 * Osmocom socket convenience functions.
25 *
26 * \file socket.c */
Harald Welte96e2a002017-06-12 21:44:18 +020027
Harald Weltee4764422011-05-22 12:25:57 +020028#ifdef HAVE_SYS_SOCKET_H
29
Harald Welte33cb71a2011-05-21 18:54:32 +020030#include <osmocom/core/logging.h>
31#include <osmocom/core/select.h>
32#include <osmocom/core/socket.h>
Alexander Couzens43957e62020-08-01 21:56:45 +020033#include <osmocom/core/sockaddr_str.h>
Harald Welte48f55832017-01-26 00:03:10 +010034#include <osmocom/core/talloc.h>
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +020035#include <osmocom/core/utils.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020036
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +020037#include <sys/ioctl.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020038#include <sys/socket.h>
39#include <sys/types.h>
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +010040#include <sys/un.h>
Harald Welte44b99262020-03-07 14:59:05 +010041#include <net/if.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020042
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010043#include <netinet/in.h>
Harald Weltee30d7e62017-07-13 16:02:50 +020044#include <arpa/inet.h>
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010045
Harald Welte33cb71a2011-05-21 18:54:32 +020046#include <stdio.h>
47#include <unistd.h>
48#include <stdint.h>
49#include <string.h>
50#include <errno.h>
51#include <netdb.h>
52#include <ifaddrs.h>
53
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +020054#ifdef HAVE_LIBSCTP
55#include <netinet/sctp.h>
56#endif
57
Harald Weltedda70fc2017-04-08 20:52:33 +020058static struct addrinfo *addrinfo_helper(uint16_t family, uint16_t type, uint8_t proto,
59 const char *host, uint16_t port, bool passive)
60{
Pau Espin Pedrolff428522019-10-10 17:38:16 +020061 struct addrinfo hints, *result, *rp;
Oliver Smith860651e2018-10-30 14:31:57 +010062 char portbuf[6];
Harald Weltedda70fc2017-04-08 20:52:33 +020063 int rc;
64
65 snprintf(portbuf, sizeof(portbuf), "%u", port);
66 memset(&hints, 0, sizeof(struct addrinfo));
67 hints.ai_family = family;
68 if (type == SOCK_RAW) {
69 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
70 * SOCK_RAW and IPPROTO_GRE is used.
Pau Espin Pedrolff428522019-10-10 17:38:16 +020071 * http://sourceware.org/bugzilla/show_bug.cgi?id=15015
Harald Weltedda70fc2017-04-08 20:52:33 +020072 */
73 hints.ai_socktype = SOCK_DGRAM;
74 hints.ai_protocol = IPPROTO_UDP;
75 } else {
76 hints.ai_socktype = type;
77 hints.ai_protocol = proto;
78 }
Pau Espin Pedrol3119d472020-08-25 12:30:55 +020079
Harald Weltedda70fc2017-04-08 20:52:33 +020080 if (passive)
81 hints.ai_flags |= AI_PASSIVE;
82
83 rc = getaddrinfo(host, portbuf, &hints, &result);
84 if (rc != 0) {
Pau Espin Pedrolba828c32020-08-20 18:28:10 +020085 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo(%s, %u) failed: %s\n",
86 host, port, gai_strerror(rc));
Harald Weltedda70fc2017-04-08 20:52:33 +020087 return NULL;
88 }
89
Pau Espin Pedrolff428522019-10-10 17:38:16 +020090 for (rp = result; rp != NULL; rp = rp->ai_next) {
91 /* Workaround for glibc again */
92 if (type == SOCK_RAW) {
93 rp->ai_socktype = SOCK_RAW;
94 rp->ai_protocol = proto;
95 }
96 }
97
Harald Weltedda70fc2017-04-08 20:52:33 +020098 return result;
99}
100
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200101#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200102/*! Retrieve an array of addrinfo with specified hints, one for each host in the hosts array.
103 * \param[out] addrinfo array of addrinfo pointers, will be filled by the function on success.
104 * Its size must be at least the one of hosts.
105 * \param[in] family Socket family like AF_INET, AF_INET6.
106 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM.
107 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP.
108 * \param[in] hosts array of char pointers (strings) containing the addresses to query.
109 * \param[in] host_cnt length of the hosts array (in items).
110 * \param[in] port port number in host byte order.
111 * \param[in] passive whether to include the AI_PASSIVE flag in getaddrinfo() hints.
112 * \returns 0 is returned on success together with a filled addrinfo array; negative on error
113 */
114static int addrinfo_helper_multi(struct addrinfo **addrinfo, uint16_t family, uint16_t type, uint8_t proto,
115 const char **hosts, size_t host_cnt, uint16_t port, bool passive)
116{
Harald Welte0b08d512022-01-09 12:03:12 +0100117 unsigned int i, j;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200118
119 for (i = 0; i < host_cnt; i++) {
120 addrinfo[i] = addrinfo_helper(family, type, proto, hosts[i], port, passive);
121 if (!addrinfo[i]) {
122 for (j = 0; j < i; j++)
123 freeaddrinfo(addrinfo[j]);
124 return -EINVAL;
125 }
126 }
127 return 0;
128}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200129#endif /* HAVE_LIBSCTP*/
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200130
Harald Weltefaf6b702021-04-28 13:04:59 +0200131static int socket_helper_tail(int sfd, unsigned int flags)
132{
Harald Weltec545ff62021-04-28 13:09:49 +0200133 int rc, on = 1;
134 uint8_t dscp = GET_OSMO_SOCK_F_DSCP(flags);
135 uint8_t prio = GET_OSMO_SOCK_F_PRIO(flags);
Harald Weltefaf6b702021-04-28 13:04:59 +0200136
137 if (flags & OSMO_SOCK_F_NONBLOCK) {
138 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
139 LOGP(DLGLOBAL, LOGL_ERROR,
140 "cannot set this socket unblocking: %s\n",
141 strerror(errno));
142 close(sfd);
143 return -EINVAL;
144 }
145 }
146
Harald Weltec545ff62021-04-28 13:09:49 +0200147 if (dscp) {
148 rc = osmo_sock_set_dscp(sfd, dscp);
149 if (rc) {
150 LOGP(DLGLOBAL, LOGL_ERROR, "cannot set IP DSCP of socket to %u: %s\n",
151 dscp, strerror(errno));
152 /* we consider this a non-fatal error */
153 }
154 }
155
156 if (prio) {
157 rc = osmo_sock_set_priority(sfd, prio);
158 if (rc) {
159 LOGP(DLGLOBAL, LOGL_ERROR, "cannot set priority of socket to %u: %s\n",
160 prio, strerror(errno));
161 /* we consider this a non-fatal error */
162 }
163 }
164
Harald Weltefaf6b702021-04-28 13:04:59 +0200165 return 0;
166}
167
Harald Weltedda70fc2017-04-08 20:52:33 +0200168static int socket_helper(const struct addrinfo *rp, unsigned int flags)
169{
Harald Weltefaf6b702021-04-28 13:04:59 +0200170 int sfd, rc;
Harald Weltedda70fc2017-04-08 20:52:33 +0200171
172 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200173 if (sfd == -1) {
174 LOGP(DLGLOBAL, LOGL_ERROR,
175 "unable to create socket: %s\n", strerror(errno));
Harald Weltedda70fc2017-04-08 20:52:33 +0200176 return sfd;
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200177 }
Harald Weltefaf6b702021-04-28 13:04:59 +0200178
179 rc = socket_helper_tail(sfd, flags);
180 if (rc < 0)
181 return rc;
182
Harald Weltedda70fc2017-04-08 20:52:33 +0200183 return sfd;
184}
185
Alexander Couzens43957e62020-08-01 21:56:45 +0200186static int socket_helper_osa(const struct osmo_sockaddr *addr, uint16_t type, uint8_t proto, unsigned int flags)
187{
Harald Weltefaf6b702021-04-28 13:04:59 +0200188 int sfd, rc;
Alexander Couzens43957e62020-08-01 21:56:45 +0200189
190 sfd = socket(addr->u.sa.sa_family, type, proto);
191 if (sfd == -1) {
192 LOGP(DLGLOBAL, LOGL_ERROR,
193 "unable to create socket: %s\n", strerror(errno));
194 return sfd;
195 }
Harald Weltefaf6b702021-04-28 13:04:59 +0200196
197 rc = socket_helper_tail(sfd, flags);
198 if (rc < 0)
199 return rc;
200
Alexander Couzens43957e62020-08-01 21:56:45 +0200201 return sfd;
202}
203
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200204#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200205/* Fill buf with a string representation of the address set, in the form:
206 * buf_len == 0: "()"
207 * buf_len == 1: "hostA"
208 * buf_len >= 2: (hostA|hostB|...|...)
209 */
210static int multiaddr_snprintf(char* buf, size_t buf_len, const char **hosts, size_t host_cnt)
211{
212 int len = 0, offset = 0, rem = buf_len;
Harald Welte0b08d512022-01-09 12:03:12 +0100213 size_t i;
214 int ret;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200215 char *after;
216
217 if (buf_len < 3)
218 return -EINVAL;
219
220 if (host_cnt != 1) {
221 ret = snprintf(buf, rem, "(");
222 if (ret < 0)
223 return ret;
224 OSMO_SNPRINTF_RET(ret, rem, offset, len);
225 }
226 for (i = 0; i < host_cnt; i++) {
227 if (host_cnt == 1)
228 after = "";
229 else
230 after = (i == (host_cnt - 1)) ? ")" : "|";
231 ret = snprintf(buf + offset, rem, "%s%s", hosts[i] ? : "0.0.0.0", after);
232 OSMO_SNPRINTF_RET(ret, rem, offset, len);
233 }
234
235 return len;
236}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200237#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200238
Harald Weltec47bbda2017-07-13 16:13:26 +0200239static int osmo_sock_init_tail(int fd, uint16_t type, unsigned int flags)
240{
Harald Weltebc43a622017-07-13 16:20:21 +0200241 int rc;
Harald Weltec47bbda2017-07-13 16:13:26 +0200242
243 /* Make sure to call 'listen' on a bound, connection-oriented sock */
244 if ((flags & (OSMO_SOCK_F_BIND|OSMO_SOCK_F_CONNECT)) == OSMO_SOCK_F_BIND) {
245 switch (type) {
246 case SOCK_STREAM:
247 case SOCK_SEQPACKET:
248 rc = listen(fd, 10);
Harald Weltebc43a622017-07-13 16:20:21 +0200249 if (rc < 0) {
250 LOGP(DLGLOBAL, LOGL_ERROR, "unable to listen on socket: %s\n",
251 strerror(errno));
Maxdb7cb692023-02-11 21:35:21 +0300252 return -errno;
Harald Weltebc43a622017-07-13 16:20:21 +0200253 }
254 break;
Harald Weltec47bbda2017-07-13 16:13:26 +0200255 }
256 }
257
Harald Weltebc43a622017-07-13 16:20:21 +0200258 if (flags & OSMO_SOCK_F_NO_MCAST_LOOP) {
259 rc = osmo_sock_mcast_loop_set(fd, false);
260 if (rc < 0) {
261 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable multicast loop: %s\n",
262 strerror(errno));
263 return rc;
264 }
265 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200266
Harald Welte37d204a2017-07-13 16:33:16 +0200267 if (flags & OSMO_SOCK_F_NO_MCAST_ALL) {
268 rc = osmo_sock_mcast_all_set(fd, false);
269 if (rc < 0) {
270 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable receive of all multicast: %s\n",
271 strerror(errno));
272 /* do not abort here, as this is just an
273 * optional additional optimization that only
274 * exists on Linux only */
275 }
276 }
Harald Weltebc43a622017-07-13 16:20:21 +0200277 return 0;
Harald Weltec47bbda2017-07-13 16:13:26 +0200278}
279
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200280/*! Initialize a socket (including bind and/or connect)
Harald Weltedda70fc2017-04-08 20:52:33 +0200281 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
282 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
283 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
284 * \param[in] local_host local host name or IP address in string form
285 * \param[in] local_port local port number in host byte order
286 * \param[in] remote_host remote host name or IP address in string form
287 * \param[in] remote_port remote port number in host byte order
288 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
289 * \returns socket file descriptor on success; negative on error
290 *
291 * This function creates a new socket of the designated \a family, \a
292 * type and \a proto and optionally binds it to the \a local_host and \a
293 * local_port as well as optionally connects it to the \a remote_host
294 * and \q remote_port, depending on the value * of \a flags parameter.
295 *
296 * As opposed to \ref osmo_sock_init(), this function allows to combine
297 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
298 * is useful if you want to connect to a remote host/port, but still
299 * want to bind that socket to either a specific local alias IP and/or a
300 * specific local source port.
301 *
302 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
303 * OSMO_SOCK_F_CONNECT, or both.
304 *
305 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
306 * non-blocking mode.
307 */
308int osmo_sock_init2(uint16_t family, uint16_t type, uint8_t proto,
309 const char *local_host, uint16_t local_port,
310 const char *remote_host, uint16_t remote_port, unsigned int flags)
311{
Alexander Couzens2c962f52020-06-03 00:28:02 +0200312 struct addrinfo *local = NULL, *remote = NULL, *rp;
Harald Weltedda70fc2017-04-08 20:52:33 +0200313 int sfd = -1, rc, on = 1;
314
Alexander Couzens2c962f52020-06-03 00:28:02 +0200315 bool local_ipv4 = false, local_ipv6 = false;
316 bool remote_ipv4 = false, remote_ipv6 = false;
317
Harald Weltedda70fc2017-04-08 20:52:33 +0200318 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
319 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
320 "BIND or CONNECT flags\n");
321 return -EINVAL;
322 }
323
Alexander Couzens2c962f52020-06-03 00:28:02 +0200324 /* figure out local address infos */
325 if (flags & OSMO_SOCK_F_BIND) {
326 local = addrinfo_helper(family, type, proto, local_host, local_port, true);
327 if (!local)
328 return -EINVAL;
329 }
330
331 /* figure out remote address infos */
332 if (flags & OSMO_SOCK_F_CONNECT) {
333 remote = addrinfo_helper(family, type, proto, remote_host, remote_port, false);
334 if (!remote) {
335 if (local)
336 freeaddrinfo(local);
337
338 return -EINVAL;
339 }
340 }
341
342 /* It must do a full run to ensure AF_UNSPEC does not fail.
343 * In case first local valid entry is IPv4 and only remote valid entry
344 * is IPv6 or vice versa */
345 if (family == AF_UNSPEC) {
346 for (rp = local; rp != NULL; rp = rp->ai_next) {
347 switch (rp->ai_family) {
348 case AF_INET:
349 local_ipv4 = true;
350 break;
351 case AF_INET6:
352 local_ipv6 = true;
353 break;
354 }
355 }
356
357 for (rp = remote; rp != NULL; rp = rp->ai_next) {
358 switch (rp->ai_family) {
359 case AF_INET:
360 remote_ipv4 = true;
361 break;
362 case AF_INET6:
363 remote_ipv6 = true;
364 break;
365 }
366 }
367
Pau Espin Pedrold8cf52b2020-08-31 19:00:59 +0200368 if ((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) {
369 /* prioritize ipv6 as per RFC */
370 if (local_ipv6 && remote_ipv6)
371 family = AF_INET6;
372 else if (local_ipv4 && remote_ipv4)
373 family = AF_INET;
374 else {
375 if (local)
376 freeaddrinfo(local);
377 if (remote)
378 freeaddrinfo(remote);
379 LOGP(DLGLOBAL, LOGL_ERROR,
380 "Unable to find a common protocol (IPv4 or IPv6) "
381 "for local host: %s and remote host: %s.\n",
382 local_host, remote_host);
383 return -ENODEV;
384 }
385 } else if ((flags & OSMO_SOCK_F_BIND)) {
386 family = local_ipv6 ? AF_INET6 : AF_INET;
387 } else if ((flags & OSMO_SOCK_F_CONNECT)) {
388 family = remote_ipv6 ? AF_INET6 : AF_INET;
Alexander Couzens2c962f52020-06-03 00:28:02 +0200389 }
390 }
391
Harald Weltedda70fc2017-04-08 20:52:33 +0200392 /* figure out local side of socket */
393 if (flags & OSMO_SOCK_F_BIND) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200394 for (rp = local; rp != NULL; rp = rp->ai_next) {
395 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
396 if (rp->ai_family != family)
397 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200398
Harald Weltedda70fc2017-04-08 20:52:33 +0200399 sfd = socket_helper(rp, flags);
400 if (sfd < 0)
401 continue;
402
Philipp Maier73196e72018-08-23 20:11:50 +0200403 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200404 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
405 &on, sizeof(on));
406 if (rc < 0) {
407 LOGP(DLGLOBAL, LOGL_ERROR,
408 "cannot setsockopt socket:"
409 " %s:%u: %s\n",
410 local_host, local_port,
411 strerror(errno));
412 close(sfd);
413 continue;
414 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200415 }
Philipp Maier99f706d2018-08-01 12:40:36 +0200416
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200417 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
418 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
419 local_host, local_port, strerror(errno));
420 close(sfd);
421 continue;
422 }
423 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200424 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200425
426 freeaddrinfo(local);
Harald Weltedda70fc2017-04-08 20:52:33 +0200427 if (rp == NULL) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200428 if (remote)
429 freeaddrinfo(remote);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200430 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
431 local_host, local_port);
Harald Weltedda70fc2017-04-08 20:52:33 +0200432 return -ENODEV;
433 }
434 }
435
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200436 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
437 was already closed and func returned. If OSMO_SOCK_F_BIND is not
438 set, then sfd = -1 */
439
Harald Weltedda70fc2017-04-08 20:52:33 +0200440 /* figure out remote side of socket */
441 if (flags & OSMO_SOCK_F_CONNECT) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200442 for (rp = remote; rp != NULL; rp = rp->ai_next) {
443 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
444 if (rp->ai_family != family)
445 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200446
Harald Welte5cfa6dc2017-07-21 16:52:29 +0200447 if (sfd < 0) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200448 sfd = socket_helper(rp, flags);
449 if (sfd < 0)
450 continue;
451 }
452
453 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200454 if (rc != 0 && errno != EINPROGRESS) {
455 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
456 remote_host, remote_port, strerror(errno));
457 /* We want to maintain the bind socket if bind was enabled */
458 if (!(flags & OSMO_SOCK_F_BIND)) {
459 close(sfd);
460 sfd = -1;
461 }
462 continue;
463 }
464 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200465 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200466
467 freeaddrinfo(remote);
Harald Weltedda70fc2017-04-08 20:52:33 +0200468 if (rp == NULL) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200469 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable remote addr found for: %s:%u\n",
470 remote_host, remote_port);
471 if (sfd >= 0)
472 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200473 return -ENODEV;
474 }
475 }
476
Harald Weltec47bbda2017-07-13 16:13:26 +0200477 rc = osmo_sock_init_tail(sfd, type, flags);
478 if (rc < 0) {
479 close(sfd);
480 sfd = -1;
Harald Weltedda70fc2017-04-08 20:52:33 +0200481 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200482
Harald Weltedda70fc2017-04-08 20:52:33 +0200483 return sfd;
484}
485
Alexander Couzens43957e62020-08-01 21:56:45 +0200486#define _SOCKADDR_TO_STR(dest, sockaddr) do { \
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100487 if (osmo_sockaddr_str_from_sockaddr(dest, &sockaddr->u.sas)) \
488 osmo_strlcpy((dest)->ip, "Invalid IP", 11); \
Alexander Couzens43957e62020-08-01 21:56:45 +0200489 } while (0)
490
491/*! Initialize a socket (including bind and/or connect)
492 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
493 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
494 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
495 * \param[in] local local address
496 * \param[in] remote remote address
497 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
498 * \returns socket file descriptor on success; negative on error
499 *
500 * This function creates a new socket of the
501 * \a type and \a proto and optionally binds it to the \a local
502 * as well as optionally connects it to the \a remote
503 * depending on the value * of \a flags parameter.
504 *
505 * As opposed to \ref osmo_sock_init(), this function allows to combine
506 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
507 * is useful if you want to connect to a remote host/port, but still
508 * want to bind that socket to either a specific local alias IP and/or a
509 * specific local source port.
510 *
511 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
512 * OSMO_SOCK_F_CONNECT, or both.
513 *
514 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
515 * non-blocking mode.
516 */
517int osmo_sock_init_osa(uint16_t type, uint8_t proto,
518 const struct osmo_sockaddr *local,
519 const struct osmo_sockaddr *remote,
520 unsigned int flags)
521{
522 int sfd = -1, rc, on = 1;
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100523 struct osmo_sockaddr_str _sastr = {};
524 struct osmo_sockaddr_str *sastr = &_sastr;
Alexander Couzens43957e62020-08-01 21:56:45 +0200525
526 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
527 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
528 "BIND or CONNECT flags\n");
529 return -EINVAL;
530 }
531
532 if ((flags & OSMO_SOCK_F_BIND) && !local) {
533 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot BIND when local is NULL\n");
534 return -EINVAL;
535 }
536
537 if ((flags & OSMO_SOCK_F_CONNECT) && !remote) {
538 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot CONNECT when remote is NULL\n");
539 return -EINVAL;
540 }
541
542 if ((flags & OSMO_SOCK_F_BIND) &&
543 (flags & OSMO_SOCK_F_CONNECT) &&
544 local->u.sa.sa_family != remote->u.sa.sa_family) {
545 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: the family for "
546 "local and remote endpoint must be same.\n");
547 return -EINVAL;
548 }
549
550 /* figure out local side of socket */
551 if (flags & OSMO_SOCK_F_BIND) {
552 sfd = socket_helper_osa(local, type, proto, flags);
553 if (sfd < 0) {
554 _SOCKADDR_TO_STR(sastr, local);
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100555 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: " OSMO_SOCKADDR_STR_FMT "\n",
556 OSMO_SOCKADDR_STR_FMT_ARGS(sastr));
Alexander Couzens43957e62020-08-01 21:56:45 +0200557 return -ENODEV;
558 }
559
560 if (proto != IPPROTO_UDP || (flags & OSMO_SOCK_F_UDP_REUSEADDR)) {
561 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
562 &on, sizeof(on));
563 if (rc < 0) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200564 int err = errno;
Alexander Couzens43957e62020-08-01 21:56:45 +0200565 _SOCKADDR_TO_STR(sastr, local);
566 LOGP(DLGLOBAL, LOGL_ERROR,
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100567 "cannot setsockopt socket: " OSMO_SOCKADDR_STR_FMT ": %s\n",
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200568 OSMO_SOCKADDR_STR_FMT_ARGS(sastr), strerror(err));
Alexander Couzens43957e62020-08-01 21:56:45 +0200569 close(sfd);
570 return rc;
571 }
572 }
573
574 if (bind(sfd, &local->u.sa, sizeof(struct osmo_sockaddr)) == -1) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200575 int err = errno;
Alexander Couzens43957e62020-08-01 21:56:45 +0200576 _SOCKADDR_TO_STR(sastr, local);
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100577 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: " OSMO_SOCKADDR_STR_FMT ": %s\n",
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200578 OSMO_SOCKADDR_STR_FMT_ARGS(sastr), strerror(err));
Alexander Couzens43957e62020-08-01 21:56:45 +0200579 close(sfd);
580 return -1;
581 }
582 }
583
584 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
585 was already closed and func returned. If OSMO_SOCK_F_BIND is not
586 set, then sfd = -1 */
587
588 /* figure out remote side of socket */
589 if (flags & OSMO_SOCK_F_CONNECT) {
590 if (sfd < 0) {
591 sfd = socket_helper_osa(remote, type, proto, flags);
592 if (sfd < 0) {
593 return sfd;
594 }
595 }
596
597 rc = connect(sfd, &remote->u.sa, sizeof(struct osmo_sockaddr));
598 if (rc != 0 && errno != EINPROGRESS) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200599 int err = errno;
Alexander Couzens43957e62020-08-01 21:56:45 +0200600 _SOCKADDR_TO_STR(sastr, remote);
Neels Hofmeyrf3270f22021-12-17 14:21:29 +0100601 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: " OSMO_SOCKADDR_STR_FMT ": %s\n",
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200602 OSMO_SOCKADDR_STR_FMT_ARGS(sastr), strerror(err));
Alexander Couzens43957e62020-08-01 21:56:45 +0200603 close(sfd);
604 return rc;
605 }
606 }
607
608 rc = osmo_sock_init_tail(sfd, type, flags);
609 if (rc < 0) {
610 close(sfd);
611 sfd = -1;
612 }
613
614 return sfd;
615}
616
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200617#ifdef HAVE_LIBSCTP
618
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200619/* Check whether there's an IPv6 Addr as first option of any addrinfo item in the addrinfo set */
620static void addrinfo_has_v4v6addr(const struct addrinfo **result, size_t result_count, bool *has_v4, bool *has_v6)
621{
622 size_t host_idx;
623 *has_v4 = false;
624 *has_v6 = false;
625
626 for (host_idx = 0; host_idx < result_count; host_idx++) {
627 if (result[host_idx]->ai_family == AF_INET)
628 *has_v4 = true;
629 else if (result[host_idx]->ai_family == AF_INET6)
630 *has_v6 = true;
631 }
632}
633
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200634/* Check whether there's an IPv6 with IN6ADDR_ANY_INIT ("::") */
635static bool addrinfo_has_in6addr_any(const struct addrinfo **result, size_t result_count)
636{
637 size_t host_idx;
638 struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
639
640 for (host_idx = 0; host_idx < result_count; host_idx++) {
641 if (result[host_idx]->ai_family != AF_INET6)
642 continue;
643 if (memcmp(&((struct sockaddr_in6 *)result[host_idx]->ai_addr)->sin6_addr,
644 &in6addr_any, sizeof(in6addr_any)) == 0)
645 return true;
646 }
647 return false;
648}
649
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200650static int socket_helper_multiaddr(uint16_t family, uint16_t type, uint8_t proto, unsigned int flags)
651{
Harald Weltefaf6b702021-04-28 13:04:59 +0200652 int sfd, rc;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200653
654 sfd = socket(family, type, proto);
655 if (sfd == -1) {
656 LOGP(DLGLOBAL, LOGL_ERROR,
657 "Unable to create socket: %s\n", strerror(errno));
658 return sfd;
659 }
Harald Weltefaf6b702021-04-28 13:04:59 +0200660
661 rc = socket_helper_tail(sfd, flags);
662 if (rc < 0)
663 return rc;
664
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200665 return sfd;
666}
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200667
668/* Build array of addresses taking first addrinfo result of the requested family
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200669 * for each host in addrs_buf. */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200670static int addrinfo_to_sockaddr(uint16_t family, const struct addrinfo **result,
Harald Welte0b08d512022-01-09 12:03:12 +0100671 const char **hosts, unsigned int host_cont,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200672 uint8_t *addrs_buf, size_t addrs_buf_len) {
673 size_t host_idx, offset = 0;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200674 const struct addrinfo *rp;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200675
676 for (host_idx = 0; host_idx < host_cont; host_idx++) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200677 /* Addresses are ordered based on RFC 3484, see man getaddrinfo */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200678 for (rp = result[host_idx]; rp != NULL; rp = rp->ai_next) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200679 if (family != AF_UNSPEC && rp->ai_family != family)
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200680 continue;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200681 if (offset + rp->ai_addrlen > addrs_buf_len) {
682 LOGP(DLGLOBAL, LOGL_ERROR, "Output buffer to small: %zu\n",
683 addrs_buf_len);
684 return -ENOSPC;
685 }
686 memcpy(addrs_buf + offset, rp->ai_addr, rp->ai_addrlen);
687 offset += rp->ai_addrlen;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200688 break;
689 }
690 if (!rp) { /* No addr could be bound for this host! */
691 LOGP(DLGLOBAL, LOGL_ERROR, "No suitable remote address found for host: %s\n",
692 hosts[host_idx]);
693 return -ENODEV;
694 }
695 }
696 return 0;
697}
698
Pau Espin Pedrole83227f2023-08-08 19:32:56 +0200699static int setsockopt_sctp_auth_supported(int fd)
700{
701#ifdef SCTP_AUTH_SUPPORTED
702 struct sctp_assoc_value assoc_val = {
703 .assoc_id = SCTP_FUTURE_ASSOC,
704 .assoc_value = 1,
705 };
706 return setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_SUPPORTED, &assoc_val, sizeof(assoc_val));
707#else
708#pragma message "setsockopt(SCTP_AUTH_SUPPORTED) not supported! some SCTP features may not be available!"
709 LOGP(DLGLOBAL, LOGL_NOTICE, "Built without support for setsockopt(SCTP_AUTH_SUPPORTED), skipping\n");
710 return 0;
711#endif
712}
713
714static int setsockopt_sctp_asconf_supported(int fd)
715{
716#ifdef SCTP_ASCONF_SUPPORTED
717 struct sctp_assoc_value assoc_val = {
718 .assoc_id = SCTP_FUTURE_ASSOC,
719 .assoc_value = 1,
720 };
721 return setsockopt(fd, IPPROTO_SCTP, SCTP_ASCONF_SUPPORTED, &assoc_val, sizeof(assoc_val));
722#else
723#pragma message "setsockopt(SCTP_ASCONF_SUPPORTED) not supported! some SCTP features may not be available!"
724 LOGP(DLGLOBAL, LOGL_NOTICE, "Built without support for setsockopt(SCTP_ASCONF_SUPPORTED), skipping\n");
725 return 0;
726#endif
727}
728
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200729/*! Initialize a socket (including bind and/or connect) with multiple local or remote addresses.
730 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
731 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
732 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
733 * \param[in] local_hosts array of char pointers (strings), each containing local host name or IP address in string form
734 * \param[in] local_hosts_cnt length of local_hosts (in items)
735 * \param[in] local_port local port number in host byte order
736 * \param[in] remote_host array of char pointers (strings), each containing remote host name or IP address in string form
737 * \param[in] remote_hosts_cnt length of remote_hosts (in items)
738 * \param[in] remote_port remote port number in host byte order
739 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
740 * \returns socket file descriptor on success; negative on error
741 *
742 * This function is similar to \ref osmo_sock_init2(), but can be passed an
743 * array of local or remote addresses for protocols supporting multiple
744 * addresses per socket, like SCTP (currently only one supported). This function
745 * should not be used by protocols not supporting this kind of features, but
746 * rather \ref osmo_sock_init2() should be used instead.
747 * See \ref osmo_sock_init2() for more information on flags and general behavior.
748 */
749int osmo_sock_init2_multiaddr(uint16_t family, uint16_t type, uint8_t proto,
750 const char **local_hosts, size_t local_hosts_cnt, uint16_t local_port,
751 const char **remote_hosts, size_t remote_hosts_cnt, uint16_t remote_port,
752 unsigned int flags)
753
754{
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200755 struct addrinfo *res_loc[OSMO_SOCK_MAX_ADDRS], *res_rem[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200756 int sfd = -1, rc, on = 1;
Harald Welte0b08d512022-01-09 12:03:12 +0100757 unsigned int i;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200758 bool loc_has_v4addr, rem_has_v4addr;
759 bool loc_has_v6addr, rem_has_v6addr;
760 struct sockaddr_in6 addrs_buf[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200761 char strbuf[512];
762
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200763 /* updated later in case of AF_UNSPEC */
764 loc_has_v4addr = rem_has_v4addr = (family == AF_INET);
765 loc_has_v6addr = rem_has_v6addr = (family == AF_INET6);
766
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200767 /* TODO: So far this function is only aimed for SCTP, but could be
768 reused in the future for other protocols with multi-addr support */
769 if (proto != IPPROTO_SCTP)
770 return -ENOTSUP;
771
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200772 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
773 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
774 "BIND or CONNECT flags\n");
775 return -EINVAL;
776 }
777
778 if (((flags & OSMO_SOCK_F_BIND) && !local_hosts_cnt) ||
779 ((flags & OSMO_SOCK_F_CONNECT) && !remote_hosts_cnt) ||
780 local_hosts_cnt > OSMO_SOCK_MAX_ADDRS ||
781 remote_hosts_cnt > OSMO_SOCK_MAX_ADDRS)
782 return -EINVAL;
783
784 /* figure out local side of socket */
785 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200786 rc = addrinfo_helper_multi(res_loc, family, type, proto, local_hosts,
787 local_hosts_cnt, local_port, true);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200788 if (rc < 0)
789 return -EINVAL;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200790 /* Figure out if there's any IPV4 or IPv6 addr in the set */
791 if (family == AF_UNSPEC)
792 addrinfo_has_v4v6addr((const struct addrinfo **)res_loc, local_hosts_cnt,
793 &loc_has_v4addr, &loc_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200794 }
795 /* figure out remote side of socket */
796 if (flags & OSMO_SOCK_F_CONNECT) {
797 rc = addrinfo_helper_multi(res_rem, family, type, proto, remote_hosts,
798 remote_hosts_cnt, remote_port, false);
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200799 if (rc < 0) {
800 rc = -EINVAL;
801 goto ret_freeaddrinfo_loc;
802 }
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200803 /* Figure out if there's any IPv4 or IPv6 addr in the set */
804 if (family == AF_UNSPEC)
805 addrinfo_has_v4v6addr((const struct addrinfo **)res_rem, remote_hosts_cnt,
806 &rem_has_v4addr, &rem_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200807 }
808
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200809 if (((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) &&
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200810 !addrinfo_has_in6addr_any((const struct addrinfo **)res_loc, local_hosts_cnt) &&
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200811 (loc_has_v4addr != rem_has_v4addr || loc_has_v6addr != rem_has_v6addr)) {
Neels Hofmeyr5761c442020-09-22 00:24:06 +0000812 LOGP(DLGLOBAL, LOGL_ERROR, "Invalid v4 vs v6 in local vs remote addresses: "
813 "local:%s%s remote:%s%s\n",
814 loc_has_v4addr ? " v4" : "", loc_has_v6addr ? " v6" : "",
815 rem_has_v4addr ? " v4" : "", rem_has_v6addr ? " v6" : ""
816 );
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200817 rc = -EINVAL;
818 goto ret_freeaddrinfo;
819 }
820
821 sfd = socket_helper_multiaddr(loc_has_v6addr ? AF_INET6 : AF_INET,
822 type, proto, flags);
823 if (sfd < 0) {
824 rc = sfd;
825 goto ret_freeaddrinfo;
826 }
827
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200828 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200829 /* Since so far we only allow IPPROTO_SCTP in this function,
830 no need to check below for "proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR" */
831 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
832 &on, sizeof(on));
833 if (rc < 0) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200834 int err = errno;
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200835 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
836 LOGP(DLGLOBAL, LOGL_ERROR,
837 "cannot setsockopt socket:"
838 " %s:%u: %s\n",
839 strbuf, local_port,
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200840 strerror(err));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200841 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200842 }
843
Pau Espin Pedrole83227f2023-08-08 19:32:56 +0200844 if (flags & OSMO_SOCK_F_SCTP_ASCONF_SUPPORTED) {
845 /* RFC 5061 4.2.7: ASCONF also requires AUTH feature. */
846 rc = setsockopt_sctp_auth_supported(sfd);
847 if (rc < 0) {
848 int err = errno;
849 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
850 LOGP(DLGLOBAL, LOGL_ERROR,
851 "cannot setsockopt(SCTP_AUTH_SUPPORTED) socket: %s:%u: %s\n",
852 strbuf, local_port, strerror(err));
Pau Espin Pedrolb437f802023-08-28 13:56:25 +0200853 /* do not fail, some features such as Peer Primary Address won't be available
854 * unless configured system-wide through sysctl */
Pau Espin Pedrole83227f2023-08-08 19:32:56 +0200855 }
856
857 rc = setsockopt_sctp_asconf_supported(sfd);
858 if (rc < 0) {
859 int err = errno;
860 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
861 LOGP(DLGLOBAL, LOGL_ERROR,
862 "cannot setsockopt(SCTP_ASCONF_SUPPORTED) socket: %s:%u: %s\n",
863 strbuf, local_port, strerror(err));
Pau Espin Pedrolb437f802023-08-28 13:56:25 +0200864 /* do not fail, some features such as Peer Primary Address won't be available
865 * unless configured system-wide through sysctl */
Pau Espin Pedrole83227f2023-08-08 19:32:56 +0200866 }
867 }
868
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200869 /* Build array of addresses taking first entry for each host.
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200870 TODO: Ideally we should use backtracking storing last used
871 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200872 /* We could alternatively use v4v6 mapped addresses and call sctp_bindx once with an array od sockaddr_in6 */
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200873 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_loc,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200874 local_hosts, local_hosts_cnt,
875 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200876 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200877 rc = -ENODEV;
878 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200879 }
880
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200881 rc = sctp_bindx(sfd, (struct sockaddr *)addrs_buf, local_hosts_cnt, SCTP_BINDX_ADD_ADDR);
882 if (rc == -1) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200883 int err = errno;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200884 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
885 LOGP(DLGLOBAL, LOGL_NOTICE, "unable to bind socket: %s:%u: %s\n",
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200886 strbuf, local_port, strerror(err));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200887 rc = -ENODEV;
888 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200889 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200890 }
891
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200892 if (flags & OSMO_SOCK_F_CONNECT) {
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200893 /* Build array of addresses taking first of same family for each host.
894 TODO: Ideally we should use backtracking storing last used
895 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200896 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_rem,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200897 remote_hosts, remote_hosts_cnt,
898 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200899 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200900 rc = -ENODEV;
901 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200902 }
903
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200904 rc = sctp_connectx(sfd, (struct sockaddr *)addrs_buf, remote_hosts_cnt, NULL);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200905 if (rc != 0 && errno != EINPROGRESS) {
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200906 int err = errno;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200907 multiaddr_snprintf(strbuf, sizeof(strbuf), remote_hosts, remote_hosts_cnt);
908 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
Pau Espin Pedrolc3b772b2023-07-06 12:25:26 +0200909 strbuf, remote_port, strerror(err));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200910 rc = -ENODEV;
911 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200912 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200913 }
914
915 rc = osmo_sock_init_tail(sfd, type, flags);
916 if (rc < 0) {
917 close(sfd);
918 sfd = -1;
919 }
920
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200921 rc = sfd;
922 goto ret_freeaddrinfo;
923
924ret_close:
925 if (sfd >= 0)
926 close(sfd);
927ret_freeaddrinfo:
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200928 if (flags & OSMO_SOCK_F_CONNECT) {
929 for (i = 0; i < remote_hosts_cnt; i++)
930 freeaddrinfo(res_rem[i]);
931 }
932ret_freeaddrinfo_loc:
933 if (flags & OSMO_SOCK_F_BIND) {
934 for (i = 0; i < local_hosts_cnt; i++)
935 freeaddrinfo(res_loc[i]);
936 }
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200937 return rc;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200938}
939#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200940
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200941/*! Initialize a socket (including bind/connect)
Harald Welteba6988b2011-08-17 12:46:48 +0200942 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
943 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
944 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
945 * \param[in] host remote host name or IP address in string form
946 * \param[in] port remote port number in host byte order
947 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200948 * \returns socket file descriptor on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200949 *
950 * This function creates a new socket of the designated \a family, \a
951 * type and \a proto and optionally binds or connects it, depending on
952 * the value of \a flags parameter.
953 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200954int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200955 const char *host, uint16_t port, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200956{
Harald Weltedda70fc2017-04-08 20:52:33 +0200957 struct addrinfo *result, *rp;
Pau Espin Pedrol6fe865d2021-07-15 13:08:08 +0200958 int sfd = -1; /* initialize to avoid uninitialized false warnings on some gcc versions (11.1.0) */
959 int on = 1;
960 int rc;
Harald Welte33cb71a2011-05-21 18:54:32 +0200961
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200962 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200963 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100964 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: both bind and connect flags set:"
Neels Hofmeyrb7f191f2016-08-29 11:22:03 +0200965 " %s:%u\n", host, port);
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200966 return -EINVAL;
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200967 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200968
Harald Weltedda70fc2017-04-08 20:52:33 +0200969 result = addrinfo_helper(family, type, proto, host, port, flags & OSMO_SOCK_F_BIND);
Pau Espin Pedrolba828c32020-08-20 18:28:10 +0200970 if (!result)
Harald Welte33cb71a2011-05-21 18:54:32 +0200971 return -EINVAL;
Harald Welte33cb71a2011-05-21 18:54:32 +0200972
973 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200974 sfd = socket_helper(rp, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200975 if (sfd == -1)
976 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200977
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200978 if (flags & OSMO_SOCK_F_CONNECT) {
979 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200980 if (rc != 0 && errno != EINPROGRESS) {
981 close(sfd);
982 continue;
983 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200984 } else {
Philipp Maier73196e72018-08-23 20:11:50 +0200985 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200986 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
987 &on, sizeof(on));
988 if (rc < 0) {
989 LOGP(DLGLOBAL, LOGL_ERROR,
990 "cannot setsockopt socket:"
991 " %s:%u: %s\n",
992 host, port, strerror(errno));
993 close(sfd);
994 continue;
995 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200996 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200997 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
998 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket:"
999 "%s:%u: %s\n",
1000 host, port, strerror(errno));
1001 close(sfd);
1002 continue;
1003 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001004 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +02001005 break;
Harald Welte33cb71a2011-05-21 18:54:32 +02001006 }
1007 freeaddrinfo(result);
1008
1009 if (rp == NULL) {
Pau Espin Pedrol3a321472018-04-05 17:49:40 +02001010 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable addr found for: %s:%u\n",
1011 host, port);
Harald Welte33cb71a2011-05-21 18:54:32 +02001012 return -ENODEV;
1013 }
Harald Welte68b15742011-05-22 21:47:29 +02001014
Philipp Maier73196e72018-08-23 20:11:50 +02001015 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +02001016 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1017 if (rc < 0) {
1018 LOGP(DLGLOBAL, LOGL_ERROR,
1019 "cannot setsockopt socket: %s:%u: %s\n", host,
1020 port, strerror(errno));
1021 close(sfd);
1022 sfd = -1;
1023 }
Philipp Maier0659c5d2018-08-01 12:43:08 +02001024 }
Harald Welte68b15742011-05-22 21:47:29 +02001025
Harald Weltec47bbda2017-07-13 16:13:26 +02001026 rc = osmo_sock_init_tail(sfd, type, flags);
1027 if (rc < 0) {
1028 close(sfd);
1029 sfd = -1;
Harald Welte68b15742011-05-22 21:47:29 +02001030 }
Harald Weltec47bbda2017-07-13 16:13:26 +02001031
Harald Welte68b15742011-05-22 21:47:29 +02001032 return sfd;
1033}
1034
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001035/*! fill \ref osmo_fd for a give sfd
Max862ba652014-10-13 14:54:25 +02001036 * \param[out] ofd file descriptor (will be filled in)
1037 * \param[in] sfd socket file descriptor
Harald Welte24980ba2021-04-23 14:07:18 +02001038 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001039 * \returns socket fd on success; negative on error
Max862ba652014-10-13 14:54:25 +02001040 *
1041 * This function fills the \a ofd structure.
1042 */
Harald Welte24980ba2021-04-23 14:07:18 +02001043static inline int osmo_fd_init_ofd(struct osmo_fd *ofd, int sfd, unsigned int flags)
Max862ba652014-10-13 14:54:25 +02001044{
1045 int rc;
1046
1047 if (sfd < 0)
1048 return sfd;
1049
1050 ofd->fd = sfd;
Harald Welte16886992019-03-20 10:26:39 +01001051 ofd->when = OSMO_FD_READ;
Max862ba652014-10-13 14:54:25 +02001052
Harald Welte24980ba2021-04-23 14:07:18 +02001053 /* if we're doing a non-blocking connect, the completion will be signaled
1054 * by marking the fd as WRITE-able. So in this exceptional case, we're
1055 * also interested in when the socket becomes write-able */
1056 if ((flags & (OSMO_SOCK_F_CONNECT|OSMO_SOCK_F_NONBLOCK)) ==
1057 (OSMO_SOCK_F_CONNECT|OSMO_SOCK_F_NONBLOCK)) {
1058 ofd->when |= OSMO_FD_WRITE;
1059 }
1060
Max862ba652014-10-13 14:54:25 +02001061 rc = osmo_fd_register(ofd);
1062 if (rc < 0) {
1063 close(sfd);
1064 return rc;
1065 }
1066
1067 return sfd;
1068}
1069
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001070/*! Initialize a socket and fill \ref osmo_fd
Katerina Barone-Adesic28c6a02013-02-15 13:27:59 +01001071 * \param[out] ofd file descriptor (will be filled in)
Harald Welteba6988b2011-08-17 12:46:48 +02001072 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
1073 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1074 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1075 * \param[in] host remote host name or IP address in string form
1076 * \param[in] port remote port number in host byte order
1077 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001078 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +02001079 *
1080 * This function creates (and optionall binds/connects) a socket using
1081 * \ref osmo_sock_init, but also fills the \a ofd structure.
1082 */
Harald Welte68b15742011-05-22 21:47:29 +02001083int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001084 const char *host, uint16_t port, unsigned int flags)
Harald Welte68b15742011-05-22 21:47:29 +02001085{
Harald Welte24980ba2021-04-23 14:07:18 +02001086 return osmo_fd_init_ofd(ofd, osmo_sock_init(family, type, proto, host, port, flags), flags);
Harald Welte33cb71a2011-05-21 18:54:32 +02001087}
1088
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001089/*! Initialize a socket and fill \ref osmo_fd
Pau Espin Pedrol75989e62017-05-26 12:39:53 +02001090 * \param[out] ofd file descriptor (will be filled in)
1091 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
1092 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1093 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1094 * \param[in] local_host local host name or IP address in string form
1095 * \param[in] local_port local port number in host byte order
1096 * \param[in] remote_host remote host name or IP address in string form
1097 * \param[in] remote_port remote port number in host byte order
1098 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
1099 * \returns socket fd on success; negative on error
1100 *
1101 * This function creates (and optionall binds/connects) a socket using
1102 * \ref osmo_sock_init2, but also fills the \a ofd structure.
1103 */
1104int osmo_sock_init2_ofd(struct osmo_fd *ofd, int family, int type, int proto,
1105 const char *local_host, uint16_t local_port,
1106 const char *remote_host, uint16_t remote_port, unsigned int flags)
1107{
1108 return osmo_fd_init_ofd(ofd, osmo_sock_init2(family, type, proto, local_host,
Harald Welte24980ba2021-04-23 14:07:18 +02001109 local_port, remote_host, remote_port, flags), flags);
Pau Espin Pedrol75989e62017-05-26 12:39:53 +02001110}
1111
Alexander Couzens43957e62020-08-01 21:56:45 +02001112int osmo_sock_init_osa_ofd(struct osmo_fd *ofd, int type, int proto,
1113 const struct osmo_sockaddr *local,
1114 const struct osmo_sockaddr *remote, unsigned int flags)
1115{
Harald Welte24980ba2021-04-23 14:07:18 +02001116 return osmo_fd_init_ofd(ofd, osmo_sock_init_osa(type, proto, local, remote, flags), flags);
Alexander Couzens43957e62020-08-01 21:56:45 +02001117}
1118
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001119/*! Initialize a socket and fill \ref sockaddr
Harald Welteba6988b2011-08-17 12:46:48 +02001120 * \param[out] ss socket address (will be filled in)
1121 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1122 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1123 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001124 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +02001125 *
1126 * This function creates (and optionall binds/connects) a socket using
1127 * \ref osmo_sock_init, but also fills the \a ss structure.
1128 */
Harald Welte33cb71a2011-05-21 18:54:32 +02001129int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001130 uint8_t proto, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +02001131{
1132 char host[NI_MAXHOST];
1133 uint16_t port;
1134 struct sockaddr_in *sin;
1135 struct sockaddr_in6 *sin6;
1136 int s, sa_len;
1137
1138 /* determine port and host from ss */
1139 switch (ss->sa_family) {
1140 case AF_INET:
1141 sin = (struct sockaddr_in *) ss;
1142 sa_len = sizeof(struct sockaddr_in);
1143 port = ntohs(sin->sin_port);
1144 break;
1145 case AF_INET6:
1146 sin6 = (struct sockaddr_in6 *) ss;
1147 sa_len = sizeof(struct sockaddr_in6);
1148 port = ntohs(sin6->sin6_port);
1149 break;
1150 default:
1151 return -EINVAL;
1152 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001153
1154 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
1155 NULL, 0, NI_NUMERICHOST);
1156 if (s != 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001157 LOGP(DLGLOBAL, LOGL_ERROR, "getnameinfo failed:"
1158 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001159 return s;
1160 }
1161
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001162 return osmo_sock_init(ss->sa_family, type, proto, host, port, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +02001163}
1164
1165static int sockaddr_equal(const struct sockaddr *a,
Harald Weltee4764422011-05-22 12:25:57 +02001166 const struct sockaddr *b, unsigned int len)
Harald Welte33cb71a2011-05-21 18:54:32 +02001167{
1168 struct sockaddr_in *sin_a, *sin_b;
1169 struct sockaddr_in6 *sin6_a, *sin6_b;
1170
1171 if (a->sa_family != b->sa_family)
1172 return 0;
1173
1174 switch (a->sa_family) {
1175 case AF_INET:
1176 sin_a = (struct sockaddr_in *)a;
1177 sin_b = (struct sockaddr_in *)b;
1178 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
1179 sizeof(struct in_addr)))
1180 return 1;
1181 break;
1182 case AF_INET6:
1183 sin6_a = (struct sockaddr_in6 *)a;
1184 sin6_b = (struct sockaddr_in6 *)b;
1185 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
1186 sizeof(struct in6_addr)))
1187 return 1;
1188 break;
1189 }
1190 return 0;
1191}
1192
Eric8ae40cb2021-09-27 22:10:01 +02001193/* linux has a default route:
1194local 127.0.0.0/8 dev lo proto kernel scope host src 127.0.0.1
1195*/
1196static int sockaddr_is_local_routed(const struct sockaddr *a)
1197{
1198#if __linux__
1199 if (a->sa_family != AF_INET)
1200 return 0;
1201
1202 uint32_t address = ((struct sockaddr_in *)a)->sin_addr.s_addr; /* already BE */
1203 uint32_t eightmask = htonl(0xff000000); /* /8 mask */
1204 uint32_t local_prefix_127 = htonl(0x7f000000); /* 127.0.0.0 */
1205
1206 if ((address & eightmask) == local_prefix_127)
1207 return 1;
1208#endif
1209 return 0;
1210}
1211
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001212/*! Determine if the given address is a local address
Harald Welteba6988b2011-08-17 12:46:48 +02001213 * \param[in] addr Socket Address
1214 * \param[in] addrlen Length of socket address in bytes
1215 * \returns 1 if address is local, 0 otherwise.
1216 */
Harald Weltebc32d052012-04-08 11:31:32 +02001217int osmo_sockaddr_is_local(struct sockaddr *addr, unsigned int addrlen)
Harald Welte33cb71a2011-05-21 18:54:32 +02001218{
1219 struct ifaddrs *ifaddr, *ifa;
1220
Eric8ae40cb2021-09-27 22:10:01 +02001221 if (sockaddr_is_local_routed(addr))
1222 return 1;
1223
Harald Welte33cb71a2011-05-21 18:54:32 +02001224 if (getifaddrs(&ifaddr) == -1) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001225 LOGP(DLGLOBAL, LOGL_ERROR, "getifaddrs:"
1226 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001227 return -EIO;
1228 }
1229
1230 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
Harald Welte4d3a7b12011-05-24 21:31:53 +02001231 if (!ifa->ifa_addr)
1232 continue;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001233 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen)) {
1234 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001235 return 1;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001236 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001237 }
1238
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001239 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001240 return 0;
1241}
Harald Weltee4764422011-05-22 12:25:57 +02001242
Pau Espin Pedrol3b3955b2022-10-04 12:38:49 +02001243/*! Determine if the given address is an ANY address ("0.0.0.0", "::"). Port is not checked.
1244 * \param[in] addr Socket Address
1245 * \param[in] addrlen Length of socket address in bytes
1246 * \returns 1 if address is ANY, 0 otherwise. -1 is address family not supported/detected.
1247 */
1248int osmo_sockaddr_is_any(const struct osmo_sockaddr *addr)
1249{
1250 switch (addr->u.sa.sa_family) {
1251 case AF_INET6: {
1252 struct in6_addr ip6_any = IN6ADDR_ANY_INIT;
1253 return memcmp(&addr->u.sin6.sin6_addr,
1254 &ip6_any, sizeof(ip6_any)) == 0;
1255 }
1256 case AF_INET:
1257 return addr->u.sin.sin_addr.s_addr == INADDR_ANY;
1258 default:
1259 return -1;
1260 }
1261}
1262
Max9d7a2472018-11-20 15:18:31 +01001263/*! Convert sockaddr_in to IP address as char string and port as uint16_t.
1264 * \param[out] addr String buffer to write IP address to, or NULL.
1265 * \param[out] addr_len Size of \a addr.
1266 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1267 * \param[in] sin Sockaddr to convert.
1268 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1269 */
1270size_t osmo_sockaddr_in_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1271 const struct sockaddr_in *sin)
1272{
1273 if (port)
1274 *port = ntohs(sin->sin_port);
1275
1276 if (addr)
1277 return osmo_strlcpy(addr, inet_ntoa(sin->sin_addr), addr_len);
1278
1279 return 0;
1280}
1281
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001282/*! Convert sockaddr to IP address as char string and port as uint16_t.
1283 * \param[out] addr String buffer to write IP address to, or NULL.
1284 * \param[out] addr_len Size of \a addr.
1285 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1286 * \param[in] sa Sockaddr to convert.
1287 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1288 */
1289unsigned int osmo_sockaddr_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1290 const struct sockaddr *sa)
1291{
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001292
Pau Espin Pedrol1a3d24e2020-08-28 18:31:32 +02001293 const struct sockaddr_in6 *sin6;
1294
1295 switch (sa->sa_family) {
1296 case AF_INET:
1297 return osmo_sockaddr_in_to_str_and_uint(addr, addr_len, port,
1298 (const struct sockaddr_in *)sa);
1299 case AF_INET6:
1300 sin6 = (const struct sockaddr_in6 *)sa;
1301 if (port)
1302 *port = ntohs(sin6->sin6_port);
1303 if (addr && inet_ntop(sa->sa_family, &sin6->sin6_addr, addr, addr_len))
1304 return strlen(addr);
1305 break;
1306 }
1307 return 0;
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001308}
1309
Pau Espin Pedrol5cc4fe42020-08-31 12:52:06 +02001310/*! inet_ntop() wrapper for a struct sockaddr.
1311 * \param[in] sa source sockaddr to get the address from.
1312 * \param[out] dst string buffer of at least INET6_ADDRSTRLEN size.
1313 * \returns returns a non-null pointer to dst. NULL is returned if there was an
1314 * error, with errno set to indicate the error.
1315 */
1316const char *osmo_sockaddr_ntop(const struct sockaddr *sa, char *dst)
1317{
1318 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1319 return inet_ntop(osa->u.sa.sa_family,
1320 osa->u.sa.sa_family == AF_INET6 ?
1321 (const void *)&osa->u.sin6.sin6_addr :
1322 (const void *)&osa->u.sin.sin_addr,
1323 dst, INET6_ADDRSTRLEN);
1324}
1325
1326/*! Get sockaddr port content (in host byte order)
1327 * \param[in] sa source sockaddr to get the port from.
1328 * \returns returns the sockaddr port in host byte order
1329 */
1330uint16_t osmo_sockaddr_port(const struct sockaddr *sa)
1331{
1332 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1333 switch (osa->u.sa.sa_family) {
1334 case AF_INET6:
1335 return ntohs(osa->u.sin6.sin6_port);
1336 case AF_INET:
1337 return ntohs(osa->u.sin.sin_port);
1338 }
1339 return 0;
1340}
1341
Neels Hofmeyr9c7f7f82022-01-11 19:25:40 +01001342/*! Set sockaddr port content (to network byte order).
1343 * \param[out] sa sockaddr to set the port of.
1344 * \param[in] port port nr to set.
1345 */
1346void osmo_sockaddr_set_port(struct sockaddr *sa, uint16_t port)
1347{
1348 struct osmo_sockaddr *osa = (struct osmo_sockaddr *)sa;
1349 switch (osa->u.sa.sa_family) {
1350 case AF_INET6:
1351 osa->u.sin6.sin6_port = htons(port);
1352 return;
1353 case AF_INET:
1354 osa->u.sin.sin_port = htons(port);
1355 return;
1356 }
1357}
1358
Pau Espin Pedrolcc296c92023-01-16 14:54:55 +01001359static unsigned int in6_addr_netmask_to_prefixlen(const struct in6_addr *netmask)
1360{
1361 #if defined(__linux__)
1362 #define ADDRFIELD(i) s6_addr32[i]
1363 #else
1364 #define ADDRFIELD(i) __u6_addr.__u6_addr32[i]
1365 #endif
1366
1367 unsigned int i, j, prefix = 0;
1368
1369 for (j = 0; j < 4; j++) {
1370 uint32_t bits = netmask->ADDRFIELD(j);
1371 uint8_t *b = (uint8_t *)&bits;
1372 for (i = 0; i < 4; i++) {
1373 while (b[i] & 0x80) {
1374 prefix++;
1375 b[i] = b[i] << 1;
1376 }
1377 }
1378 }
1379
1380 #undef ADDRFIELD
1381
1382 return prefix;
1383}
1384
1385static unsigned int in_addr_netmask_to_prefixlen(const struct in_addr *netmask)
1386{
1387 uint32_t bits = netmask->s_addr;
1388 uint8_t *b = (uint8_t *)&bits;
1389 unsigned int i, prefix = 0;
1390
1391 for (i = 0; i < 4; i++) {
1392 while (b[i] & 0x80) {
1393 prefix++;
1394 b[i] = b[i] << 1;
1395 }
1396 }
1397 return prefix;
1398}
1399
1400/*! Convert netmask to prefix length representation
1401 * \param[in] netmask sockaddr containing a netmask (consecutive list of 1-bit followed by consecutive list of 0-bit)
1402 * \returns prefix length representation of the netmask (count of 1-bit from the start of the netmask), negative on error.
1403 */
1404int osmo_sockaddr_netmask_to_prefixlen(const struct osmo_sockaddr *netmask)
1405{
1406 switch (netmask->u.sa.sa_family) {
1407 case AF_INET6:
1408 return in6_addr_netmask_to_prefixlen(&netmask->u.sin6.sin6_addr);
1409 case AF_INET:
1410 return in_addr_netmask_to_prefixlen(&netmask->u.sin.sin_addr);
1411 default:
1412 return -ENOTSUP;
1413 }
1414}
1415
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001416/*! Initialize a unix domain socket (including bind/connect)
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001417 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1418 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1419 * \param[in] socket_path path to identify the socket
1420 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001421 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001422 *
1423 * This function creates a new unix domain socket, \a
1424 * type and \a proto and optionally binds or connects it, depending on
1425 * the value of \a flags parameter.
1426 */
Eric Wildeb5769b2019-06-27 15:31:17 +02001427#if defined(__clang__) && defined(SUN_LEN)
1428__attribute__((no_sanitize("undefined")))
1429#endif
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001430int osmo_sock_unix_init(uint16_t type, uint8_t proto,
1431 const char *socket_path, unsigned int flags)
1432{
1433 struct sockaddr_un local;
Harald Weltefaf6b702021-04-28 13:04:59 +02001434 int sfd, rc;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001435 unsigned int namelen;
1436
1437 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
1438 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT))
1439 return -EINVAL;
1440
1441 local.sun_family = AF_UNIX;
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001442 /* When an AF_UNIX socket is bound, sun_path should be NUL-terminated. See unix(7) man page. */
1443 if (osmo_strlcpy(local.sun_path, socket_path, sizeof(local.sun_path)) >= sizeof(local.sun_path)) {
Stefan Sperling896ff6d2018-08-28 14:34:17 +02001444 LOGP(DLGLOBAL, LOGL_ERROR, "Socket path exceeds maximum length of %zd bytes: %s\n",
1445 sizeof(local.sun_path), socket_path);
1446 return -ENOSPC;
1447 }
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001448
1449#if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001450 local.sun_len = strlen(local.sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001451#endif
1452#if defined(BSD44SOCKETS) || defined(SUN_LEN)
1453 namelen = SUN_LEN(&local);
1454#else
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001455 namelen = strlen(local.sun_path) +
1456 offsetof(struct sockaddr_un, sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001457#endif
1458
1459 sfd = socket(AF_UNIX, type, proto);
1460 if (sfd < 0)
Maxdb7cb692023-02-11 21:35:21 +03001461 return -errno;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001462
1463 if (flags & OSMO_SOCK_F_CONNECT) {
1464 rc = connect(sfd, (struct sockaddr *)&local, namelen);
1465 if (rc < 0)
1466 goto err;
1467 } else {
1468 unlink(local.sun_path);
1469 rc = bind(sfd, (struct sockaddr *)&local, namelen);
1470 if (rc < 0)
1471 goto err;
1472 }
1473
Harald Weltefaf6b702021-04-28 13:04:59 +02001474 rc = socket_helper_tail(sfd, flags);
1475 if (rc < 0)
1476 return rc;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001477
Harald Weltec47bbda2017-07-13 16:13:26 +02001478 rc = osmo_sock_init_tail(sfd, type, flags);
1479 if (rc < 0) {
1480 close(sfd);
Maxdb7cb692023-02-11 21:35:21 +03001481 sfd = rc;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001482 }
1483
1484 return sfd;
1485err:
1486 close(sfd);
Maxdb7cb692023-02-11 21:35:21 +03001487 return -errno;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001488}
1489
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001490/*! Initialize a unix domain socket and fill \ref osmo_fd
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001491 * \param[out] ofd file descriptor (will be filled in)
1492 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1493 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1494 * \param[in] socket_path path to identify the socket
1495 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001496 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001497 *
Vadim Yanitskiyb606d762019-06-01 19:02:47 +07001498 * This function creates (and optionally binds/connects) a socket
1499 * using osmo_sock_unix_init, but also fills the ofd structure.
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001500 */
1501int osmo_sock_unix_init_ofd(struct osmo_fd *ofd, uint16_t type, uint8_t proto,
1502 const char *socket_path, unsigned int flags)
1503{
Harald Welte24980ba2021-04-23 14:07:18 +02001504 return osmo_fd_init_ofd(ofd, osmo_sock_unix_init(type, proto, socket_path, flags), flags);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001505}
1506
Neels Hofmeyr01457512018-12-12 01:48:54 +01001507/*! Get the IP and/or port number on socket in separate string buffers.
Oliver Smith7acd5d02018-10-25 11:16:36 +02001508 * \param[in] fd file descriptor of socket
1509 * \param[out] ip IP address (will be filled in when not NULL)
1510 * \param[in] ip_len length of the ip buffer
1511 * \param[out] port number (will be filled in when not NULL)
1512 * \param[in] port_len length of the port buffer
1513 * \param[in] local (true) or remote (false) name will get looked at
1514 * \returns 0 on success; negative otherwise
1515 */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001516int 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 +02001517{
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001518 struct sockaddr_storage sa;
Oliver Smith7acd5d02018-10-25 11:16:36 +02001519 socklen_t len = sizeof(sa);
Oliver Smith860651e2018-10-30 14:31:57 +01001520 char ipbuf[INET6_ADDRSTRLEN], portbuf[6];
Oliver Smith7acd5d02018-10-25 11:16:36 +02001521 int rc;
1522
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001523 rc = local ? getsockname(fd, (struct sockaddr*)&sa, &len) : getpeername(fd, (struct sockaddr*)&sa, &len);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001524 if (rc < 0)
1525 return rc;
1526
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001527 rc = getnameinfo((const struct sockaddr*)&sa, len, ipbuf, sizeof(ipbuf),
Oliver Smith7acd5d02018-10-25 11:16:36 +02001528 portbuf, sizeof(portbuf),
1529 NI_NUMERICHOST | NI_NUMERICSERV);
1530 if (rc < 0)
1531 return rc;
1532
1533 if (ip)
1534 strncpy(ip, ipbuf, ip_len);
1535 if (port)
1536 strncpy(port, portbuf, port_len);
1537 return 0;
1538}
1539
1540/*! Get local IP address on socket
1541 * \param[in] fd file descriptor of socket
1542 * \param[out] ip IP address (will be filled in)
1543 * \param[in] len length of the output buffer
1544 * \returns 0 on success; negative otherwise
1545 */
1546int osmo_sock_get_local_ip(int fd, char *ip, size_t len)
1547{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001548 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001549}
1550
1551/*! Get local port on socket
1552 * \param[in] fd file descriptor of socket
1553 * \param[out] port number (will be filled in)
1554 * \param[in] len length of the output buffer
1555 * \returns 0 on success; negative otherwise
1556 */
1557int osmo_sock_get_local_ip_port(int fd, char *port, size_t len)
1558{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001559 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001560}
1561
1562/*! Get remote IP address on socket
1563 * \param[in] fd file descriptor of socket
1564 * \param[out] ip IP address (will be filled in)
1565 * \param[in] len length of the output buffer
1566 * \returns 0 on success; negative otherwise
1567 */
1568int osmo_sock_get_remote_ip(int fd, char *ip, size_t len)
1569{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001570 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001571}
1572
1573/*! Get remote port on socket
1574 * \param[in] fd file descriptor of socket
1575 * \param[out] port number (will be filled in)
1576 * \param[in] len length of the output buffer
1577 * \returns 0 on success; negative otherwise
1578 */
1579int osmo_sock_get_remote_ip_port(int fd, char *port, size_t len)
1580{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001581 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001582}
1583
Neels Hofmeyr01457512018-12-12 01:48:54 +01001584/*! Get address/port information on socket in dyn-alloc string like "(r=1.2.3.4:5<->l=6.7.8.9:10)".
1585 * Usually, it is better to use osmo_sock_get_name2() for a static string buffer or osmo_sock_get_name_buf() for a
1586 * caller provided string buffer, to avoid the dynamic talloc allocation.
Harald Welte48f55832017-01-26 00:03:10 +01001587 * \param[in] ctx talloc context from which to allocate string buffer
1588 * \param[in] fd file descriptor of socket
Neels Hofmeyr01457512018-12-12 01:48:54 +01001589 * \returns string identifying the connection of this socket, talloc'd from ctx.
Harald Welte48f55832017-01-26 00:03:10 +01001590 */
Harald Weltec0dfc9d2019-03-18 18:29:43 +01001591char *osmo_sock_get_name(const void *ctx, int fd)
Harald Welte48f55832017-01-26 00:03:10 +01001592{
Philipp Maier64b51eb2019-01-14 11:59:11 +01001593 char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001594 int rc;
1595 rc = osmo_sock_get_name_buf(str, sizeof(str), fd);
1596 if (rc <= 0)
1597 return NULL;
1598 return talloc_asprintf(ctx, "(%s)", str);
1599}
1600
1601/*! Get address/port information on socket in provided string buffer, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1602 * This does not include braces like osmo_sock_get_name().
1603 * \param[out] str Destination string buffer.
1604 * \param[in] str_len sizeof(str).
1605 * \param[in] fd File descriptor of socket.
1606 * \return String length as returned by snprintf(), or negative on error.
1607 */
1608int osmo_sock_get_name_buf(char *str, size_t str_len, int fd)
1609{
Oliver Smith860651e2018-10-30 14:31:57 +01001610 char hostbuf_l[INET6_ADDRSTRLEN], hostbuf_r[INET6_ADDRSTRLEN];
1611 char portbuf_l[6], portbuf_r[6];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001612 int rc;
Harald Welte48f55832017-01-26 00:03:10 +01001613
Daniel Willmann7052cc62023-06-16 09:53:15 +02001614 if (fd < 0) {
1615 osmo_strlcpy(str, "<error-bad-fd>", str_len);
1616 return -EBADF;
1617 }
1618
Oliver Smith7acd5d02018-10-25 11:16:36 +02001619 /* get local */
Harald Welteea9ea522019-05-10 09:28:24 +02001620 if ((rc = osmo_sock_get_ip_and_port(fd, hostbuf_l, sizeof(hostbuf_l), portbuf_l, sizeof(portbuf_l), true))) {
1621 osmo_strlcpy(str, "<error-in-getsockname>", str_len);
Neels Hofmeyr01457512018-12-12 01:48:54 +01001622 return rc;
Harald Welteea9ea522019-05-10 09:28:24 +02001623 }
Harald Welte48f55832017-01-26 00:03:10 +01001624
Oliver Smith7acd5d02018-10-25 11:16:36 +02001625 /* get remote */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001626 if (osmo_sock_get_ip_and_port(fd, hostbuf_r, sizeof(hostbuf_r), portbuf_r, sizeof(portbuf_r), false) != 0)
1627 return snprintf(str, str_len, "r=NULL<->l=%s:%s", hostbuf_l, portbuf_l);
Harald Welte48f55832017-01-26 00:03:10 +01001628
Neels Hofmeyr01457512018-12-12 01:48:54 +01001629 return snprintf(str, str_len, "r=%s:%s<->l=%s:%s", hostbuf_r, portbuf_r, hostbuf_l, portbuf_l);
1630}
1631
1632/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1633 * This does not include braces like osmo_sock_get_name().
1634 * \param[in] fd File descriptor of socket.
1635 * \return Static string buffer containing the result.
1636 */
1637const char *osmo_sock_get_name2(int fd)
1638{
Harald Welte171ef822019-03-28 10:49:05 +01001639 static __thread char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001640 osmo_sock_get_name_buf(str, sizeof(str), fd);
1641 return str;
Harald Welte48f55832017-01-26 00:03:10 +01001642}
1643
Harald Welte179f3572019-03-18 18:38:47 +01001644/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1645 * This does not include braces like osmo_sock_get_name().
1646 * \param[in] fd File descriptor of socket.
1647 * \return Static string buffer containing the result.
1648 */
1649char *osmo_sock_get_name2_c(const void *ctx, int fd)
1650{
1651 char *str = talloc_size(ctx, OSMO_SOCK_NAME_MAXLEN);
1652 if (!str)
1653 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001654 osmo_sock_get_name_buf(str, OSMO_SOCK_NAME_MAXLEN, fd);
Harald Welte179f3572019-03-18 18:38:47 +01001655 return str;
1656}
1657
Harald Weltee30d7e62017-07-13 16:02:50 +02001658static int sock_get_domain(int fd)
1659{
1660 int domain;
1661#ifdef SO_DOMAIN
1662 socklen_t dom_len = sizeof(domain);
1663 int rc;
1664
1665 rc = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &dom_len);
1666 if (rc < 0)
1667 return rc;
1668#else
1669 /* This of course sucks, but what shall we do on OSs like
1670 * FreeBSD that don't seem to expose a method by which one can
1671 * learn the address family of a socket? */
1672 domain = AF_INET;
1673#endif
1674 return domain;
1675}
1676
1677
1678/*! Activate or de-activate local loop-back of transmitted multicast packets
1679 * \param[in] fd file descriptor of related socket
1680 * \param[in] enable Enable (true) or disable (false) loop-back
1681 * \returns 0 on success; negative otherwise */
1682int osmo_sock_mcast_loop_set(int fd, bool enable)
1683{
1684 int domain, loop = 0;
1685
1686 if (enable)
1687 loop = 1;
1688
1689 domain = sock_get_domain(fd);
1690 if (domain < 0)
1691 return domain;
1692
1693 switch (domain) {
1694 case AF_INET:
1695 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1696 case AF_INET6:
1697 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop));
1698 default:
1699 return -EINVAL;
1700 }
1701}
1702
1703/*! Set the TTL of outbound multicast packets
1704 * \param[in] fd file descriptor of related socket
1705 * \param[in] ttl TTL of to-be-sent multicast packets
1706 * \returns 0 on success; negative otherwise */
1707int osmo_sock_mcast_ttl_set(int fd, uint8_t ttl)
1708{
1709 int domain, ttli = ttl;
1710
1711 domain = sock_get_domain(fd);
1712 if (domain < 0)
1713 return domain;
1714
1715 switch (domain) {
1716 case AF_INET:
1717 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttli, sizeof(ttli));
1718 case AF_INET6:
1719 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttli, sizeof(ttli));
1720 default:
1721 return -EINVAL;
1722 }
1723}
1724
Harald Welte44b99262020-03-07 14:59:05 +01001725/*! Set the network device to which we should bind the multicast socket
1726 * \param[in] fd file descriptor of related socket
1727 * \param[in] ifname name of network interface to user for multicast
1728 * \returns 0 on success; negative otherwise */
1729int osmo_sock_mcast_iface_set(int fd, const char *ifname)
1730{
1731 unsigned int ifindex;
1732 struct ip_mreqn mr;
1733
1734 /* first, resolve interface name to ifindex */
1735 ifindex = if_nametoindex(ifname);
1736 if (ifindex == 0)
1737 return -errno;
1738
1739 /* next, configure kernel to use that ifindex for this sockets multicast traffic */
1740 memset(&mr, 0, sizeof(mr));
1741 mr.imr_ifindex = ifindex;
1742 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mr, sizeof(mr));
1743}
1744
1745
Harald Weltee30d7e62017-07-13 16:02:50 +02001746/*! Enable/disable receiving all multicast packets, even for non-subscribed groups
1747 * \param[in] fd file descriptor of related socket
1748 * \param[in] enable Enable or Disable receiving of all packets
1749 * \returns 0 on success; negative otherwise */
1750int osmo_sock_mcast_all_set(int fd, bool enable)
1751{
1752 int domain, all = 0;
1753
1754 if (enable)
1755 all = 1;
1756
1757 domain = sock_get_domain(fd);
1758 if (domain < 0)
1759 return domain;
1760
1761 switch (domain) {
1762 case AF_INET:
1763#ifdef IP_MULTICAST_ALL
1764 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_ALL, &all, sizeof(all));
1765#endif
1766 case AF_INET6:
1767 /* there seems no equivalent ?!? */
1768 default:
1769 return -EINVAL;
1770 }
1771}
1772
1773/* FreeBSD calls the socket option differently */
1774#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
1775#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1776#endif
1777
1778/*! Subscribe to the given IP multicast group
1779 * \param[in] fd file descriptor of related scoket
1780 * \param[in] grp_addr ASCII representation of the multicast group address
1781 * \returns 0 on success; negative otherwise */
1782int osmo_sock_mcast_subscribe(int fd, const char *grp_addr)
1783{
1784 int rc, domain;
1785 struct ip_mreq mreq;
1786 struct ipv6_mreq mreq6;
1787 struct in6_addr i6a;
1788
1789 domain = sock_get_domain(fd);
1790 if (domain < 0)
1791 return domain;
1792
1793 switch (domain) {
1794 case AF_INET:
1795 memset(&mreq, 0, sizeof(mreq));
1796 mreq.imr_multiaddr.s_addr = inet_addr(grp_addr);
1797 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1798 return setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
1799#ifdef IPV6_ADD_MEMBERSHIP
1800 case AF_INET6:
1801 memset(&mreq6, 0, sizeof(mreq6));
1802 rc = inet_pton(AF_INET6, grp_addr, (void *)&i6a);
1803 if (rc < 0)
1804 return -EINVAL;
1805 mreq6.ipv6mr_multiaddr = i6a;
1806 return setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
1807#endif
1808 default:
1809 return -EINVAL;
1810 }
1811}
1812
Philipp Maier2d2490e2017-10-20 19:41:26 +02001813/*! Determine the matching local IP-address for a given remote IP-Address.
1814 * \param[out] local_ip caller provided memory for resulting local IP-address
1815 * \param[in] remote_ip remote IP-address
Philipp Maier2d2490e2017-10-20 19:41:26 +02001816 * \returns 0 on success; negative otherwise
1817 *
1818 * The function accepts IPv4 and IPv6 address strings. The caller must provide
1819 * at least INET6_ADDRSTRLEN bytes for local_ip if an IPv6 is expected as
1820 * as result. For IPv4 addresses the required amount is INET_ADDRSTRLEN. */
1821int osmo_sock_local_ip(char *local_ip, const char *remote_ip)
1822{
1823 int sfd;
1824 int rc;
1825 struct addrinfo addrinfo_hint;
1826 struct addrinfo *addrinfo = NULL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001827 struct sockaddr_storage local_addr;
1828 struct sockaddr_in *sin;
1829 struct sockaddr_in6 *sin6;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001830 socklen_t local_addr_len;
1831 uint16_t family;
1832
1833 /* Find out the address family (AF_INET or AF_INET6?) */
1834 memset(&addrinfo_hint, '\0', sizeof(addrinfo_hint));
Pau Espin Pedrol308ab792020-08-28 19:47:25 +02001835 addrinfo_hint.ai_family = AF_UNSPEC;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001836 addrinfo_hint.ai_flags = AI_NUMERICHOST;
1837 rc = getaddrinfo(remote_ip, NULL, &addrinfo_hint, &addrinfo);
1838 if (rc)
1839 return -EINVAL;
1840 family = addrinfo->ai_family;
1841 freeaddrinfo(addrinfo);
1842
1843 /* Connect a dummy socket to trick the kernel into determining the
1844 * ip-address of the interface that would be used if we would send
1845 * out an actual packet */
1846 sfd = osmo_sock_init2(family, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, remote_ip, 0, OSMO_SOCK_F_CONNECT);
1847 if (sfd < 0)
1848 return -EINVAL;
1849
1850 /* Request the IP address of the interface that the kernel has
1851 * actually choosen. */
1852 memset(&local_addr, 0, sizeof(local_addr));
1853 local_addr_len = sizeof(local_addr);
1854 rc = getsockname(sfd, (struct sockaddr *)&local_addr, &local_addr_len);
Philipp Maier8b7975b2018-01-22 15:38:07 +01001855 close(sfd);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001856 if (rc < 0)
1857 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001858
1859 switch (local_addr.ss_family) {
1860 case AF_INET:
1861 sin = (struct sockaddr_in*)&local_addr;
1862 if (!inet_ntop(AF_INET, &sin->sin_addr, local_ip, INET_ADDRSTRLEN))
1863 return -EINVAL;
1864 break;
1865 case AF_INET6:
1866 sin6 = (struct sockaddr_in6*)&local_addr;
Pau Espin Pedrol7bda8542020-08-31 11:21:30 +02001867 if (!inet_ntop(AF_INET6, &sin6->sin6_addr, local_ip, INET6_ADDRSTRLEN))
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001868 return -EINVAL;
1869 break;
1870 default:
Philipp Maier2d2490e2017-10-20 19:41:26 +02001871 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001872 }
Philipp Maier2d2490e2017-10-20 19:41:26 +02001873
1874 return 0;
1875}
1876
Alexander Couzens0f364212020-07-27 22:33:01 +02001877/*! Determine the matching local address for a given remote address.
1878 * \param[out] local_ip caller provided memory for resulting local address
1879 * \param[in] remote_ip remote address
1880 * \returns 0 on success; negative otherwise
1881 */
1882int osmo_sockaddr_local_ip(struct osmo_sockaddr *local_ip, const struct osmo_sockaddr *remote_ip)
1883{
1884 int sfd;
1885 int rc;
1886 socklen_t local_ip_len;
1887
1888 sfd = osmo_sock_init_osa(SOCK_DGRAM, IPPROTO_UDP, NULL, remote_ip, OSMO_SOCK_F_CONNECT);
1889 if (sfd < 0)
1890 return -EINVAL;
1891
1892 memset(local_ip, 0, sizeof(*local_ip));
1893 local_ip_len = sizeof(*local_ip);
1894 rc = getsockname(sfd, (struct sockaddr *)local_ip, &local_ip_len);
1895 close(sfd);
1896
1897 return rc;
1898}
1899
Neels Hofmeyrcf7f7922022-02-02 03:08:40 +01001900/*! Copy the addr part, the IP address octets in network byte order, to a buffer.
1901 * Useful for encoding network protocols.
1902 * \param[out] dst Write octets to this buffer.
1903 * \param[in] dst_maxlen Space available in buffer.
1904 * \param[in] os Sockaddr to copy IP of.
1905 * \return nr of octets written on success, negative on error.
1906 */
1907int osmo_sockaddr_to_octets(uint8_t *dst, size_t dst_maxlen, const struct osmo_sockaddr *os)
1908{
1909 const void *addr;
1910 size_t len;
Neels Hofmeyr1790f172022-02-02 03:08:40 +01001911 switch (os->u.sa.sa_family) {
Neels Hofmeyrcf7f7922022-02-02 03:08:40 +01001912 case AF_INET:
1913 addr = &os->u.sin.sin_addr;
1914 len = sizeof(os->u.sin.sin_addr);
1915 break;
1916 case AF_INET6:
1917 addr = &os->u.sin6.sin6_addr;
1918 len = sizeof(os->u.sin6.sin6_addr);
1919 break;
1920 default:
1921 return -ENOTSUP;
1922 }
1923 if (dst_maxlen < len)
1924 return -ENOSPC;
1925 memcpy(dst, addr, len);
1926 return len;
1927}
1928
1929/*! Copy the addr part, the IP address octets in network byte order, from a buffer.
1930 * Useful for decoding network protocols.
1931 * \param[out] os Write IP address to this sockaddr.
1932 * \param[in] src Source buffer to read IP address octets from.
1933 * \param[in] src_len Number of octets to copy.
1934 * \return number of octets read on success, negative on error.
1935 */
1936int osmo_sockaddr_from_octets(struct osmo_sockaddr *os, const void *src, size_t src_len)
1937{
1938 void *addr;
1939 size_t len;
1940 *os = (struct osmo_sockaddr){0};
1941 switch (src_len) {
1942 case sizeof(os->u.sin.sin_addr):
Neels Hofmeyr1790f172022-02-02 03:08:40 +01001943 os->u.sa.sa_family = AF_INET;
Neels Hofmeyrcf7f7922022-02-02 03:08:40 +01001944 addr = &os->u.sin.sin_addr;
1945 len = sizeof(os->u.sin.sin_addr);
1946 break;
1947 case sizeof(os->u.sin6.sin6_addr):
1948 os->u.sin6.sin6_family = AF_INET6;
1949 addr = &os->u.sin6.sin6_addr;
1950 len = sizeof(os->u.sin6.sin6_addr);
1951 break;
1952 default:
1953 return -ENOTSUP;
1954 }
1955 memcpy(addr, src, len);
1956 return len;
1957}
1958
Alexander Couzense4181ea2020-07-20 00:03:16 +02001959/*! Compare two osmo_sockaddr.
1960 * \param[in] a
1961 * \param[in] b
1962 * \return 0 if a and b are equal. Otherwise it follows memcmp()
1963 */
Vadim Yanitskiydef5a402020-10-09 21:40:47 +07001964int osmo_sockaddr_cmp(const struct osmo_sockaddr *a,
1965 const struct osmo_sockaddr *b)
Alexander Couzense4181ea2020-07-20 00:03:16 +02001966{
1967 if (a == b)
1968 return 0;
1969 if (!a)
1970 return 1;
1971 if (!b)
1972 return -1;
1973
1974 if (a->u.sa.sa_family != b->u.sa.sa_family) {
1975 return OSMO_CMP(a->u.sa.sa_family, b->u.sa.sa_family);
1976 }
1977
1978 switch (a->u.sa.sa_family) {
1979 case AF_INET:
1980 return memcmp(&a->u.sin, &b->u.sin, sizeof(struct sockaddr_in));
1981 case AF_INET6:
1982 return memcmp(&a->u.sin6, &b->u.sin6, sizeof(struct sockaddr_in6));
1983 default:
1984 /* fallback to memcmp for remaining AF over the full osmo_sockaddr length */
1985 return memcmp(a, b, sizeof(struct osmo_sockaddr));
1986 }
1987}
1988
Alexander Couzens80788fa2020-10-12 01:11:20 +02001989/*! string-format a given osmo_sockaddr address
1990 * \param[in] sockaddr the osmo_sockaddr to print
1991 * \return pointer to the string on success; NULL on error
1992 */
1993const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *sockaddr)
1994{
1995 /* INET6_ADDRSTRLEN contains already a null termination,
1996 * adding '[' ']' ':' '16 bit port' */
1997 static __thread char buf[INET6_ADDRSTRLEN + 8];
1998 return osmo_sockaddr_to_str_buf(buf, sizeof(buf), sockaddr);
1999}
2000
Neels Hofmeyr09d65742021-12-01 10:25:02 +01002001/*! string-format a given osmo_sockaddr address into a user-supplied buffer.
2002 * Same as osmo_sockaddr_to_str_buf() but returns a would-be length in snprintf() style.
2003 * \param[in] buf user-supplied output buffer
2004 * \param[in] buf_len size of the user-supplied output buffer in bytes
2005 * \param[in] sockaddr the osmo_sockaddr to print
2006 * \return number of characters that would be written if the buffer is large enough, like snprintf().
2007 */
2008int osmo_sockaddr_to_str_buf2(char *buf, size_t buf_len, const struct osmo_sockaddr *sockaddr)
2009{
2010 struct osmo_strbuf sb = { .buf = buf, .len = buf_len };
2011 uint16_t port = 0;
2012
2013 if (!sockaddr) {
2014 OSMO_STRBUF_PRINTF(sb, "NULL");
2015 return sb.chars_needed;
2016 }
2017
2018 switch (sockaddr->u.sa.sa_family) {
2019 case AF_INET:
2020 OSMO_STRBUF_APPEND(sb, osmo_sockaddr_to_str_and_uint, &port, &sockaddr->u.sa);
2021 if (port)
2022 OSMO_STRBUF_PRINTF(sb, ":%u", port);
2023 break;
2024 case AF_INET6:
2025 OSMO_STRBUF_PRINTF(sb, "[");
2026 OSMO_STRBUF_APPEND(sb, osmo_sockaddr_to_str_and_uint, &port, &sockaddr->u.sa);
2027 OSMO_STRBUF_PRINTF(sb, "]");
2028 if (port)
2029 OSMO_STRBUF_PRINTF(sb, ":%u", port);
2030 break;
2031 default:
2032 OSMO_STRBUF_PRINTF(sb, "unsupported family %d", sockaddr->u.sa.sa_family);
2033 break;
2034 }
2035
2036 return sb.chars_needed;
2037}
2038
2039/*! string-format a given osmo_sockaddr address into a talloc allocated buffer.
2040 * Like osmo_sockaddr_to_str_buf2() but returns a talloc allocated string.
2041 * \param[in] ctx talloc context to allocate from, e.g. OTC_SELECT.
2042 * \param[in] sockaddr the osmo_sockaddr to print.
2043 * \return human readable string.
2044 */
2045char *osmo_sockaddr_to_str_c(void *ctx, const struct osmo_sockaddr *sockaddr)
2046{
2047 OSMO_NAME_C_IMPL(ctx, 64, "ERROR", osmo_sockaddr_to_str_buf2, sockaddr)
2048}
2049
2050/*! string-format a given osmo_sockaddr address into a user-supplied buffer.
2051 * Like osmo_sockaddr_to_str_buf2() but returns buf, or NULL if too short.
Alexander Couzens80788fa2020-10-12 01:11:20 +02002052 * \param[in] buf user-supplied output buffer
2053 * \param[in] buf_len size of the user-supplied output buffer in bytes
2054 * \param[in] sockaddr the osmo_sockaddr to print
2055 * \return pointer to the string on success; NULL on error
2056 */
2057char *osmo_sockaddr_to_str_buf(char *buf, size_t buf_len,
2058 const struct osmo_sockaddr *sockaddr)
2059{
Neels Hofmeyr09d65742021-12-01 10:25:02 +01002060 int chars_needed = osmo_sockaddr_to_str_buf2(buf, buf_len, sockaddr);
2061 if (chars_needed >= buf_len)
Alexander Couzens80788fa2020-10-12 01:11:20 +02002062 return NULL;
Alexander Couzens80788fa2020-10-12 01:11:20 +02002063 return buf;
2064}
2065
Harald Weltece53e032021-04-27 21:44:34 +02002066/*! Set the DSCP (differentiated services code point) of a socket.
2067 * \param[in] dscp DSCP value in range 0..63
2068 * \returns 0 on success; negative on error. */
2069int osmo_sock_set_dscp(int fd, uint8_t dscp)
2070{
Harald Welte903e6702021-04-28 13:27:12 +02002071 struct sockaddr_storage local_addr;
2072 socklen_t local_addr_len = sizeof(local_addr);
Harald Weltece53e032021-04-27 21:44:34 +02002073 uint8_t tos;
2074 socklen_t tos_len = sizeof(tos);
Harald Welte903e6702021-04-28 13:27:12 +02002075 int tclass;
2076 socklen_t tclass_len = sizeof(tclass);
Harald Weltece53e032021-04-27 21:44:34 +02002077 int rc;
2078
2079 /* DSCP is a 6-bit value stored in the upper 6 bits of the 8-bit TOS */
2080 if (dscp > 63)
2081 return -EINVAL;
2082
Harald Welte903e6702021-04-28 13:27:12 +02002083 rc = getsockname(fd, (struct sockaddr *)&local_addr, &local_addr_len);
Harald Weltece53e032021-04-27 21:44:34 +02002084 if (rc < 0)
2085 return rc;
2086
Harald Welte903e6702021-04-28 13:27:12 +02002087 switch (local_addr.ss_family) {
2088 case AF_INET:
2089 /* read the original value */
2090 rc = getsockopt(fd, IPPROTO_IP, IP_TOS, &tos, &tos_len);
2091 if (rc < 0)
2092 return rc;
2093 /* mask-in the DSCP into the upper 6 bits */
2094 tos &= 0x03;
2095 tos |= dscp << 2;
2096 /* and write it back to the kernel */
2097 rc = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
2098 break;
2099 case AF_INET6:
2100 /* read the original value */
2101 rc = getsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tclass, &tclass_len);
2102 if (rc < 0)
2103 return rc;
2104 /* mask-in the DSCP into the upper 6 bits */
2105 tclass &= 0x03;
2106 tclass |= dscp << 2;
2107 /* and write it back to the kernel */
2108 rc = setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof(tclass));
2109 break;
2110 case AF_UNSPEC:
2111 default:
2112 LOGP(DLGLOBAL, LOGL_ERROR, "No DSCP support for socket family %u\n",
2113 local_addr.ss_family);
2114 rc = -1;
2115 break;
2116 }
Harald Weltece53e032021-04-27 21:44:34 +02002117
Harald Welte903e6702021-04-28 13:27:12 +02002118 return rc;
Harald Weltece53e032021-04-27 21:44:34 +02002119}
2120
Harald Welteecc0bd82021-04-27 22:24:08 +02002121/*! Set the priority value of a socket.
2122 * \param[in] prio priority value. Values outside 0..6 require CAP_NET_ADMIN.
2123 * \returns 0 on success; negative on error. */
2124int osmo_sock_set_priority(int fd, int prio)
2125{
2126 /* and write it back to the kernel */
2127 return setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(prio));
2128}
Alexander Couzens80788fa2020-10-12 01:11:20 +02002129
Harald Weltee4764422011-05-22 12:25:57 +02002130#endif /* HAVE_SYS_SOCKET_H */
Harald Welteba6988b2011-08-17 12:46:48 +02002131
Sylvain Munautdca7d2c2012-04-18 21:53:23 +02002132/*! @} */