blob: 125106182fe044cb6e64381b4a256f787a1f2294 [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
Harald Welte33cb71a2011-05-21 18:54:32 +020020#include "../config.h"
21
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{
117 int i, j;
118
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;
213 int ret, i;
214 char *after;
215
216 if (buf_len < 3)
217 return -EINVAL;
218
219 if (host_cnt != 1) {
220 ret = snprintf(buf, rem, "(");
221 if (ret < 0)
222 return ret;
223 OSMO_SNPRINTF_RET(ret, rem, offset, len);
224 }
225 for (i = 0; i < host_cnt; i++) {
226 if (host_cnt == 1)
227 after = "";
228 else
229 after = (i == (host_cnt - 1)) ? ")" : "|";
230 ret = snprintf(buf + offset, rem, "%s%s", hosts[i] ? : "0.0.0.0", after);
231 OSMO_SNPRINTF_RET(ret, rem, offset, len);
232 }
233
234 return len;
235}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200236#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200237
Harald Weltec47bbda2017-07-13 16:13:26 +0200238static int osmo_sock_init_tail(int fd, uint16_t type, unsigned int flags)
239{
Harald Weltebc43a622017-07-13 16:20:21 +0200240 int rc;
Harald Weltec47bbda2017-07-13 16:13:26 +0200241
242 /* Make sure to call 'listen' on a bound, connection-oriented sock */
243 if ((flags & (OSMO_SOCK_F_BIND|OSMO_SOCK_F_CONNECT)) == OSMO_SOCK_F_BIND) {
244 switch (type) {
245 case SOCK_STREAM:
246 case SOCK_SEQPACKET:
247 rc = listen(fd, 10);
Harald Weltebc43a622017-07-13 16:20:21 +0200248 if (rc < 0) {
249 LOGP(DLGLOBAL, LOGL_ERROR, "unable to listen on socket: %s\n",
250 strerror(errno));
251 return rc;
252 }
253 break;
Harald Weltec47bbda2017-07-13 16:13:26 +0200254 }
255 }
256
Harald Weltebc43a622017-07-13 16:20:21 +0200257 if (flags & OSMO_SOCK_F_NO_MCAST_LOOP) {
258 rc = osmo_sock_mcast_loop_set(fd, false);
259 if (rc < 0) {
260 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable multicast loop: %s\n",
261 strerror(errno));
262 return rc;
263 }
264 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200265
Harald Welte37d204a2017-07-13 16:33:16 +0200266 if (flags & OSMO_SOCK_F_NO_MCAST_ALL) {
267 rc = osmo_sock_mcast_all_set(fd, false);
268 if (rc < 0) {
269 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable receive of all multicast: %s\n",
270 strerror(errno));
271 /* do not abort here, as this is just an
272 * optional additional optimization that only
273 * exists on Linux only */
274 }
275 }
Harald Weltebc43a622017-07-13 16:20:21 +0200276 return 0;
Harald Weltec47bbda2017-07-13 16:13:26 +0200277}
278
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200279/*! Initialize a socket (including bind and/or connect)
Harald Weltedda70fc2017-04-08 20:52:33 +0200280 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
281 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
282 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
283 * \param[in] local_host local host name or IP address in string form
284 * \param[in] local_port local port number in host byte order
285 * \param[in] remote_host remote host name or IP address in string form
286 * \param[in] remote_port remote port number in host byte order
287 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
288 * \returns socket file descriptor on success; negative on error
289 *
290 * This function creates a new socket of the designated \a family, \a
291 * type and \a proto and optionally binds it to the \a local_host and \a
292 * local_port as well as optionally connects it to the \a remote_host
293 * and \q remote_port, depending on the value * of \a flags parameter.
294 *
295 * As opposed to \ref osmo_sock_init(), this function allows to combine
296 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
297 * is useful if you want to connect to a remote host/port, but still
298 * want to bind that socket to either a specific local alias IP and/or a
299 * specific local source port.
300 *
301 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
302 * OSMO_SOCK_F_CONNECT, or both.
303 *
304 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
305 * non-blocking mode.
306 */
307int osmo_sock_init2(uint16_t family, uint16_t type, uint8_t proto,
308 const char *local_host, uint16_t local_port,
309 const char *remote_host, uint16_t remote_port, unsigned int flags)
310{
Alexander Couzens2c962f52020-06-03 00:28:02 +0200311 struct addrinfo *local = NULL, *remote = NULL, *rp;
Harald Weltedda70fc2017-04-08 20:52:33 +0200312 int sfd = -1, rc, on = 1;
313
Alexander Couzens2c962f52020-06-03 00:28:02 +0200314 bool local_ipv4 = false, local_ipv6 = false;
315 bool remote_ipv4 = false, remote_ipv6 = false;
316
Harald Weltedda70fc2017-04-08 20:52:33 +0200317 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
318 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
319 "BIND or CONNECT flags\n");
320 return -EINVAL;
321 }
322
Alexander Couzens2c962f52020-06-03 00:28:02 +0200323 /* figure out local address infos */
324 if (flags & OSMO_SOCK_F_BIND) {
325 local = addrinfo_helper(family, type, proto, local_host, local_port, true);
326 if (!local)
327 return -EINVAL;
328 }
329
330 /* figure out remote address infos */
331 if (flags & OSMO_SOCK_F_CONNECT) {
332 remote = addrinfo_helper(family, type, proto, remote_host, remote_port, false);
333 if (!remote) {
334 if (local)
335 freeaddrinfo(local);
336
337 return -EINVAL;
338 }
339 }
340
341 /* It must do a full run to ensure AF_UNSPEC does not fail.
342 * In case first local valid entry is IPv4 and only remote valid entry
343 * is IPv6 or vice versa */
344 if (family == AF_UNSPEC) {
345 for (rp = local; rp != NULL; rp = rp->ai_next) {
346 switch (rp->ai_family) {
347 case AF_INET:
348 local_ipv4 = true;
349 break;
350 case AF_INET6:
351 local_ipv6 = true;
352 break;
353 }
354 }
355
356 for (rp = remote; rp != NULL; rp = rp->ai_next) {
357 switch (rp->ai_family) {
358 case AF_INET:
359 remote_ipv4 = true;
360 break;
361 case AF_INET6:
362 remote_ipv6 = true;
363 break;
364 }
365 }
366
Pau Espin Pedrold8cf52b2020-08-31 19:00:59 +0200367 if ((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) {
368 /* prioritize ipv6 as per RFC */
369 if (local_ipv6 && remote_ipv6)
370 family = AF_INET6;
371 else if (local_ipv4 && remote_ipv4)
372 family = AF_INET;
373 else {
374 if (local)
375 freeaddrinfo(local);
376 if (remote)
377 freeaddrinfo(remote);
378 LOGP(DLGLOBAL, LOGL_ERROR,
379 "Unable to find a common protocol (IPv4 or IPv6) "
380 "for local host: %s and remote host: %s.\n",
381 local_host, remote_host);
382 return -ENODEV;
383 }
384 } else if ((flags & OSMO_SOCK_F_BIND)) {
385 family = local_ipv6 ? AF_INET6 : AF_INET;
386 } else if ((flags & OSMO_SOCK_F_CONNECT)) {
387 family = remote_ipv6 ? AF_INET6 : AF_INET;
Alexander Couzens2c962f52020-06-03 00:28:02 +0200388 }
389 }
390
Harald Weltedda70fc2017-04-08 20:52:33 +0200391 /* figure out local side of socket */
392 if (flags & OSMO_SOCK_F_BIND) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200393 for (rp = local; rp != NULL; rp = rp->ai_next) {
394 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
395 if (rp->ai_family != family)
396 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200397
Harald Weltedda70fc2017-04-08 20:52:33 +0200398 sfd = socket_helper(rp, flags);
399 if (sfd < 0)
400 continue;
401
Philipp Maier73196e72018-08-23 20:11:50 +0200402 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200403 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
404 &on, sizeof(on));
405 if (rc < 0) {
406 LOGP(DLGLOBAL, LOGL_ERROR,
407 "cannot setsockopt socket:"
408 " %s:%u: %s\n",
409 local_host, local_port,
410 strerror(errno));
411 close(sfd);
412 continue;
413 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200414 }
Philipp Maier99f706d2018-08-01 12:40:36 +0200415
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200416 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
417 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
418 local_host, local_port, strerror(errno));
419 close(sfd);
420 continue;
421 }
422 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200423 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200424
425 freeaddrinfo(local);
Harald Weltedda70fc2017-04-08 20:52:33 +0200426 if (rp == NULL) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200427 if (remote)
428 freeaddrinfo(remote);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200429 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
430 local_host, local_port);
Harald Weltedda70fc2017-04-08 20:52:33 +0200431 return -ENODEV;
432 }
433 }
434
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200435 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
436 was already closed and func returned. If OSMO_SOCK_F_BIND is not
437 set, then sfd = -1 */
438
Harald Weltedda70fc2017-04-08 20:52:33 +0200439 /* figure out remote side of socket */
440 if (flags & OSMO_SOCK_F_CONNECT) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200441 for (rp = remote; rp != NULL; rp = rp->ai_next) {
442 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
443 if (rp->ai_family != family)
444 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200445
Harald Welte5cfa6dc2017-07-21 16:52:29 +0200446 if (sfd < 0) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200447 sfd = socket_helper(rp, flags);
448 if (sfd < 0)
449 continue;
450 }
451
452 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200453 if (rc != 0 && errno != EINPROGRESS) {
454 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
455 remote_host, remote_port, strerror(errno));
456 /* We want to maintain the bind socket if bind was enabled */
457 if (!(flags & OSMO_SOCK_F_BIND)) {
458 close(sfd);
459 sfd = -1;
460 }
461 continue;
462 }
463 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200464 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200465
466 freeaddrinfo(remote);
Harald Weltedda70fc2017-04-08 20:52:33 +0200467 if (rp == NULL) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200468 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable remote addr found for: %s:%u\n",
469 remote_host, remote_port);
470 if (sfd >= 0)
471 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200472 return -ENODEV;
473 }
474 }
475
Harald Weltec47bbda2017-07-13 16:13:26 +0200476 rc = osmo_sock_init_tail(sfd, type, flags);
477 if (rc < 0) {
478 close(sfd);
479 sfd = -1;
Harald Weltedda70fc2017-04-08 20:52:33 +0200480 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200481
Harald Weltedda70fc2017-04-08 20:52:33 +0200482 return sfd;
483}
484
Alexander Couzens43957e62020-08-01 21:56:45 +0200485#define _SOCKADDR_TO_STR(dest, sockaddr) do { \
486 if (osmo_sockaddr_str_from_sockaddr(&dest, &sockaddr->u.sas)) \
487 osmo_strlcpy(dest.ip, "Invalid IP", 11); \
488 } while (0)
489
490/*! Initialize a socket (including bind and/or connect)
491 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
492 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
493 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
494 * \param[in] local local address
495 * \param[in] remote remote address
496 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
497 * \returns socket file descriptor on success; negative on error
498 *
499 * This function creates a new socket of the
500 * \a type and \a proto and optionally binds it to the \a local
501 * as well as optionally connects it to the \a remote
502 * depending on the value * of \a flags parameter.
503 *
504 * As opposed to \ref osmo_sock_init(), this function allows to combine
505 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
506 * is useful if you want to connect to a remote host/port, but still
507 * want to bind that socket to either a specific local alias IP and/or a
508 * specific local source port.
509 *
510 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
511 * OSMO_SOCK_F_CONNECT, or both.
512 *
513 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
514 * non-blocking mode.
515 */
516int osmo_sock_init_osa(uint16_t type, uint8_t proto,
517 const struct osmo_sockaddr *local,
518 const struct osmo_sockaddr *remote,
519 unsigned int flags)
520{
521 int sfd = -1, rc, on = 1;
522 struct osmo_sockaddr_str sastr = {};
523
524 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
525 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
526 "BIND or CONNECT flags\n");
527 return -EINVAL;
528 }
529
530 if ((flags & OSMO_SOCK_F_BIND) && !local) {
531 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot BIND when local is NULL\n");
532 return -EINVAL;
533 }
534
535 if ((flags & OSMO_SOCK_F_CONNECT) && !remote) {
536 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot CONNECT when remote is NULL\n");
537 return -EINVAL;
538 }
539
540 if ((flags & OSMO_SOCK_F_BIND) &&
541 (flags & OSMO_SOCK_F_CONNECT) &&
542 local->u.sa.sa_family != remote->u.sa.sa_family) {
543 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: the family for "
544 "local and remote endpoint must be same.\n");
545 return -EINVAL;
546 }
547
548 /* figure out local side of socket */
549 if (flags & OSMO_SOCK_F_BIND) {
550 sfd = socket_helper_osa(local, type, proto, flags);
551 if (sfd < 0) {
552 _SOCKADDR_TO_STR(sastr, local);
553 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
554 sastr.ip, sastr.port);
555 return -ENODEV;
556 }
557
558 if (proto != IPPROTO_UDP || (flags & OSMO_SOCK_F_UDP_REUSEADDR)) {
559 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
560 &on, sizeof(on));
561 if (rc < 0) {
562 _SOCKADDR_TO_STR(sastr, local);
563 LOGP(DLGLOBAL, LOGL_ERROR,
564 "cannot setsockopt socket:"
565 " %s:%u: %s\n",
566 sastr.ip, sastr.port,
567 strerror(errno));
568 close(sfd);
569 return rc;
570 }
571 }
572
573 if (bind(sfd, &local->u.sa, sizeof(struct osmo_sockaddr)) == -1) {
574 _SOCKADDR_TO_STR(sastr, local);
575 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
576 sastr.ip, sastr.port, strerror(errno));
577 close(sfd);
578 return -1;
579 }
580 }
581
582 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
583 was already closed and func returned. If OSMO_SOCK_F_BIND is not
584 set, then sfd = -1 */
585
586 /* figure out remote side of socket */
587 if (flags & OSMO_SOCK_F_CONNECT) {
588 if (sfd < 0) {
589 sfd = socket_helper_osa(remote, type, proto, flags);
590 if (sfd < 0) {
591 return sfd;
592 }
593 }
594
595 rc = connect(sfd, &remote->u.sa, sizeof(struct osmo_sockaddr));
596 if (rc != 0 && errno != EINPROGRESS) {
597 _SOCKADDR_TO_STR(sastr, remote);
598 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
599 sastr.ip, sastr.port, strerror(errno));
600 close(sfd);
601 return rc;
602 }
603 }
604
605 rc = osmo_sock_init_tail(sfd, type, flags);
606 if (rc < 0) {
607 close(sfd);
608 sfd = -1;
609 }
610
611 return sfd;
612}
613
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200614#ifdef HAVE_LIBSCTP
615
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200616/* Check whether there's an IPv6 Addr as first option of any addrinfo item in the addrinfo set */
617static void addrinfo_has_v4v6addr(const struct addrinfo **result, size_t result_count, bool *has_v4, bool *has_v6)
618{
619 size_t host_idx;
620 *has_v4 = false;
621 *has_v6 = false;
622
623 for (host_idx = 0; host_idx < result_count; host_idx++) {
624 if (result[host_idx]->ai_family == AF_INET)
625 *has_v4 = true;
626 else if (result[host_idx]->ai_family == AF_INET6)
627 *has_v6 = true;
628 }
629}
630
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200631/* Check whether there's an IPv6 with IN6ADDR_ANY_INIT ("::") */
632static bool addrinfo_has_in6addr_any(const struct addrinfo **result, size_t result_count)
633{
634 size_t host_idx;
635 struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
636
637 for (host_idx = 0; host_idx < result_count; host_idx++) {
638 if (result[host_idx]->ai_family != AF_INET6)
639 continue;
640 if (memcmp(&((struct sockaddr_in6 *)result[host_idx]->ai_addr)->sin6_addr,
641 &in6addr_any, sizeof(in6addr_any)) == 0)
642 return true;
643 }
644 return false;
645}
646
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200647static int socket_helper_multiaddr(uint16_t family, uint16_t type, uint8_t proto, unsigned int flags)
648{
Harald Weltefaf6b702021-04-28 13:04:59 +0200649 int sfd, rc;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200650
651 sfd = socket(family, type, proto);
652 if (sfd == -1) {
653 LOGP(DLGLOBAL, LOGL_ERROR,
654 "Unable to create socket: %s\n", strerror(errno));
655 return sfd;
656 }
Harald Weltefaf6b702021-04-28 13:04:59 +0200657
658 rc = socket_helper_tail(sfd, flags);
659 if (rc < 0)
660 return rc;
661
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200662 return sfd;
663}
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200664
665/* Build array of addresses taking first addrinfo result of the requested family
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200666 * for each host in addrs_buf. */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200667static int addrinfo_to_sockaddr(uint16_t family, const struct addrinfo **result,
668 const char **hosts, int host_cont,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200669 uint8_t *addrs_buf, size_t addrs_buf_len) {
670 size_t host_idx, offset = 0;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200671 const struct addrinfo *rp;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200672
673 for (host_idx = 0; host_idx < host_cont; host_idx++) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200674 /* Addresses are ordered based on RFC 3484, see man getaddrinfo */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200675 for (rp = result[host_idx]; rp != NULL; rp = rp->ai_next) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200676 if (family != AF_UNSPEC && rp->ai_family != family)
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200677 continue;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200678 if (offset + rp->ai_addrlen > addrs_buf_len) {
679 LOGP(DLGLOBAL, LOGL_ERROR, "Output buffer to small: %zu\n",
680 addrs_buf_len);
681 return -ENOSPC;
682 }
683 memcpy(addrs_buf + offset, rp->ai_addr, rp->ai_addrlen);
684 offset += rp->ai_addrlen;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200685 break;
686 }
687 if (!rp) { /* No addr could be bound for this host! */
688 LOGP(DLGLOBAL, LOGL_ERROR, "No suitable remote address found for host: %s\n",
689 hosts[host_idx]);
690 return -ENODEV;
691 }
692 }
693 return 0;
694}
695
696/*! Initialize a socket (including bind and/or connect) with multiple local or remote addresses.
697 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
698 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
699 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
700 * \param[in] local_hosts array of char pointers (strings), each containing local host name or IP address in string form
701 * \param[in] local_hosts_cnt length of local_hosts (in items)
702 * \param[in] local_port local port number in host byte order
703 * \param[in] remote_host array of char pointers (strings), each containing remote host name or IP address in string form
704 * \param[in] remote_hosts_cnt length of remote_hosts (in items)
705 * \param[in] remote_port remote port number in host byte order
706 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
707 * \returns socket file descriptor on success; negative on error
708 *
709 * This function is similar to \ref osmo_sock_init2(), but can be passed an
710 * array of local or remote addresses for protocols supporting multiple
711 * addresses per socket, like SCTP (currently only one supported). This function
712 * should not be used by protocols not supporting this kind of features, but
713 * rather \ref osmo_sock_init2() should be used instead.
714 * See \ref osmo_sock_init2() for more information on flags and general behavior.
715 */
716int osmo_sock_init2_multiaddr(uint16_t family, uint16_t type, uint8_t proto,
717 const char **local_hosts, size_t local_hosts_cnt, uint16_t local_port,
718 const char **remote_hosts, size_t remote_hosts_cnt, uint16_t remote_port,
719 unsigned int flags)
720
721{
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200722 struct addrinfo *res_loc[OSMO_SOCK_MAX_ADDRS], *res_rem[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200723 int sfd = -1, rc, on = 1;
724 int i;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200725 bool loc_has_v4addr, rem_has_v4addr;
726 bool loc_has_v6addr, rem_has_v6addr;
727 struct sockaddr_in6 addrs_buf[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200728 char strbuf[512];
729
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200730 /* updated later in case of AF_UNSPEC */
731 loc_has_v4addr = rem_has_v4addr = (family == AF_INET);
732 loc_has_v6addr = rem_has_v6addr = (family == AF_INET6);
733
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200734 /* TODO: So far this function is only aimed for SCTP, but could be
735 reused in the future for other protocols with multi-addr support */
736 if (proto != IPPROTO_SCTP)
737 return -ENOTSUP;
738
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200739 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
740 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
741 "BIND or CONNECT flags\n");
742 return -EINVAL;
743 }
744
745 if (((flags & OSMO_SOCK_F_BIND) && !local_hosts_cnt) ||
746 ((flags & OSMO_SOCK_F_CONNECT) && !remote_hosts_cnt) ||
747 local_hosts_cnt > OSMO_SOCK_MAX_ADDRS ||
748 remote_hosts_cnt > OSMO_SOCK_MAX_ADDRS)
749 return -EINVAL;
750
751 /* figure out local side of socket */
752 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200753 rc = addrinfo_helper_multi(res_loc, family, type, proto, local_hosts,
754 local_hosts_cnt, local_port, true);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200755 if (rc < 0)
756 return -EINVAL;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200757 /* Figure out if there's any IPV4 or IPv6 addr in the set */
758 if (family == AF_UNSPEC)
759 addrinfo_has_v4v6addr((const struct addrinfo **)res_loc, local_hosts_cnt,
760 &loc_has_v4addr, &loc_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200761 }
762 /* figure out remote side of socket */
763 if (flags & OSMO_SOCK_F_CONNECT) {
764 rc = addrinfo_helper_multi(res_rem, family, type, proto, remote_hosts,
765 remote_hosts_cnt, remote_port, false);
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200766 if (rc < 0) {
767 rc = -EINVAL;
768 goto ret_freeaddrinfo_loc;
769 }
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200770 /* Figure out if there's any IPv4 or IPv6 addr in the set */
771 if (family == AF_UNSPEC)
772 addrinfo_has_v4v6addr((const struct addrinfo **)res_rem, remote_hosts_cnt,
773 &rem_has_v4addr, &rem_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200774 }
775
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200776 if (((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) &&
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200777 !addrinfo_has_in6addr_any((const struct addrinfo **)res_loc, local_hosts_cnt) &&
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200778 (loc_has_v4addr != rem_has_v4addr || loc_has_v6addr != rem_has_v6addr)) {
779 LOGP(DLGLOBAL, LOGL_ERROR, "Invalid v4 vs v6 in local vs remote addresses\n");
780 rc = -EINVAL;
781 goto ret_freeaddrinfo;
782 }
783
784 sfd = socket_helper_multiaddr(loc_has_v6addr ? AF_INET6 : AF_INET,
785 type, proto, flags);
786 if (sfd < 0) {
787 rc = sfd;
788 goto ret_freeaddrinfo;
789 }
790
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200791 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200792 /* Since so far we only allow IPPROTO_SCTP in this function,
793 no need to check below for "proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR" */
794 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
795 &on, sizeof(on));
796 if (rc < 0) {
797 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
798 LOGP(DLGLOBAL, LOGL_ERROR,
799 "cannot setsockopt socket:"
800 " %s:%u: %s\n",
801 strbuf, local_port,
802 strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200803 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200804 }
805
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200806 /* Build array of addresses taking first entry for each host.
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200807 TODO: Ideally we should use backtracking storing last used
808 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200809 /* 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 +0200810 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_loc,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200811 local_hosts, local_hosts_cnt,
812 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200813 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200814 rc = -ENODEV;
815 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200816 }
817
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200818 rc = sctp_bindx(sfd, (struct sockaddr *)addrs_buf, local_hosts_cnt, SCTP_BINDX_ADD_ADDR);
819 if (rc == -1) {
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200820 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
821 LOGP(DLGLOBAL, LOGL_NOTICE, "unable to bind socket: %s:%u: %s\n",
822 strbuf, local_port, strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200823 rc = -ENODEV;
824 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200825 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200826 }
827
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200828 if (flags & OSMO_SOCK_F_CONNECT) {
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200829 /* Build array of addresses taking first of same family for each host.
830 TODO: Ideally we should use backtracking storing last used
831 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200832 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_rem,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200833 remote_hosts, remote_hosts_cnt,
834 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200835 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200836 rc = -ENODEV;
837 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200838 }
839
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200840 rc = sctp_connectx(sfd, (struct sockaddr *)addrs_buf, remote_hosts_cnt, NULL);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200841 if (rc != 0 && errno != EINPROGRESS) {
842 multiaddr_snprintf(strbuf, sizeof(strbuf), remote_hosts, remote_hosts_cnt);
843 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
844 strbuf, remote_port, strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200845 rc = -ENODEV;
846 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200847 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200848 }
849
850 rc = osmo_sock_init_tail(sfd, type, flags);
851 if (rc < 0) {
852 close(sfd);
853 sfd = -1;
854 }
855
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200856 rc = sfd;
857 goto ret_freeaddrinfo;
858
859ret_close:
860 if (sfd >= 0)
861 close(sfd);
862ret_freeaddrinfo:
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200863 if (flags & OSMO_SOCK_F_CONNECT) {
864 for (i = 0; i < remote_hosts_cnt; i++)
865 freeaddrinfo(res_rem[i]);
866 }
867ret_freeaddrinfo_loc:
868 if (flags & OSMO_SOCK_F_BIND) {
869 for (i = 0; i < local_hosts_cnt; i++)
870 freeaddrinfo(res_loc[i]);
871 }
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200872 return rc;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200873}
874#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200875
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200876/*! Initialize a socket (including bind/connect)
Harald Welteba6988b2011-08-17 12:46:48 +0200877 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
878 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
879 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
880 * \param[in] host remote host name or IP address in string form
881 * \param[in] port remote port number in host byte order
882 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200883 * \returns socket file descriptor on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200884 *
885 * This function creates a new socket of the designated \a family, \a
886 * type and \a proto and optionally binds or connects it, depending on
887 * the value of \a flags parameter.
888 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200889int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200890 const char *host, uint16_t port, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200891{
Harald Weltedda70fc2017-04-08 20:52:33 +0200892 struct addrinfo *result, *rp;
Pau Espin Pedrol6fe865d2021-07-15 13:08:08 +0200893 int sfd = -1; /* initialize to avoid uninitialized false warnings on some gcc versions (11.1.0) */
894 int on = 1;
895 int rc;
Harald Welte33cb71a2011-05-21 18:54:32 +0200896
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200897 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200898 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100899 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: both bind and connect flags set:"
Neels Hofmeyrb7f191f2016-08-29 11:22:03 +0200900 " %s:%u\n", host, port);
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200901 return -EINVAL;
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200902 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200903
Harald Weltedda70fc2017-04-08 20:52:33 +0200904 result = addrinfo_helper(family, type, proto, host, port, flags & OSMO_SOCK_F_BIND);
Pau Espin Pedrolba828c32020-08-20 18:28:10 +0200905 if (!result)
Harald Welte33cb71a2011-05-21 18:54:32 +0200906 return -EINVAL;
Harald Welte33cb71a2011-05-21 18:54:32 +0200907
908 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200909 sfd = socket_helper(rp, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200910 if (sfd == -1)
911 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200912
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200913 if (flags & OSMO_SOCK_F_CONNECT) {
914 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200915 if (rc != 0 && errno != EINPROGRESS) {
916 close(sfd);
917 continue;
918 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200919 } else {
Philipp Maier73196e72018-08-23 20:11:50 +0200920 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200921 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
922 &on, sizeof(on));
923 if (rc < 0) {
924 LOGP(DLGLOBAL, LOGL_ERROR,
925 "cannot setsockopt socket:"
926 " %s:%u: %s\n",
927 host, port, strerror(errno));
928 close(sfd);
929 continue;
930 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200931 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200932 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
933 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket:"
934 "%s:%u: %s\n",
935 host, port, strerror(errno));
936 close(sfd);
937 continue;
938 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200939 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200940 break;
Harald Welte33cb71a2011-05-21 18:54:32 +0200941 }
942 freeaddrinfo(result);
943
944 if (rp == NULL) {
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200945 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable addr found for: %s:%u\n",
946 host, port);
Harald Welte33cb71a2011-05-21 18:54:32 +0200947 return -ENODEV;
948 }
Harald Welte68b15742011-05-22 21:47:29 +0200949
Philipp Maier73196e72018-08-23 20:11:50 +0200950 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200951 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
952 if (rc < 0) {
953 LOGP(DLGLOBAL, LOGL_ERROR,
954 "cannot setsockopt socket: %s:%u: %s\n", host,
955 port, strerror(errno));
956 close(sfd);
957 sfd = -1;
958 }
Philipp Maier0659c5d2018-08-01 12:43:08 +0200959 }
Harald Welte68b15742011-05-22 21:47:29 +0200960
Harald Weltec47bbda2017-07-13 16:13:26 +0200961 rc = osmo_sock_init_tail(sfd, type, flags);
962 if (rc < 0) {
963 close(sfd);
964 sfd = -1;
Harald Welte68b15742011-05-22 21:47:29 +0200965 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200966
Harald Welte68b15742011-05-22 21:47:29 +0200967 return sfd;
968}
969
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200970/*! fill \ref osmo_fd for a give sfd
Max862ba652014-10-13 14:54:25 +0200971 * \param[out] ofd file descriptor (will be filled in)
972 * \param[in] sfd socket file descriptor
Harald Welte24980ba2021-04-23 14:07:18 +0200973 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200974 * \returns socket fd on success; negative on error
Max862ba652014-10-13 14:54:25 +0200975 *
976 * This function fills the \a ofd structure.
977 */
Harald Welte24980ba2021-04-23 14:07:18 +0200978static inline int osmo_fd_init_ofd(struct osmo_fd *ofd, int sfd, unsigned int flags)
Max862ba652014-10-13 14:54:25 +0200979{
980 int rc;
981
982 if (sfd < 0)
983 return sfd;
984
985 ofd->fd = sfd;
Harald Welte16886992019-03-20 10:26:39 +0100986 ofd->when = OSMO_FD_READ;
Max862ba652014-10-13 14:54:25 +0200987
Harald Welte24980ba2021-04-23 14:07:18 +0200988 /* if we're doing a non-blocking connect, the completion will be signaled
989 * by marking the fd as WRITE-able. So in this exceptional case, we're
990 * also interested in when the socket becomes write-able */
991 if ((flags & (OSMO_SOCK_F_CONNECT|OSMO_SOCK_F_NONBLOCK)) ==
992 (OSMO_SOCK_F_CONNECT|OSMO_SOCK_F_NONBLOCK)) {
993 ofd->when |= OSMO_FD_WRITE;
994 }
995
Max862ba652014-10-13 14:54:25 +0200996 rc = osmo_fd_register(ofd);
997 if (rc < 0) {
998 close(sfd);
999 return rc;
1000 }
1001
1002 return sfd;
1003}
1004
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001005/*! Initialize a socket and fill \ref osmo_fd
Katerina Barone-Adesic28c6a02013-02-15 13:27:59 +01001006 * \param[out] ofd file descriptor (will be filled in)
Harald Welteba6988b2011-08-17 12:46:48 +02001007 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
1008 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1009 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1010 * \param[in] host remote host name or IP address in string form
1011 * \param[in] port remote port number in host byte order
1012 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001013 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +02001014 *
1015 * This function creates (and optionall binds/connects) a socket using
1016 * \ref osmo_sock_init, but also fills the \a ofd structure.
1017 */
Harald Welte68b15742011-05-22 21:47:29 +02001018int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001019 const char *host, uint16_t port, unsigned int flags)
Harald Welte68b15742011-05-22 21:47:29 +02001020{
Harald Welte24980ba2021-04-23 14:07:18 +02001021 return osmo_fd_init_ofd(ofd, osmo_sock_init(family, type, proto, host, port, flags), flags);
Harald Welte33cb71a2011-05-21 18:54:32 +02001022}
1023
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001024/*! Initialize a socket and fill \ref osmo_fd
Pau Espin Pedrol75989e62017-05-26 12:39:53 +02001025 * \param[out] ofd file descriptor (will be filled in)
1026 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
1027 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1028 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1029 * \param[in] local_host local host name or IP address in string form
1030 * \param[in] local_port local port number in host byte order
1031 * \param[in] remote_host remote host name or IP address in string form
1032 * \param[in] remote_port remote port number in host byte order
1033 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
1034 * \returns socket fd on success; negative on error
1035 *
1036 * This function creates (and optionall binds/connects) a socket using
1037 * \ref osmo_sock_init2, but also fills the \a ofd structure.
1038 */
1039int osmo_sock_init2_ofd(struct osmo_fd *ofd, int family, int type, int proto,
1040 const char *local_host, uint16_t local_port,
1041 const char *remote_host, uint16_t remote_port, unsigned int flags)
1042{
1043 return osmo_fd_init_ofd(ofd, osmo_sock_init2(family, type, proto, local_host,
Harald Welte24980ba2021-04-23 14:07:18 +02001044 local_port, remote_host, remote_port, flags), flags);
Pau Espin Pedrol75989e62017-05-26 12:39:53 +02001045}
1046
Alexander Couzens43957e62020-08-01 21:56:45 +02001047int osmo_sock_init_osa_ofd(struct osmo_fd *ofd, int type, int proto,
1048 const struct osmo_sockaddr *local,
1049 const struct osmo_sockaddr *remote, unsigned int flags)
1050{
Harald Welte24980ba2021-04-23 14:07:18 +02001051 return osmo_fd_init_ofd(ofd, osmo_sock_init_osa(type, proto, local, remote, flags), flags);
Alexander Couzens43957e62020-08-01 21:56:45 +02001052}
1053
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001054/*! Initialize a socket and fill \ref sockaddr
Harald Welteba6988b2011-08-17 12:46:48 +02001055 * \param[out] ss socket address (will be filled in)
1056 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1057 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1058 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001059 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +02001060 *
1061 * This function creates (and optionall binds/connects) a socket using
1062 * \ref osmo_sock_init, but also fills the \a ss structure.
1063 */
Harald Welte33cb71a2011-05-21 18:54:32 +02001064int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001065 uint8_t proto, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +02001066{
1067 char host[NI_MAXHOST];
1068 uint16_t port;
1069 struct sockaddr_in *sin;
1070 struct sockaddr_in6 *sin6;
1071 int s, sa_len;
1072
1073 /* determine port and host from ss */
1074 switch (ss->sa_family) {
1075 case AF_INET:
1076 sin = (struct sockaddr_in *) ss;
1077 sa_len = sizeof(struct sockaddr_in);
1078 port = ntohs(sin->sin_port);
1079 break;
1080 case AF_INET6:
1081 sin6 = (struct sockaddr_in6 *) ss;
1082 sa_len = sizeof(struct sockaddr_in6);
1083 port = ntohs(sin6->sin6_port);
1084 break;
1085 default:
1086 return -EINVAL;
1087 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001088
1089 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
1090 NULL, 0, NI_NUMERICHOST);
1091 if (s != 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001092 LOGP(DLGLOBAL, LOGL_ERROR, "getnameinfo failed:"
1093 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001094 return s;
1095 }
1096
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001097 return osmo_sock_init(ss->sa_family, type, proto, host, port, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +02001098}
1099
1100static int sockaddr_equal(const struct sockaddr *a,
Harald Weltee4764422011-05-22 12:25:57 +02001101 const struct sockaddr *b, unsigned int len)
Harald Welte33cb71a2011-05-21 18:54:32 +02001102{
1103 struct sockaddr_in *sin_a, *sin_b;
1104 struct sockaddr_in6 *sin6_a, *sin6_b;
1105
1106 if (a->sa_family != b->sa_family)
1107 return 0;
1108
1109 switch (a->sa_family) {
1110 case AF_INET:
1111 sin_a = (struct sockaddr_in *)a;
1112 sin_b = (struct sockaddr_in *)b;
1113 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
1114 sizeof(struct in_addr)))
1115 return 1;
1116 break;
1117 case AF_INET6:
1118 sin6_a = (struct sockaddr_in6 *)a;
1119 sin6_b = (struct sockaddr_in6 *)b;
1120 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
1121 sizeof(struct in6_addr)))
1122 return 1;
1123 break;
1124 }
1125 return 0;
1126}
1127
Eric8ae40cb2021-09-27 22:10:01 +02001128/* linux has a default route:
1129local 127.0.0.0/8 dev lo proto kernel scope host src 127.0.0.1
1130*/
1131static int sockaddr_is_local_routed(const struct sockaddr *a)
1132{
1133#if __linux__
1134 if (a->sa_family != AF_INET)
1135 return 0;
1136
1137 uint32_t address = ((struct sockaddr_in *)a)->sin_addr.s_addr; /* already BE */
1138 uint32_t eightmask = htonl(0xff000000); /* /8 mask */
1139 uint32_t local_prefix_127 = htonl(0x7f000000); /* 127.0.0.0 */
1140
1141 if ((address & eightmask) == local_prefix_127)
1142 return 1;
1143#endif
1144 return 0;
1145}
1146
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001147/*! Determine if the given address is a local address
Harald Welteba6988b2011-08-17 12:46:48 +02001148 * \param[in] addr Socket Address
1149 * \param[in] addrlen Length of socket address in bytes
1150 * \returns 1 if address is local, 0 otherwise.
1151 */
Harald Weltebc32d052012-04-08 11:31:32 +02001152int osmo_sockaddr_is_local(struct sockaddr *addr, unsigned int addrlen)
Harald Welte33cb71a2011-05-21 18:54:32 +02001153{
1154 struct ifaddrs *ifaddr, *ifa;
1155
Eric8ae40cb2021-09-27 22:10:01 +02001156 if (sockaddr_is_local_routed(addr))
1157 return 1;
1158
Harald Welte33cb71a2011-05-21 18:54:32 +02001159 if (getifaddrs(&ifaddr) == -1) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001160 LOGP(DLGLOBAL, LOGL_ERROR, "getifaddrs:"
1161 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001162 return -EIO;
1163 }
1164
1165 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
Harald Welte4d3a7b12011-05-24 21:31:53 +02001166 if (!ifa->ifa_addr)
1167 continue;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001168 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen)) {
1169 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001170 return 1;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001171 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001172 }
1173
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001174 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001175 return 0;
1176}
Harald Weltee4764422011-05-22 12:25:57 +02001177
Max9d7a2472018-11-20 15:18:31 +01001178/*! Convert sockaddr_in to IP address as char string and port as uint16_t.
1179 * \param[out] addr String buffer to write IP address to, or NULL.
1180 * \param[out] addr_len Size of \a addr.
1181 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1182 * \param[in] sin Sockaddr to convert.
1183 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1184 */
1185size_t osmo_sockaddr_in_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1186 const struct sockaddr_in *sin)
1187{
1188 if (port)
1189 *port = ntohs(sin->sin_port);
1190
1191 if (addr)
1192 return osmo_strlcpy(addr, inet_ntoa(sin->sin_addr), addr_len);
1193
1194 return 0;
1195}
1196
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001197/*! Convert sockaddr to IP address as char string and port as uint16_t.
1198 * \param[out] addr String buffer to write IP address to, or NULL.
1199 * \param[out] addr_len Size of \a addr.
1200 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1201 * \param[in] sa Sockaddr to convert.
1202 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1203 */
1204unsigned int osmo_sockaddr_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1205 const struct sockaddr *sa)
1206{
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001207
Pau Espin Pedrol1a3d24e2020-08-28 18:31:32 +02001208 const struct sockaddr_in6 *sin6;
1209
1210 switch (sa->sa_family) {
1211 case AF_INET:
1212 return osmo_sockaddr_in_to_str_and_uint(addr, addr_len, port,
1213 (const struct sockaddr_in *)sa);
1214 case AF_INET6:
1215 sin6 = (const struct sockaddr_in6 *)sa;
1216 if (port)
1217 *port = ntohs(sin6->sin6_port);
1218 if (addr && inet_ntop(sa->sa_family, &sin6->sin6_addr, addr, addr_len))
1219 return strlen(addr);
1220 break;
1221 }
1222 return 0;
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001223}
1224
Pau Espin Pedrol5cc4fe42020-08-31 12:52:06 +02001225/*! inet_ntop() wrapper for a struct sockaddr.
1226 * \param[in] sa source sockaddr to get the address from.
1227 * \param[out] dst string buffer of at least INET6_ADDRSTRLEN size.
1228 * \returns returns a non-null pointer to dst. NULL is returned if there was an
1229 * error, with errno set to indicate the error.
1230 */
1231const char *osmo_sockaddr_ntop(const struct sockaddr *sa, char *dst)
1232{
1233 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1234 return inet_ntop(osa->u.sa.sa_family,
1235 osa->u.sa.sa_family == AF_INET6 ?
1236 (const void *)&osa->u.sin6.sin6_addr :
1237 (const void *)&osa->u.sin.sin_addr,
1238 dst, INET6_ADDRSTRLEN);
1239}
1240
1241/*! Get sockaddr port content (in host byte order)
1242 * \param[in] sa source sockaddr to get the port from.
1243 * \returns returns the sockaddr port in host byte order
1244 */
1245uint16_t osmo_sockaddr_port(const struct sockaddr *sa)
1246{
1247 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1248 switch (osa->u.sa.sa_family) {
1249 case AF_INET6:
1250 return ntohs(osa->u.sin6.sin6_port);
1251 case AF_INET:
1252 return ntohs(osa->u.sin.sin_port);
1253 }
1254 return 0;
1255}
1256
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001257/*! Initialize a unix domain socket (including bind/connect)
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001258 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1259 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1260 * \param[in] socket_path path to identify the socket
1261 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001262 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001263 *
1264 * This function creates a new unix domain socket, \a
1265 * type and \a proto and optionally binds or connects it, depending on
1266 * the value of \a flags parameter.
1267 */
Eric Wildeb5769b2019-06-27 15:31:17 +02001268#if defined(__clang__) && defined(SUN_LEN)
1269__attribute__((no_sanitize("undefined")))
1270#endif
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001271int osmo_sock_unix_init(uint16_t type, uint8_t proto,
1272 const char *socket_path, unsigned int flags)
1273{
1274 struct sockaddr_un local;
Harald Weltefaf6b702021-04-28 13:04:59 +02001275 int sfd, rc;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001276 unsigned int namelen;
1277
1278 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
1279 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT))
1280 return -EINVAL;
1281
1282 local.sun_family = AF_UNIX;
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001283 /* When an AF_UNIX socket is bound, sun_path should be NUL-terminated. See unix(7) man page. */
1284 if (osmo_strlcpy(local.sun_path, socket_path, sizeof(local.sun_path)) >= sizeof(local.sun_path)) {
Stefan Sperling896ff6d2018-08-28 14:34:17 +02001285 LOGP(DLGLOBAL, LOGL_ERROR, "Socket path exceeds maximum length of %zd bytes: %s\n",
1286 sizeof(local.sun_path), socket_path);
1287 return -ENOSPC;
1288 }
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001289
1290#if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001291 local.sun_len = strlen(local.sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001292#endif
1293#if defined(BSD44SOCKETS) || defined(SUN_LEN)
1294 namelen = SUN_LEN(&local);
1295#else
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001296 namelen = strlen(local.sun_path) +
1297 offsetof(struct sockaddr_un, sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001298#endif
1299
1300 sfd = socket(AF_UNIX, type, proto);
1301 if (sfd < 0)
1302 return -1;
1303
1304 if (flags & OSMO_SOCK_F_CONNECT) {
1305 rc = connect(sfd, (struct sockaddr *)&local, namelen);
1306 if (rc < 0)
1307 goto err;
1308 } else {
1309 unlink(local.sun_path);
1310 rc = bind(sfd, (struct sockaddr *)&local, namelen);
1311 if (rc < 0)
1312 goto err;
1313 }
1314
Harald Weltefaf6b702021-04-28 13:04:59 +02001315 rc = socket_helper_tail(sfd, flags);
1316 if (rc < 0)
1317 return rc;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001318
Harald Weltec47bbda2017-07-13 16:13:26 +02001319 rc = osmo_sock_init_tail(sfd, type, flags);
1320 if (rc < 0) {
1321 close(sfd);
1322 sfd = -1;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001323 }
1324
1325 return sfd;
1326err:
1327 close(sfd);
1328 return -1;
1329}
1330
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001331/*! Initialize a unix domain socket and fill \ref osmo_fd
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001332 * \param[out] ofd file descriptor (will be filled in)
1333 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1334 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1335 * \param[in] socket_path path to identify the socket
1336 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001337 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001338 *
Vadim Yanitskiyb606d762019-06-01 19:02:47 +07001339 * This function creates (and optionally binds/connects) a socket
1340 * using osmo_sock_unix_init, but also fills the ofd structure.
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001341 */
1342int osmo_sock_unix_init_ofd(struct osmo_fd *ofd, uint16_t type, uint8_t proto,
1343 const char *socket_path, unsigned int flags)
1344{
Harald Welte24980ba2021-04-23 14:07:18 +02001345 return osmo_fd_init_ofd(ofd, osmo_sock_unix_init(type, proto, socket_path, flags), flags);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001346}
1347
Neels Hofmeyr01457512018-12-12 01:48:54 +01001348/*! Get the IP and/or port number on socket in separate string buffers.
Oliver Smith7acd5d02018-10-25 11:16:36 +02001349 * \param[in] fd file descriptor of socket
1350 * \param[out] ip IP address (will be filled in when not NULL)
1351 * \param[in] ip_len length of the ip buffer
1352 * \param[out] port number (will be filled in when not NULL)
1353 * \param[in] port_len length of the port buffer
1354 * \param[in] local (true) or remote (false) name will get looked at
1355 * \returns 0 on success; negative otherwise
1356 */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001357int 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 +02001358{
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001359 struct sockaddr_storage sa;
Oliver Smith7acd5d02018-10-25 11:16:36 +02001360 socklen_t len = sizeof(sa);
Oliver Smith860651e2018-10-30 14:31:57 +01001361 char ipbuf[INET6_ADDRSTRLEN], portbuf[6];
Oliver Smith7acd5d02018-10-25 11:16:36 +02001362 int rc;
1363
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001364 rc = local ? getsockname(fd, (struct sockaddr*)&sa, &len) : getpeername(fd, (struct sockaddr*)&sa, &len);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001365 if (rc < 0)
1366 return rc;
1367
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001368 rc = getnameinfo((const struct sockaddr*)&sa, len, ipbuf, sizeof(ipbuf),
Oliver Smith7acd5d02018-10-25 11:16:36 +02001369 portbuf, sizeof(portbuf),
1370 NI_NUMERICHOST | NI_NUMERICSERV);
1371 if (rc < 0)
1372 return rc;
1373
1374 if (ip)
1375 strncpy(ip, ipbuf, ip_len);
1376 if (port)
1377 strncpy(port, portbuf, port_len);
1378 return 0;
1379}
1380
1381/*! Get local IP address on socket
1382 * \param[in] fd file descriptor of socket
1383 * \param[out] ip IP address (will be filled in)
1384 * \param[in] len length of the output buffer
1385 * \returns 0 on success; negative otherwise
1386 */
1387int osmo_sock_get_local_ip(int fd, char *ip, size_t len)
1388{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001389 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001390}
1391
1392/*! Get local port on socket
1393 * \param[in] fd file descriptor of socket
1394 * \param[out] port number (will be filled in)
1395 * \param[in] len length of the output buffer
1396 * \returns 0 on success; negative otherwise
1397 */
1398int osmo_sock_get_local_ip_port(int fd, char *port, size_t len)
1399{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001400 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001401}
1402
1403/*! Get remote IP address on socket
1404 * \param[in] fd file descriptor of socket
1405 * \param[out] ip IP address (will be filled in)
1406 * \param[in] len length of the output buffer
1407 * \returns 0 on success; negative otherwise
1408 */
1409int osmo_sock_get_remote_ip(int fd, char *ip, size_t len)
1410{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001411 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001412}
1413
1414/*! Get remote port on socket
1415 * \param[in] fd file descriptor of socket
1416 * \param[out] port number (will be filled in)
1417 * \param[in] len length of the output buffer
1418 * \returns 0 on success; negative otherwise
1419 */
1420int osmo_sock_get_remote_ip_port(int fd, char *port, size_t len)
1421{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001422 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001423}
1424
Neels Hofmeyr01457512018-12-12 01:48:54 +01001425/*! Get address/port information on socket in dyn-alloc string like "(r=1.2.3.4:5<->l=6.7.8.9:10)".
1426 * Usually, it is better to use osmo_sock_get_name2() for a static string buffer or osmo_sock_get_name_buf() for a
1427 * caller provided string buffer, to avoid the dynamic talloc allocation.
Harald Welte48f55832017-01-26 00:03:10 +01001428 * \param[in] ctx talloc context from which to allocate string buffer
1429 * \param[in] fd file descriptor of socket
Neels Hofmeyr01457512018-12-12 01:48:54 +01001430 * \returns string identifying the connection of this socket, talloc'd from ctx.
Harald Welte48f55832017-01-26 00:03:10 +01001431 */
Harald Weltec0dfc9d2019-03-18 18:29:43 +01001432char *osmo_sock_get_name(const void *ctx, int fd)
Harald Welte48f55832017-01-26 00:03:10 +01001433{
Philipp Maier64b51eb2019-01-14 11:59:11 +01001434 char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001435 int rc;
1436 rc = osmo_sock_get_name_buf(str, sizeof(str), fd);
1437 if (rc <= 0)
1438 return NULL;
1439 return talloc_asprintf(ctx, "(%s)", str);
1440}
1441
1442/*! Get address/port information on socket in provided string buffer, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1443 * This does not include braces like osmo_sock_get_name().
1444 * \param[out] str Destination string buffer.
1445 * \param[in] str_len sizeof(str).
1446 * \param[in] fd File descriptor of socket.
1447 * \return String length as returned by snprintf(), or negative on error.
1448 */
1449int osmo_sock_get_name_buf(char *str, size_t str_len, int fd)
1450{
Oliver Smith860651e2018-10-30 14:31:57 +01001451 char hostbuf_l[INET6_ADDRSTRLEN], hostbuf_r[INET6_ADDRSTRLEN];
1452 char portbuf_l[6], portbuf_r[6];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001453 int rc;
Harald Welte48f55832017-01-26 00:03:10 +01001454
Oliver Smith7acd5d02018-10-25 11:16:36 +02001455 /* get local */
Harald Welteea9ea522019-05-10 09:28:24 +02001456 if ((rc = osmo_sock_get_ip_and_port(fd, hostbuf_l, sizeof(hostbuf_l), portbuf_l, sizeof(portbuf_l), true))) {
1457 osmo_strlcpy(str, "<error-in-getsockname>", str_len);
Neels Hofmeyr01457512018-12-12 01:48:54 +01001458 return rc;
Harald Welteea9ea522019-05-10 09:28:24 +02001459 }
Harald Welte48f55832017-01-26 00:03:10 +01001460
Oliver Smith7acd5d02018-10-25 11:16:36 +02001461 /* get remote */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001462 if (osmo_sock_get_ip_and_port(fd, hostbuf_r, sizeof(hostbuf_r), portbuf_r, sizeof(portbuf_r), false) != 0)
1463 return snprintf(str, str_len, "r=NULL<->l=%s:%s", hostbuf_l, portbuf_l);
Harald Welte48f55832017-01-26 00:03:10 +01001464
Neels Hofmeyr01457512018-12-12 01:48:54 +01001465 return snprintf(str, str_len, "r=%s:%s<->l=%s:%s", hostbuf_r, portbuf_r, hostbuf_l, portbuf_l);
1466}
1467
1468/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1469 * This does not include braces like osmo_sock_get_name().
1470 * \param[in] fd File descriptor of socket.
1471 * \return Static string buffer containing the result.
1472 */
1473const char *osmo_sock_get_name2(int fd)
1474{
Harald Welte171ef822019-03-28 10:49:05 +01001475 static __thread char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001476 osmo_sock_get_name_buf(str, sizeof(str), fd);
1477 return str;
Harald Welte48f55832017-01-26 00:03:10 +01001478}
1479
Harald Welte179f3572019-03-18 18:38:47 +01001480/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1481 * This does not include braces like osmo_sock_get_name().
1482 * \param[in] fd File descriptor of socket.
1483 * \return Static string buffer containing the result.
1484 */
1485char *osmo_sock_get_name2_c(const void *ctx, int fd)
1486{
1487 char *str = talloc_size(ctx, OSMO_SOCK_NAME_MAXLEN);
1488 if (!str)
1489 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001490 osmo_sock_get_name_buf(str, OSMO_SOCK_NAME_MAXLEN, fd);
Harald Welte179f3572019-03-18 18:38:47 +01001491 return str;
1492}
1493
Harald Weltee30d7e62017-07-13 16:02:50 +02001494static int sock_get_domain(int fd)
1495{
1496 int domain;
1497#ifdef SO_DOMAIN
1498 socklen_t dom_len = sizeof(domain);
1499 int rc;
1500
1501 rc = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &dom_len);
1502 if (rc < 0)
1503 return rc;
1504#else
1505 /* This of course sucks, but what shall we do on OSs like
1506 * FreeBSD that don't seem to expose a method by which one can
1507 * learn the address family of a socket? */
1508 domain = AF_INET;
1509#endif
1510 return domain;
1511}
1512
1513
1514/*! Activate or de-activate local loop-back of transmitted multicast packets
1515 * \param[in] fd file descriptor of related socket
1516 * \param[in] enable Enable (true) or disable (false) loop-back
1517 * \returns 0 on success; negative otherwise */
1518int osmo_sock_mcast_loop_set(int fd, bool enable)
1519{
1520 int domain, loop = 0;
1521
1522 if (enable)
1523 loop = 1;
1524
1525 domain = sock_get_domain(fd);
1526 if (domain < 0)
1527 return domain;
1528
1529 switch (domain) {
1530 case AF_INET:
1531 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1532 case AF_INET6:
1533 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop));
1534 default:
1535 return -EINVAL;
1536 }
1537}
1538
1539/*! Set the TTL of outbound multicast packets
1540 * \param[in] fd file descriptor of related socket
1541 * \param[in] ttl TTL of to-be-sent multicast packets
1542 * \returns 0 on success; negative otherwise */
1543int osmo_sock_mcast_ttl_set(int fd, uint8_t ttl)
1544{
1545 int domain, ttli = ttl;
1546
1547 domain = sock_get_domain(fd);
1548 if (domain < 0)
1549 return domain;
1550
1551 switch (domain) {
1552 case AF_INET:
1553 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttli, sizeof(ttli));
1554 case AF_INET6:
1555 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttli, sizeof(ttli));
1556 default:
1557 return -EINVAL;
1558 }
1559}
1560
Harald Welte44b99262020-03-07 14:59:05 +01001561/*! Set the network device to which we should bind the multicast socket
1562 * \param[in] fd file descriptor of related socket
1563 * \param[in] ifname name of network interface to user for multicast
1564 * \returns 0 on success; negative otherwise */
1565int osmo_sock_mcast_iface_set(int fd, const char *ifname)
1566{
1567 unsigned int ifindex;
1568 struct ip_mreqn mr;
1569
1570 /* first, resolve interface name to ifindex */
1571 ifindex = if_nametoindex(ifname);
1572 if (ifindex == 0)
1573 return -errno;
1574
1575 /* next, configure kernel to use that ifindex for this sockets multicast traffic */
1576 memset(&mr, 0, sizeof(mr));
1577 mr.imr_ifindex = ifindex;
1578 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mr, sizeof(mr));
1579}
1580
1581
Harald Weltee30d7e62017-07-13 16:02:50 +02001582/*! Enable/disable receiving all multicast packets, even for non-subscribed groups
1583 * \param[in] fd file descriptor of related socket
1584 * \param[in] enable Enable or Disable receiving of all packets
1585 * \returns 0 on success; negative otherwise */
1586int osmo_sock_mcast_all_set(int fd, bool enable)
1587{
1588 int domain, all = 0;
1589
1590 if (enable)
1591 all = 1;
1592
1593 domain = sock_get_domain(fd);
1594 if (domain < 0)
1595 return domain;
1596
1597 switch (domain) {
1598 case AF_INET:
1599#ifdef IP_MULTICAST_ALL
1600 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_ALL, &all, sizeof(all));
1601#endif
1602 case AF_INET6:
1603 /* there seems no equivalent ?!? */
1604 default:
1605 return -EINVAL;
1606 }
1607}
1608
1609/* FreeBSD calls the socket option differently */
1610#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
1611#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1612#endif
1613
1614/*! Subscribe to the given IP multicast group
1615 * \param[in] fd file descriptor of related scoket
1616 * \param[in] grp_addr ASCII representation of the multicast group address
1617 * \returns 0 on success; negative otherwise */
1618int osmo_sock_mcast_subscribe(int fd, const char *grp_addr)
1619{
1620 int rc, domain;
1621 struct ip_mreq mreq;
1622 struct ipv6_mreq mreq6;
1623 struct in6_addr i6a;
1624
1625 domain = sock_get_domain(fd);
1626 if (domain < 0)
1627 return domain;
1628
1629 switch (domain) {
1630 case AF_INET:
1631 memset(&mreq, 0, sizeof(mreq));
1632 mreq.imr_multiaddr.s_addr = inet_addr(grp_addr);
1633 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1634 return setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
1635#ifdef IPV6_ADD_MEMBERSHIP
1636 case AF_INET6:
1637 memset(&mreq6, 0, sizeof(mreq6));
1638 rc = inet_pton(AF_INET6, grp_addr, (void *)&i6a);
1639 if (rc < 0)
1640 return -EINVAL;
1641 mreq6.ipv6mr_multiaddr = i6a;
1642 return setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
1643#endif
1644 default:
1645 return -EINVAL;
1646 }
1647}
1648
Philipp Maier2d2490e2017-10-20 19:41:26 +02001649/*! Determine the matching local IP-address for a given remote IP-Address.
1650 * \param[out] local_ip caller provided memory for resulting local IP-address
1651 * \param[in] remote_ip remote IP-address
Philipp Maier2d2490e2017-10-20 19:41:26 +02001652 * \returns 0 on success; negative otherwise
1653 *
1654 * The function accepts IPv4 and IPv6 address strings. The caller must provide
1655 * at least INET6_ADDRSTRLEN bytes for local_ip if an IPv6 is expected as
1656 * as result. For IPv4 addresses the required amount is INET_ADDRSTRLEN. */
1657int osmo_sock_local_ip(char *local_ip, const char *remote_ip)
1658{
1659 int sfd;
1660 int rc;
1661 struct addrinfo addrinfo_hint;
1662 struct addrinfo *addrinfo = NULL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001663 struct sockaddr_storage local_addr;
1664 struct sockaddr_in *sin;
1665 struct sockaddr_in6 *sin6;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001666 socklen_t local_addr_len;
1667 uint16_t family;
1668
1669 /* Find out the address family (AF_INET or AF_INET6?) */
1670 memset(&addrinfo_hint, '\0', sizeof(addrinfo_hint));
Pau Espin Pedrol308ab792020-08-28 19:47:25 +02001671 addrinfo_hint.ai_family = AF_UNSPEC;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001672 addrinfo_hint.ai_flags = AI_NUMERICHOST;
1673 rc = getaddrinfo(remote_ip, NULL, &addrinfo_hint, &addrinfo);
1674 if (rc)
1675 return -EINVAL;
1676 family = addrinfo->ai_family;
1677 freeaddrinfo(addrinfo);
1678
1679 /* Connect a dummy socket to trick the kernel into determining the
1680 * ip-address of the interface that would be used if we would send
1681 * out an actual packet */
1682 sfd = osmo_sock_init2(family, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, remote_ip, 0, OSMO_SOCK_F_CONNECT);
1683 if (sfd < 0)
1684 return -EINVAL;
1685
1686 /* Request the IP address of the interface that the kernel has
1687 * actually choosen. */
1688 memset(&local_addr, 0, sizeof(local_addr));
1689 local_addr_len = sizeof(local_addr);
1690 rc = getsockname(sfd, (struct sockaddr *)&local_addr, &local_addr_len);
Philipp Maier8b7975b2018-01-22 15:38:07 +01001691 close(sfd);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001692 if (rc < 0)
1693 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001694
1695 switch (local_addr.ss_family) {
1696 case AF_INET:
1697 sin = (struct sockaddr_in*)&local_addr;
1698 if (!inet_ntop(AF_INET, &sin->sin_addr, local_ip, INET_ADDRSTRLEN))
1699 return -EINVAL;
1700 break;
1701 case AF_INET6:
1702 sin6 = (struct sockaddr_in6*)&local_addr;
Pau Espin Pedrol7bda8542020-08-31 11:21:30 +02001703 if (!inet_ntop(AF_INET6, &sin6->sin6_addr, local_ip, INET6_ADDRSTRLEN))
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001704 return -EINVAL;
1705 break;
1706 default:
Philipp Maier2d2490e2017-10-20 19:41:26 +02001707 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001708 }
Philipp Maier2d2490e2017-10-20 19:41:26 +02001709
1710 return 0;
1711}
1712
Alexander Couzens0f364212020-07-27 22:33:01 +02001713/*! Determine the matching local address for a given remote address.
1714 * \param[out] local_ip caller provided memory for resulting local address
1715 * \param[in] remote_ip remote address
1716 * \returns 0 on success; negative otherwise
1717 */
1718int osmo_sockaddr_local_ip(struct osmo_sockaddr *local_ip, const struct osmo_sockaddr *remote_ip)
1719{
1720 int sfd;
1721 int rc;
1722 socklen_t local_ip_len;
1723
1724 sfd = osmo_sock_init_osa(SOCK_DGRAM, IPPROTO_UDP, NULL, remote_ip, OSMO_SOCK_F_CONNECT);
1725 if (sfd < 0)
1726 return -EINVAL;
1727
1728 memset(local_ip, 0, sizeof(*local_ip));
1729 local_ip_len = sizeof(*local_ip);
1730 rc = getsockname(sfd, (struct sockaddr *)local_ip, &local_ip_len);
1731 close(sfd);
1732
1733 return rc;
1734}
1735
Alexander Couzense4181ea2020-07-20 00:03:16 +02001736/*! Compare two osmo_sockaddr.
1737 * \param[in] a
1738 * \param[in] b
1739 * \return 0 if a and b are equal. Otherwise it follows memcmp()
1740 */
Vadim Yanitskiydef5a402020-10-09 21:40:47 +07001741int osmo_sockaddr_cmp(const struct osmo_sockaddr *a,
1742 const struct osmo_sockaddr *b)
Alexander Couzense4181ea2020-07-20 00:03:16 +02001743{
1744 if (a == b)
1745 return 0;
1746 if (!a)
1747 return 1;
1748 if (!b)
1749 return -1;
1750
1751 if (a->u.sa.sa_family != b->u.sa.sa_family) {
1752 return OSMO_CMP(a->u.sa.sa_family, b->u.sa.sa_family);
1753 }
1754
1755 switch (a->u.sa.sa_family) {
1756 case AF_INET:
1757 return memcmp(&a->u.sin, &b->u.sin, sizeof(struct sockaddr_in));
1758 case AF_INET6:
1759 return memcmp(&a->u.sin6, &b->u.sin6, sizeof(struct sockaddr_in6));
1760 default:
1761 /* fallback to memcmp for remaining AF over the full osmo_sockaddr length */
1762 return memcmp(a, b, sizeof(struct osmo_sockaddr));
1763 }
1764}
1765
Alexander Couzens80788fa2020-10-12 01:11:20 +02001766/*! string-format a given osmo_sockaddr address
1767 * \param[in] sockaddr the osmo_sockaddr to print
1768 * \return pointer to the string on success; NULL on error
1769 */
1770const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *sockaddr)
1771{
1772 /* INET6_ADDRSTRLEN contains already a null termination,
1773 * adding '[' ']' ':' '16 bit port' */
1774 static __thread char buf[INET6_ADDRSTRLEN + 8];
1775 return osmo_sockaddr_to_str_buf(buf, sizeof(buf), sockaddr);
1776}
1777
1778/*! string-format a given osmo_sockaddr address into a user-supplied buffer
1779 * \param[in] buf user-supplied output buffer
1780 * \param[in] buf_len size of the user-supplied output buffer in bytes
1781 * \param[in] sockaddr the osmo_sockaddr to print
1782 * \return pointer to the string on success; NULL on error
1783 */
1784char *osmo_sockaddr_to_str_buf(char *buf, size_t buf_len,
1785 const struct osmo_sockaddr *sockaddr)
1786{
1787 uint16_t port = 0;
1788 size_t written;
1789 if (buf_len < 5)
1790 return NULL;
1791
1792 if (!sockaddr)
1793 return NULL;
1794
1795 switch (sockaddr->u.sa.sa_family) {
1796 case AF_INET:
1797 written = osmo_sockaddr_to_str_and_uint(buf, buf_len, &port, &sockaddr->u.sa);
1798 if (written + 1 >= buf_len && port)
1799 return NULL;
1800 if (port)
1801 snprintf(buf + written, buf_len - written, ":%u", port);
1802 break;
1803 case AF_INET6:
1804 buf[0] = '[';
1805 written = osmo_sockaddr_to_str_and_uint(buf + 1, buf_len - 1, &port, &sockaddr->u.sa);
1806 if (written + 2 >= buf_len)
1807 return NULL;
1808
1809 if (written + 3 >= buf_len && port)
1810 return NULL;
1811
1812 if (port)
1813 snprintf(buf + 1 + written, buf_len - written - 1, "]:%u", port);
1814 else {
1815 buf[written + 1] = ']';
1816 buf[written + 2] = 0;
1817 }
1818 break;
1819 default:
1820 snprintf(buf, buf_len, "unsupported family %d", sockaddr->u.sa.sa_family);
1821 return buf;
1822 }
1823
1824 return buf;
1825}
1826
Harald Weltece53e032021-04-27 21:44:34 +02001827/*! Set the DSCP (differentiated services code point) of a socket.
1828 * \param[in] dscp DSCP value in range 0..63
1829 * \returns 0 on success; negative on error. */
1830int osmo_sock_set_dscp(int fd, uint8_t dscp)
1831{
Harald Welte903e6702021-04-28 13:27:12 +02001832 struct sockaddr_storage local_addr;
1833 socklen_t local_addr_len = sizeof(local_addr);
Harald Weltece53e032021-04-27 21:44:34 +02001834 uint8_t tos;
1835 socklen_t tos_len = sizeof(tos);
Harald Welte903e6702021-04-28 13:27:12 +02001836 int tclass;
1837 socklen_t tclass_len = sizeof(tclass);
Harald Weltece53e032021-04-27 21:44:34 +02001838 int rc;
1839
1840 /* DSCP is a 6-bit value stored in the upper 6 bits of the 8-bit TOS */
1841 if (dscp > 63)
1842 return -EINVAL;
1843
Harald Welte903e6702021-04-28 13:27:12 +02001844 rc = getsockname(fd, (struct sockaddr *)&local_addr, &local_addr_len);
Harald Weltece53e032021-04-27 21:44:34 +02001845 if (rc < 0)
1846 return rc;
1847
Harald Welte903e6702021-04-28 13:27:12 +02001848 switch (local_addr.ss_family) {
1849 case AF_INET:
1850 /* read the original value */
1851 rc = getsockopt(fd, IPPROTO_IP, IP_TOS, &tos, &tos_len);
1852 if (rc < 0)
1853 return rc;
1854 /* mask-in the DSCP into the upper 6 bits */
1855 tos &= 0x03;
1856 tos |= dscp << 2;
1857 /* and write it back to the kernel */
1858 rc = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
1859 break;
1860 case AF_INET6:
1861 /* read the original value */
1862 rc = getsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tclass, &tclass_len);
1863 if (rc < 0)
1864 return rc;
1865 /* mask-in the DSCP into the upper 6 bits */
1866 tclass &= 0x03;
1867 tclass |= dscp << 2;
1868 /* and write it back to the kernel */
1869 rc = setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof(tclass));
1870 break;
1871 case AF_UNSPEC:
1872 default:
1873 LOGP(DLGLOBAL, LOGL_ERROR, "No DSCP support for socket family %u\n",
1874 local_addr.ss_family);
1875 rc = -1;
1876 break;
1877 }
Harald Weltece53e032021-04-27 21:44:34 +02001878
Harald Welte903e6702021-04-28 13:27:12 +02001879 return rc;
Harald Weltece53e032021-04-27 21:44:34 +02001880}
1881
Harald Welteecc0bd82021-04-27 22:24:08 +02001882/*! Set the priority value of a socket.
1883 * \param[in] prio priority value. Values outside 0..6 require CAP_NET_ADMIN.
1884 * \returns 0 on success; negative on error. */
1885int osmo_sock_set_priority(int fd, int prio)
1886{
1887 /* and write it back to the kernel */
1888 return setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(prio));
1889}
Alexander Couzens80788fa2020-10-12 01:11:20 +02001890
Harald Weltee4764422011-05-22 12:25:57 +02001891#endif /* HAVE_SYS_SOCKET_H */
Harald Welteba6988b2011-08-17 12:46:48 +02001892
Sylvain Munautdca7d2c2012-04-18 21:53:23 +02001893/*! @} */