blob: 229f72e3651fb3b449bc9acfeb96100c732e781b [file] [log] [blame]
Harald Welte468b6432014-09-11 13:05:51 +08001/*
Harald Welte48f55832017-01-26 00:03:10 +01002 * (C) 2011-2017 by Harald Welte <laforge@gnumonks.org>
Harald Welte468b6432014-09-11 13:05:51 +08003 *
4 * All Rights Reserved
5 *
Harald Weltee08da972017-11-13 01:00:26 +09006 * SPDX-License-Identifier: GPL-2.0+
7 *
Harald Welte468b6432014-09-11 13:05:51 +08008 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 */
23
Harald Welte33cb71a2011-05-21 18:54:32 +020024#include "../config.h"
25
Harald Welteba6988b2011-08-17 12:46:48 +020026/*! \addtogroup socket
27 * @{
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020028 * Osmocom socket convenience functions.
29 *
30 * \file socket.c */
Harald Welte96e2a002017-06-12 21:44:18 +020031
Harald Weltee4764422011-05-22 12:25:57 +020032#ifdef HAVE_SYS_SOCKET_H
33
Harald Welte33cb71a2011-05-21 18:54:32 +020034#include <osmocom/core/logging.h>
35#include <osmocom/core/select.h>
36#include <osmocom/core/socket.h>
Alexander Couzens43957e62020-08-01 21:56:45 +020037#include <osmocom/core/sockaddr_str.h>
Harald Welte48f55832017-01-26 00:03:10 +010038#include <osmocom/core/talloc.h>
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +020039#include <osmocom/core/utils.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020040
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +020041#include <sys/ioctl.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020042#include <sys/socket.h>
43#include <sys/types.h>
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +010044#include <sys/un.h>
Harald Welte44b99262020-03-07 14:59:05 +010045#include <net/if.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020046
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010047#include <netinet/in.h>
Harald Weltee30d7e62017-07-13 16:02:50 +020048#include <arpa/inet.h>
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010049
Harald Welte33cb71a2011-05-21 18:54:32 +020050#include <stdio.h>
51#include <unistd.h>
52#include <stdint.h>
53#include <string.h>
54#include <errno.h>
55#include <netdb.h>
56#include <ifaddrs.h>
57
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +020058#ifdef HAVE_LIBSCTP
59#include <netinet/sctp.h>
60#endif
61
Harald Weltedda70fc2017-04-08 20:52:33 +020062static struct addrinfo *addrinfo_helper(uint16_t family, uint16_t type, uint8_t proto,
63 const char *host, uint16_t port, bool passive)
64{
Pau Espin Pedrolff428522019-10-10 17:38:16 +020065 struct addrinfo hints, *result, *rp;
Oliver Smith860651e2018-10-30 14:31:57 +010066 char portbuf[6];
Harald Weltedda70fc2017-04-08 20:52:33 +020067 int rc;
68
69 snprintf(portbuf, sizeof(portbuf), "%u", port);
70 memset(&hints, 0, sizeof(struct addrinfo));
71 hints.ai_family = family;
72 if (type == SOCK_RAW) {
73 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
74 * SOCK_RAW and IPPROTO_GRE is used.
Pau Espin Pedrolff428522019-10-10 17:38:16 +020075 * http://sourceware.org/bugzilla/show_bug.cgi?id=15015
Harald Weltedda70fc2017-04-08 20:52:33 +020076 */
77 hints.ai_socktype = SOCK_DGRAM;
78 hints.ai_protocol = IPPROTO_UDP;
79 } else {
80 hints.ai_socktype = type;
81 hints.ai_protocol = proto;
82 }
Pau Espin Pedrol3119d472020-08-25 12:30:55 +020083
Harald Weltedda70fc2017-04-08 20:52:33 +020084 if (passive)
85 hints.ai_flags |= AI_PASSIVE;
86
87 rc = getaddrinfo(host, portbuf, &hints, &result);
88 if (rc != 0) {
Pau Espin Pedrolba828c32020-08-20 18:28:10 +020089 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo(%s, %u) failed: %s\n",
90 host, port, gai_strerror(rc));
Harald Weltedda70fc2017-04-08 20:52:33 +020091 return NULL;
92 }
93
Pau Espin Pedrolff428522019-10-10 17:38:16 +020094 for (rp = result; rp != NULL; rp = rp->ai_next) {
95 /* Workaround for glibc again */
96 if (type == SOCK_RAW) {
97 rp->ai_socktype = SOCK_RAW;
98 rp->ai_protocol = proto;
99 }
100 }
101
Harald Weltedda70fc2017-04-08 20:52:33 +0200102 return result;
103}
104
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200105#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200106/*! Retrieve an array of addrinfo with specified hints, one for each host in the hosts array.
107 * \param[out] addrinfo array of addrinfo pointers, will be filled by the function on success.
108 * Its size must be at least the one of hosts.
109 * \param[in] family Socket family like AF_INET, AF_INET6.
110 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM.
111 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP.
112 * \param[in] hosts array of char pointers (strings) containing the addresses to query.
113 * \param[in] host_cnt length of the hosts array (in items).
114 * \param[in] port port number in host byte order.
115 * \param[in] passive whether to include the AI_PASSIVE flag in getaddrinfo() hints.
116 * \returns 0 is returned on success together with a filled addrinfo array; negative on error
117 */
118static int addrinfo_helper_multi(struct addrinfo **addrinfo, uint16_t family, uint16_t type, uint8_t proto,
119 const char **hosts, size_t host_cnt, uint16_t port, bool passive)
120{
121 int i, j;
122
123 for (i = 0; i < host_cnt; i++) {
124 addrinfo[i] = addrinfo_helper(family, type, proto, hosts[i], port, passive);
125 if (!addrinfo[i]) {
126 for (j = 0; j < i; j++)
127 freeaddrinfo(addrinfo[j]);
128 return -EINVAL;
129 }
130 }
131 return 0;
132}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200133#endif /* HAVE_LIBSCTP*/
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200134
Harald Weltedda70fc2017-04-08 20:52:33 +0200135static int socket_helper(const struct addrinfo *rp, unsigned int flags)
136{
137 int sfd, on = 1;
138
139 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200140 if (sfd == -1) {
141 LOGP(DLGLOBAL, LOGL_ERROR,
142 "unable to create socket: %s\n", strerror(errno));
Harald Weltedda70fc2017-04-08 20:52:33 +0200143 return sfd;
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200144 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200145 if (flags & OSMO_SOCK_F_NONBLOCK) {
146 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
147 LOGP(DLGLOBAL, LOGL_ERROR,
148 "cannot set this socket unblocking: %s\n",
149 strerror(errno));
150 close(sfd);
151 sfd = -EINVAL;
152 }
153 }
154 return sfd;
155}
156
Alexander Couzens43957e62020-08-01 21:56:45 +0200157static int socket_helper_osa(const struct osmo_sockaddr *addr, uint16_t type, uint8_t proto, unsigned int flags)
158{
159 int sfd, on = 1;
160
161 sfd = socket(addr->u.sa.sa_family, type, proto);
162 if (sfd == -1) {
163 LOGP(DLGLOBAL, LOGL_ERROR,
164 "unable to create socket: %s\n", strerror(errno));
165 return sfd;
166 }
167 if (flags & OSMO_SOCK_F_NONBLOCK) {
168 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
169 LOGP(DLGLOBAL, LOGL_ERROR,
170 "cannot set this socket unblocking: %s\n",
171 strerror(errno));
172 close(sfd);
173 sfd = -EINVAL;
174 }
175 }
176 return sfd;
177}
178
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200179#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200180/* Fill buf with a string representation of the address set, in the form:
181 * buf_len == 0: "()"
182 * buf_len == 1: "hostA"
183 * buf_len >= 2: (hostA|hostB|...|...)
184 */
185static int multiaddr_snprintf(char* buf, size_t buf_len, const char **hosts, size_t host_cnt)
186{
187 int len = 0, offset = 0, rem = buf_len;
188 int ret, i;
189 char *after;
190
191 if (buf_len < 3)
192 return -EINVAL;
193
194 if (host_cnt != 1) {
195 ret = snprintf(buf, rem, "(");
196 if (ret < 0)
197 return ret;
198 OSMO_SNPRINTF_RET(ret, rem, offset, len);
199 }
200 for (i = 0; i < host_cnt; i++) {
201 if (host_cnt == 1)
202 after = "";
203 else
204 after = (i == (host_cnt - 1)) ? ")" : "|";
205 ret = snprintf(buf + offset, rem, "%s%s", hosts[i] ? : "0.0.0.0", after);
206 OSMO_SNPRINTF_RET(ret, rem, offset, len);
207 }
208
209 return len;
210}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200211#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200212
Harald Weltec47bbda2017-07-13 16:13:26 +0200213static int osmo_sock_init_tail(int fd, uint16_t type, unsigned int flags)
214{
Harald Weltebc43a622017-07-13 16:20:21 +0200215 int rc;
Harald Weltec47bbda2017-07-13 16:13:26 +0200216
217 /* Make sure to call 'listen' on a bound, connection-oriented sock */
218 if ((flags & (OSMO_SOCK_F_BIND|OSMO_SOCK_F_CONNECT)) == OSMO_SOCK_F_BIND) {
219 switch (type) {
220 case SOCK_STREAM:
221 case SOCK_SEQPACKET:
222 rc = listen(fd, 10);
Harald Weltebc43a622017-07-13 16:20:21 +0200223 if (rc < 0) {
224 LOGP(DLGLOBAL, LOGL_ERROR, "unable to listen on socket: %s\n",
225 strerror(errno));
226 return rc;
227 }
228 break;
Harald Weltec47bbda2017-07-13 16:13:26 +0200229 }
230 }
231
Harald Weltebc43a622017-07-13 16:20:21 +0200232 if (flags & OSMO_SOCK_F_NO_MCAST_LOOP) {
233 rc = osmo_sock_mcast_loop_set(fd, false);
234 if (rc < 0) {
235 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable multicast loop: %s\n",
236 strerror(errno));
237 return rc;
238 }
239 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200240
Harald Welte37d204a2017-07-13 16:33:16 +0200241 if (flags & OSMO_SOCK_F_NO_MCAST_ALL) {
242 rc = osmo_sock_mcast_all_set(fd, false);
243 if (rc < 0) {
244 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable receive of all multicast: %s\n",
245 strerror(errno));
246 /* do not abort here, as this is just an
247 * optional additional optimization that only
248 * exists on Linux only */
249 }
250 }
Harald Weltebc43a622017-07-13 16:20:21 +0200251 return 0;
Harald Weltec47bbda2017-07-13 16:13:26 +0200252}
253
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200254/*! Initialize a socket (including bind and/or connect)
Harald Weltedda70fc2017-04-08 20:52:33 +0200255 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
256 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
257 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
258 * \param[in] local_host local host name or IP address in string form
259 * \param[in] local_port local port number in host byte order
260 * \param[in] remote_host remote host name or IP address in string form
261 * \param[in] remote_port remote port number in host byte order
262 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
263 * \returns socket file descriptor on success; negative on error
264 *
265 * This function creates a new socket of the designated \a family, \a
266 * type and \a proto and optionally binds it to the \a local_host and \a
267 * local_port as well as optionally connects it to the \a remote_host
268 * and \q remote_port, depending on the value * of \a flags parameter.
269 *
270 * As opposed to \ref osmo_sock_init(), this function allows to combine
271 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
272 * is useful if you want to connect to a remote host/port, but still
273 * want to bind that socket to either a specific local alias IP and/or a
274 * specific local source port.
275 *
276 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
277 * OSMO_SOCK_F_CONNECT, or both.
278 *
279 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
280 * non-blocking mode.
281 */
282int osmo_sock_init2(uint16_t family, uint16_t type, uint8_t proto,
283 const char *local_host, uint16_t local_port,
284 const char *remote_host, uint16_t remote_port, unsigned int flags)
285{
Alexander Couzens2c962f52020-06-03 00:28:02 +0200286 struct addrinfo *local = NULL, *remote = NULL, *rp;
Harald Weltedda70fc2017-04-08 20:52:33 +0200287 int sfd = -1, rc, on = 1;
288
Alexander Couzens2c962f52020-06-03 00:28:02 +0200289 bool local_ipv4 = false, local_ipv6 = false;
290 bool remote_ipv4 = false, remote_ipv6 = false;
291
Harald Weltedda70fc2017-04-08 20:52:33 +0200292 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
293 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
294 "BIND or CONNECT flags\n");
295 return -EINVAL;
296 }
297
Alexander Couzens2c962f52020-06-03 00:28:02 +0200298 /* figure out local address infos */
299 if (flags & OSMO_SOCK_F_BIND) {
300 local = addrinfo_helper(family, type, proto, local_host, local_port, true);
301 if (!local)
302 return -EINVAL;
303 }
304
305 /* figure out remote address infos */
306 if (flags & OSMO_SOCK_F_CONNECT) {
307 remote = addrinfo_helper(family, type, proto, remote_host, remote_port, false);
308 if (!remote) {
309 if (local)
310 freeaddrinfo(local);
311
312 return -EINVAL;
313 }
314 }
315
316 /* It must do a full run to ensure AF_UNSPEC does not fail.
317 * In case first local valid entry is IPv4 and only remote valid entry
318 * is IPv6 or vice versa */
319 if (family == AF_UNSPEC) {
320 for (rp = local; rp != NULL; rp = rp->ai_next) {
321 switch (rp->ai_family) {
322 case AF_INET:
323 local_ipv4 = true;
324 break;
325 case AF_INET6:
326 local_ipv6 = true;
327 break;
328 }
329 }
330
331 for (rp = remote; rp != NULL; rp = rp->ai_next) {
332 switch (rp->ai_family) {
333 case AF_INET:
334 remote_ipv4 = true;
335 break;
336 case AF_INET6:
337 remote_ipv6 = true;
338 break;
339 }
340 }
341
Pau Espin Pedrold8cf52b2020-08-31 19:00:59 +0200342 if ((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) {
343 /* prioritize ipv6 as per RFC */
344 if (local_ipv6 && remote_ipv6)
345 family = AF_INET6;
346 else if (local_ipv4 && remote_ipv4)
347 family = AF_INET;
348 else {
349 if (local)
350 freeaddrinfo(local);
351 if (remote)
352 freeaddrinfo(remote);
353 LOGP(DLGLOBAL, LOGL_ERROR,
354 "Unable to find a common protocol (IPv4 or IPv6) "
355 "for local host: %s and remote host: %s.\n",
356 local_host, remote_host);
357 return -ENODEV;
358 }
359 } else if ((flags & OSMO_SOCK_F_BIND)) {
360 family = local_ipv6 ? AF_INET6 : AF_INET;
361 } else if ((flags & OSMO_SOCK_F_CONNECT)) {
362 family = remote_ipv6 ? AF_INET6 : AF_INET;
Alexander Couzens2c962f52020-06-03 00:28:02 +0200363 }
364 }
365
Harald Weltedda70fc2017-04-08 20:52:33 +0200366 /* figure out local side of socket */
367 if (flags & OSMO_SOCK_F_BIND) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200368 for (rp = local; rp != NULL; rp = rp->ai_next) {
369 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
370 if (rp->ai_family != family)
371 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200372
Harald Weltedda70fc2017-04-08 20:52:33 +0200373 sfd = socket_helper(rp, flags);
374 if (sfd < 0)
375 continue;
376
Philipp Maier73196e72018-08-23 20:11:50 +0200377 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200378 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
379 &on, sizeof(on));
380 if (rc < 0) {
381 LOGP(DLGLOBAL, LOGL_ERROR,
382 "cannot setsockopt socket:"
383 " %s:%u: %s\n",
384 local_host, local_port,
385 strerror(errno));
386 close(sfd);
387 continue;
388 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200389 }
Philipp Maier99f706d2018-08-01 12:40:36 +0200390
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200391 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
392 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
393 local_host, local_port, strerror(errno));
394 close(sfd);
395 continue;
396 }
397 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200398 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200399
400 freeaddrinfo(local);
Harald Weltedda70fc2017-04-08 20:52:33 +0200401 if (rp == NULL) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200402 if (remote)
403 freeaddrinfo(remote);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200404 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
405 local_host, local_port);
Harald Weltedda70fc2017-04-08 20:52:33 +0200406 return -ENODEV;
407 }
408 }
409
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200410 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
411 was already closed and func returned. If OSMO_SOCK_F_BIND is not
412 set, then sfd = -1 */
413
Harald Weltedda70fc2017-04-08 20:52:33 +0200414 /* figure out remote side of socket */
415 if (flags & OSMO_SOCK_F_CONNECT) {
Alexander Couzens2c962f52020-06-03 00:28:02 +0200416 for (rp = remote; rp != NULL; rp = rp->ai_next) {
417 /* When called with AF_UNSPEC, family will set to IPv4 or IPv6 */
418 if (rp->ai_family != family)
419 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200420
Harald Welte5cfa6dc2017-07-21 16:52:29 +0200421 if (sfd < 0) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200422 sfd = socket_helper(rp, flags);
423 if (sfd < 0)
424 continue;
425 }
426
427 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200428 if (rc != 0 && errno != EINPROGRESS) {
429 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
430 remote_host, remote_port, strerror(errno));
431 /* We want to maintain the bind socket if bind was enabled */
432 if (!(flags & OSMO_SOCK_F_BIND)) {
433 close(sfd);
434 sfd = -1;
435 }
436 continue;
437 }
438 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200439 }
Alexander Couzens2c962f52020-06-03 00:28:02 +0200440
441 freeaddrinfo(remote);
Harald Weltedda70fc2017-04-08 20:52:33 +0200442 if (rp == NULL) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200443 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable remote addr found for: %s:%u\n",
444 remote_host, remote_port);
445 if (sfd >= 0)
446 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200447 return -ENODEV;
448 }
449 }
450
Harald Weltec47bbda2017-07-13 16:13:26 +0200451 rc = osmo_sock_init_tail(sfd, type, flags);
452 if (rc < 0) {
453 close(sfd);
454 sfd = -1;
Harald Weltedda70fc2017-04-08 20:52:33 +0200455 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200456
Harald Weltedda70fc2017-04-08 20:52:33 +0200457 return sfd;
458}
459
Alexander Couzens43957e62020-08-01 21:56:45 +0200460#define _SOCKADDR_TO_STR(dest, sockaddr) do { \
461 if (osmo_sockaddr_str_from_sockaddr(&dest, &sockaddr->u.sas)) \
462 osmo_strlcpy(dest.ip, "Invalid IP", 11); \
463 } while (0)
464
465/*! Initialize a socket (including bind and/or connect)
466 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
467 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
468 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
469 * \param[in] local local address
470 * \param[in] remote remote address
471 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
472 * \returns socket file descriptor on success; negative on error
473 *
474 * This function creates a new socket of the
475 * \a type and \a proto and optionally binds it to the \a local
476 * as well as optionally connects it to the \a remote
477 * depending on the value * of \a flags parameter.
478 *
479 * As opposed to \ref osmo_sock_init(), this function allows to combine
480 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
481 * is useful if you want to connect to a remote host/port, but still
482 * want to bind that socket to either a specific local alias IP and/or a
483 * specific local source port.
484 *
485 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
486 * OSMO_SOCK_F_CONNECT, or both.
487 *
488 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
489 * non-blocking mode.
490 */
491int osmo_sock_init_osa(uint16_t type, uint8_t proto,
492 const struct osmo_sockaddr *local,
493 const struct osmo_sockaddr *remote,
494 unsigned int flags)
495{
496 int sfd = -1, rc, on = 1;
497 struct osmo_sockaddr_str sastr = {};
498
499 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
500 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
501 "BIND or CONNECT flags\n");
502 return -EINVAL;
503 }
504
505 if ((flags & OSMO_SOCK_F_BIND) && !local) {
506 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot BIND when local is NULL\n");
507 return -EINVAL;
508 }
509
510 if ((flags & OSMO_SOCK_F_CONNECT) && !remote) {
511 LOGP(DLGLOBAL, LOGL_ERROR, "invalid argument. Cannot CONNECT when remote is NULL\n");
512 return -EINVAL;
513 }
514
515 if ((flags & OSMO_SOCK_F_BIND) &&
516 (flags & OSMO_SOCK_F_CONNECT) &&
517 local->u.sa.sa_family != remote->u.sa.sa_family) {
518 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: the family for "
519 "local and remote endpoint must be same.\n");
520 return -EINVAL;
521 }
522
523 /* figure out local side of socket */
524 if (flags & OSMO_SOCK_F_BIND) {
525 sfd = socket_helper_osa(local, type, proto, flags);
526 if (sfd < 0) {
527 _SOCKADDR_TO_STR(sastr, local);
528 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
529 sastr.ip, sastr.port);
530 return -ENODEV;
531 }
532
533 if (proto != IPPROTO_UDP || (flags & OSMO_SOCK_F_UDP_REUSEADDR)) {
534 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
535 &on, sizeof(on));
536 if (rc < 0) {
537 _SOCKADDR_TO_STR(sastr, local);
538 LOGP(DLGLOBAL, LOGL_ERROR,
539 "cannot setsockopt socket:"
540 " %s:%u: %s\n",
541 sastr.ip, sastr.port,
542 strerror(errno));
543 close(sfd);
544 return rc;
545 }
546 }
547
548 if (bind(sfd, &local->u.sa, sizeof(struct osmo_sockaddr)) == -1) {
549 _SOCKADDR_TO_STR(sastr, local);
550 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
551 sastr.ip, sastr.port, strerror(errno));
552 close(sfd);
553 return -1;
554 }
555 }
556
557 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
558 was already closed and func returned. If OSMO_SOCK_F_BIND is not
559 set, then sfd = -1 */
560
561 /* figure out remote side of socket */
562 if (flags & OSMO_SOCK_F_CONNECT) {
563 if (sfd < 0) {
564 sfd = socket_helper_osa(remote, type, proto, flags);
565 if (sfd < 0) {
566 return sfd;
567 }
568 }
569
570 rc = connect(sfd, &remote->u.sa, sizeof(struct osmo_sockaddr));
571 if (rc != 0 && errno != EINPROGRESS) {
572 _SOCKADDR_TO_STR(sastr, remote);
573 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
574 sastr.ip, sastr.port, strerror(errno));
575 close(sfd);
576 return rc;
577 }
578 }
579
580 rc = osmo_sock_init_tail(sfd, type, flags);
581 if (rc < 0) {
582 close(sfd);
583 sfd = -1;
584 }
585
586 return sfd;
587}
588
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200589#ifdef HAVE_LIBSCTP
590
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200591/* Check whether there's an IPv6 Addr as first option of any addrinfo item in the addrinfo set */
592static void addrinfo_has_v4v6addr(const struct addrinfo **result, size_t result_count, bool *has_v4, bool *has_v6)
593{
594 size_t host_idx;
595 *has_v4 = false;
596 *has_v6 = false;
597
598 for (host_idx = 0; host_idx < result_count; host_idx++) {
599 if (result[host_idx]->ai_family == AF_INET)
600 *has_v4 = true;
601 else if (result[host_idx]->ai_family == AF_INET6)
602 *has_v6 = true;
603 }
604}
605
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200606/* Check whether there's an IPv6 with IN6ADDR_ANY_INIT ("::") */
607static bool addrinfo_has_in6addr_any(const struct addrinfo **result, size_t result_count)
608{
609 size_t host_idx;
610 struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
611
612 for (host_idx = 0; host_idx < result_count; host_idx++) {
613 if (result[host_idx]->ai_family != AF_INET6)
614 continue;
615 if (memcmp(&((struct sockaddr_in6 *)result[host_idx]->ai_addr)->sin6_addr,
616 &in6addr_any, sizeof(in6addr_any)) == 0)
617 return true;
618 }
619 return false;
620}
621
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200622static int socket_helper_multiaddr(uint16_t family, uint16_t type, uint8_t proto, unsigned int flags)
623{
624 int sfd, on = 1;
625
626 sfd = socket(family, type, proto);
627 if (sfd == -1) {
628 LOGP(DLGLOBAL, LOGL_ERROR,
629 "Unable to create socket: %s\n", strerror(errno));
630 return sfd;
631 }
632 if (flags & OSMO_SOCK_F_NONBLOCK) {
633 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
634 LOGP(DLGLOBAL, LOGL_ERROR,
635 "Cannot set this socket unblocking: %s\n",
636 strerror(errno));
637 close(sfd);
638 sfd = -EINVAL;
639 }
640 }
641 return sfd;
642}
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200643
644/* Build array of addresses taking first addrinfo result of the requested family
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200645 * for each host in addrs_buf. */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200646static int addrinfo_to_sockaddr(uint16_t family, const struct addrinfo **result,
647 const char **hosts, int host_cont,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200648 uint8_t *addrs_buf, size_t addrs_buf_len) {
649 size_t host_idx, offset = 0;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200650 const struct addrinfo *rp;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200651
652 for (host_idx = 0; host_idx < host_cont; host_idx++) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200653 /* Addresses are ordered based on RFC 3484, see man getaddrinfo */
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200654 for (rp = result[host_idx]; rp != NULL; rp = rp->ai_next) {
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200655 if (family != AF_UNSPEC && rp->ai_family != family)
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200656 continue;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200657 if (offset + rp->ai_addrlen > addrs_buf_len) {
658 LOGP(DLGLOBAL, LOGL_ERROR, "Output buffer to small: %zu\n",
659 addrs_buf_len);
660 return -ENOSPC;
661 }
662 memcpy(addrs_buf + offset, rp->ai_addr, rp->ai_addrlen);
663 offset += rp->ai_addrlen;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200664 break;
665 }
666 if (!rp) { /* No addr could be bound for this host! */
667 LOGP(DLGLOBAL, LOGL_ERROR, "No suitable remote address found for host: %s\n",
668 hosts[host_idx]);
669 return -ENODEV;
670 }
671 }
672 return 0;
673}
674
675/*! Initialize a socket (including bind and/or connect) with multiple local or remote addresses.
676 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
677 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
678 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
679 * \param[in] local_hosts array of char pointers (strings), each containing local host name or IP address in string form
680 * \param[in] local_hosts_cnt length of local_hosts (in items)
681 * \param[in] local_port local port number in host byte order
682 * \param[in] remote_host array of char pointers (strings), each containing remote host name or IP address in string form
683 * \param[in] remote_hosts_cnt length of remote_hosts (in items)
684 * \param[in] remote_port remote port number in host byte order
685 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
686 * \returns socket file descriptor on success; negative on error
687 *
688 * This function is similar to \ref osmo_sock_init2(), but can be passed an
689 * array of local or remote addresses for protocols supporting multiple
690 * addresses per socket, like SCTP (currently only one supported). This function
691 * should not be used by protocols not supporting this kind of features, but
692 * rather \ref osmo_sock_init2() should be used instead.
693 * See \ref osmo_sock_init2() for more information on flags and general behavior.
694 */
695int osmo_sock_init2_multiaddr(uint16_t family, uint16_t type, uint8_t proto,
696 const char **local_hosts, size_t local_hosts_cnt, uint16_t local_port,
697 const char **remote_hosts, size_t remote_hosts_cnt, uint16_t remote_port,
698 unsigned int flags)
699
700{
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200701 struct addrinfo *res_loc[OSMO_SOCK_MAX_ADDRS], *res_rem[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200702 int sfd = -1, rc, on = 1;
703 int i;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200704 bool loc_has_v4addr, rem_has_v4addr;
705 bool loc_has_v6addr, rem_has_v6addr;
706 struct sockaddr_in6 addrs_buf[OSMO_SOCK_MAX_ADDRS];
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200707 char strbuf[512];
708
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200709 /* updated later in case of AF_UNSPEC */
710 loc_has_v4addr = rem_has_v4addr = (family == AF_INET);
711 loc_has_v6addr = rem_has_v6addr = (family == AF_INET6);
712
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200713 /* TODO: So far this function is only aimed for SCTP, but could be
714 reused in the future for other protocols with multi-addr support */
715 if (proto != IPPROTO_SCTP)
716 return -ENOTSUP;
717
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200718 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
719 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
720 "BIND or CONNECT flags\n");
721 return -EINVAL;
722 }
723
724 if (((flags & OSMO_SOCK_F_BIND) && !local_hosts_cnt) ||
725 ((flags & OSMO_SOCK_F_CONNECT) && !remote_hosts_cnt) ||
726 local_hosts_cnt > OSMO_SOCK_MAX_ADDRS ||
727 remote_hosts_cnt > OSMO_SOCK_MAX_ADDRS)
728 return -EINVAL;
729
730 /* figure out local side of socket */
731 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200732 rc = addrinfo_helper_multi(res_loc, family, type, proto, local_hosts,
733 local_hosts_cnt, local_port, true);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200734 if (rc < 0)
735 return -EINVAL;
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200736 /* Figure out if there's any IPV4 or IPv6 addr in the set */
737 if (family == AF_UNSPEC)
738 addrinfo_has_v4v6addr((const struct addrinfo **)res_loc, local_hosts_cnt,
739 &loc_has_v4addr, &loc_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200740 }
741 /* figure out remote side of socket */
742 if (flags & OSMO_SOCK_F_CONNECT) {
743 rc = addrinfo_helper_multi(res_rem, family, type, proto, remote_hosts,
744 remote_hosts_cnt, remote_port, false);
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200745 if (rc < 0) {
746 rc = -EINVAL;
747 goto ret_freeaddrinfo_loc;
748 }
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200749 /* Figure out if there's any IPv4 or IPv6 addr in the set */
750 if (family == AF_UNSPEC)
751 addrinfo_has_v4v6addr((const struct addrinfo **)res_rem, remote_hosts_cnt,
752 &rem_has_v4addr, &rem_has_v6addr);
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200753 }
754
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200755 if (((flags & OSMO_SOCK_F_BIND) && (flags & OSMO_SOCK_F_CONNECT)) &&
Pau Espin Pedrol4f463c52020-08-28 14:32:02 +0200756 !addrinfo_has_in6addr_any((const struct addrinfo **)res_loc, local_hosts_cnt) &&
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200757 (loc_has_v4addr != rem_has_v4addr || loc_has_v6addr != rem_has_v6addr)) {
758 LOGP(DLGLOBAL, LOGL_ERROR, "Invalid v4 vs v6 in local vs remote addresses\n");
759 rc = -EINVAL;
760 goto ret_freeaddrinfo;
761 }
762
763 sfd = socket_helper_multiaddr(loc_has_v6addr ? AF_INET6 : AF_INET,
764 type, proto, flags);
765 if (sfd < 0) {
766 rc = sfd;
767 goto ret_freeaddrinfo;
768 }
769
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200770 if (flags & OSMO_SOCK_F_BIND) {
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200771 /* Since so far we only allow IPPROTO_SCTP in this function,
772 no need to check below for "proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR" */
773 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
774 &on, sizeof(on));
775 if (rc < 0) {
776 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
777 LOGP(DLGLOBAL, LOGL_ERROR,
778 "cannot setsockopt socket:"
779 " %s:%u: %s\n",
780 strbuf, local_port,
781 strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200782 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200783 }
784
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200785 /* Build array of addresses taking first entry for each host.
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200786 TODO: Ideally we should use backtracking storing last used
787 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200788 /* 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 +0200789 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_loc,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200790 local_hosts, local_hosts_cnt,
791 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200792 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200793 rc = -ENODEV;
794 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200795 }
796
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200797 rc = sctp_bindx(sfd, (struct sockaddr *)addrs_buf, local_hosts_cnt, SCTP_BINDX_ADD_ADDR);
798 if (rc == -1) {
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200799 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
800 LOGP(DLGLOBAL, LOGL_NOTICE, "unable to bind socket: %s:%u: %s\n",
801 strbuf, local_port, strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200802 rc = -ENODEV;
803 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200804 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200805 }
806
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200807 if (flags & OSMO_SOCK_F_CONNECT) {
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200808 /* Build array of addresses taking first of same family for each host.
809 TODO: Ideally we should use backtracking storing last used
810 indexes and trying next combination if connect() fails .*/
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200811 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)res_rem,
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200812 remote_hosts, remote_hosts_cnt,
813 (uint8_t*)addrs_buf, sizeof(addrs_buf));
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200814 if (rc < 0) {
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200815 rc = -ENODEV;
816 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200817 }
818
Pau Espin Pedrolcd133312020-08-19 17:25:04 +0200819 rc = sctp_connectx(sfd, (struct sockaddr *)addrs_buf, remote_hosts_cnt, NULL);
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200820 if (rc != 0 && errno != EINPROGRESS) {
821 multiaddr_snprintf(strbuf, sizeof(strbuf), remote_hosts, remote_hosts_cnt);
822 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
823 strbuf, remote_port, strerror(errno));
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200824 rc = -ENODEV;
825 goto ret_close;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200826 }
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200827 }
828
829 rc = osmo_sock_init_tail(sfd, type, flags);
830 if (rc < 0) {
831 close(sfd);
832 sfd = -1;
833 }
834
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200835 rc = sfd;
836 goto ret_freeaddrinfo;
837
838ret_close:
839 if (sfd >= 0)
840 close(sfd);
841ret_freeaddrinfo:
Pau Espin Pedrol4541cf22020-08-25 11:22:09 +0200842 if (flags & OSMO_SOCK_F_CONNECT) {
843 for (i = 0; i < remote_hosts_cnt; i++)
844 freeaddrinfo(res_rem[i]);
845 }
846ret_freeaddrinfo_loc:
847 if (flags & OSMO_SOCK_F_BIND) {
848 for (i = 0; i < local_hosts_cnt; i++)
849 freeaddrinfo(res_loc[i]);
850 }
Pau Espin Pedrol796c6512020-08-19 12:03:25 +0200851 return rc;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200852}
853#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200854
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200855/*! Initialize a socket (including bind/connect)
Harald Welteba6988b2011-08-17 12:46:48 +0200856 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
857 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
858 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
859 * \param[in] host remote host name or IP address in string form
860 * \param[in] port remote port number in host byte order
861 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200862 * \returns socket file descriptor on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200863 *
864 * This function creates a new socket of the designated \a family, \a
865 * type and \a proto and optionally binds or connects it, depending on
866 * the value of \a flags parameter.
867 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200868int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200869 const char *host, uint16_t port, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200870{
Harald Weltedda70fc2017-04-08 20:52:33 +0200871 struct addrinfo *result, *rp;
Harald Welte68b15742011-05-22 21:47:29 +0200872 int sfd, rc, on = 1;
Harald Welte33cb71a2011-05-21 18:54:32 +0200873
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200874 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200875 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100876 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: both bind and connect flags set:"
Neels Hofmeyrb7f191f2016-08-29 11:22:03 +0200877 " %s:%u\n", host, port);
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200878 return -EINVAL;
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200879 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200880
Harald Weltedda70fc2017-04-08 20:52:33 +0200881 result = addrinfo_helper(family, type, proto, host, port, flags & OSMO_SOCK_F_BIND);
Pau Espin Pedrolba828c32020-08-20 18:28:10 +0200882 if (!result)
Harald Welte33cb71a2011-05-21 18:54:32 +0200883 return -EINVAL;
Harald Welte33cb71a2011-05-21 18:54:32 +0200884
885 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200886 sfd = socket_helper(rp, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200887 if (sfd == -1)
888 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200889
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200890 if (flags & OSMO_SOCK_F_CONNECT) {
891 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200892 if (rc != 0 && errno != EINPROGRESS) {
893 close(sfd);
894 continue;
895 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200896 } else {
Philipp Maier73196e72018-08-23 20:11:50 +0200897 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200898 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
899 &on, sizeof(on));
900 if (rc < 0) {
901 LOGP(DLGLOBAL, LOGL_ERROR,
902 "cannot setsockopt socket:"
903 " %s:%u: %s\n",
904 host, port, strerror(errno));
905 close(sfd);
906 continue;
907 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200908 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200909 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
910 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket:"
911 "%s:%u: %s\n",
912 host, port, strerror(errno));
913 close(sfd);
914 continue;
915 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200916 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200917 break;
Harald Welte33cb71a2011-05-21 18:54:32 +0200918 }
919 freeaddrinfo(result);
920
921 if (rp == NULL) {
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200922 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable addr found for: %s:%u\n",
923 host, port);
Harald Welte33cb71a2011-05-21 18:54:32 +0200924 return -ENODEV;
925 }
Harald Welte68b15742011-05-22 21:47:29 +0200926
Philipp Maier73196e72018-08-23 20:11:50 +0200927 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200928 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
929 if (rc < 0) {
930 LOGP(DLGLOBAL, LOGL_ERROR,
931 "cannot setsockopt socket: %s:%u: %s\n", host,
932 port, strerror(errno));
933 close(sfd);
934 sfd = -1;
935 }
Philipp Maier0659c5d2018-08-01 12:43:08 +0200936 }
Harald Welte68b15742011-05-22 21:47:29 +0200937
Harald Weltec47bbda2017-07-13 16:13:26 +0200938 rc = osmo_sock_init_tail(sfd, type, flags);
939 if (rc < 0) {
940 close(sfd);
941 sfd = -1;
Harald Welte68b15742011-05-22 21:47:29 +0200942 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200943
Harald Welte68b15742011-05-22 21:47:29 +0200944 return sfd;
945}
946
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200947/*! fill \ref osmo_fd for a give sfd
Max862ba652014-10-13 14:54:25 +0200948 * \param[out] ofd file descriptor (will be filled in)
949 * \param[in] sfd socket file descriptor
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200950 * \returns socket fd on success; negative on error
Max862ba652014-10-13 14:54:25 +0200951 *
952 * This function fills the \a ofd structure.
953 */
954static inline int osmo_fd_init_ofd(struct osmo_fd *ofd, int sfd)
955{
956 int rc;
957
958 if (sfd < 0)
959 return sfd;
960
961 ofd->fd = sfd;
Harald Welte16886992019-03-20 10:26:39 +0100962 ofd->when = OSMO_FD_READ;
Max862ba652014-10-13 14:54:25 +0200963
964 rc = osmo_fd_register(ofd);
965 if (rc < 0) {
966 close(sfd);
967 return rc;
968 }
969
970 return sfd;
971}
972
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200973/*! Initialize a socket and fill \ref osmo_fd
Katerina Barone-Adesic28c6a02013-02-15 13:27:59 +0100974 * \param[out] ofd file descriptor (will be filled in)
Harald Welteba6988b2011-08-17 12:46:48 +0200975 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
976 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
977 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
978 * \param[in] host remote host name or IP address in string form
979 * \param[in] port remote port number in host byte order
980 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200981 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200982 *
983 * This function creates (and optionall binds/connects) a socket using
984 * \ref osmo_sock_init, but also fills the \a ofd structure.
985 */
Harald Welte68b15742011-05-22 21:47:29 +0200986int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200987 const char *host, uint16_t port, unsigned int flags)
Harald Welte68b15742011-05-22 21:47:29 +0200988{
Max862ba652014-10-13 14:54:25 +0200989 return osmo_fd_init_ofd(ofd, osmo_sock_init(family, type, proto, host, port, flags));
Harald Welte33cb71a2011-05-21 18:54:32 +0200990}
991
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200992/*! Initialize a socket and fill \ref osmo_fd
Pau Espin Pedrol75989e62017-05-26 12:39:53 +0200993 * \param[out] ofd file descriptor (will be filled in)
994 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
995 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
996 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
997 * \param[in] local_host local host name or IP address in string form
998 * \param[in] local_port local port number in host byte order
999 * \param[in] remote_host remote host name or IP address in string form
1000 * \param[in] remote_port remote port number in host byte order
1001 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
1002 * \returns socket fd on success; negative on error
1003 *
1004 * This function creates (and optionall binds/connects) a socket using
1005 * \ref osmo_sock_init2, but also fills the \a ofd structure.
1006 */
1007int osmo_sock_init2_ofd(struct osmo_fd *ofd, int family, int type, int proto,
1008 const char *local_host, uint16_t local_port,
1009 const char *remote_host, uint16_t remote_port, unsigned int flags)
1010{
1011 return osmo_fd_init_ofd(ofd, osmo_sock_init2(family, type, proto, local_host,
1012 local_port, remote_host, remote_port, flags));
1013}
1014
Alexander Couzens43957e62020-08-01 21:56:45 +02001015int osmo_sock_init_osa_ofd(struct osmo_fd *ofd, int type, int proto,
1016 const struct osmo_sockaddr *local,
1017 const struct osmo_sockaddr *remote, unsigned int flags)
1018{
1019 return osmo_fd_init_ofd(ofd, osmo_sock_init_osa(type, proto, local, remote, flags));
1020}
1021
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001022/*! Initialize a socket and fill \ref sockaddr
Harald Welteba6988b2011-08-17 12:46:48 +02001023 * \param[out] ss socket address (will be filled in)
1024 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1025 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1026 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001027 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +02001028 *
1029 * This function creates (and optionall binds/connects) a socket using
1030 * \ref osmo_sock_init, but also fills the \a ss structure.
1031 */
Harald Welte33cb71a2011-05-21 18:54:32 +02001032int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001033 uint8_t proto, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +02001034{
1035 char host[NI_MAXHOST];
1036 uint16_t port;
1037 struct sockaddr_in *sin;
1038 struct sockaddr_in6 *sin6;
1039 int s, sa_len;
1040
1041 /* determine port and host from ss */
1042 switch (ss->sa_family) {
1043 case AF_INET:
1044 sin = (struct sockaddr_in *) ss;
1045 sa_len = sizeof(struct sockaddr_in);
1046 port = ntohs(sin->sin_port);
1047 break;
1048 case AF_INET6:
1049 sin6 = (struct sockaddr_in6 *) ss;
1050 sa_len = sizeof(struct sockaddr_in6);
1051 port = ntohs(sin6->sin6_port);
1052 break;
1053 default:
1054 return -EINVAL;
1055 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001056
1057 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
1058 NULL, 0, NI_NUMERICHOST);
1059 if (s != 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001060 LOGP(DLGLOBAL, LOGL_ERROR, "getnameinfo failed:"
1061 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001062 return s;
1063 }
1064
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +02001065 return osmo_sock_init(ss->sa_family, type, proto, host, port, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +02001066}
1067
1068static int sockaddr_equal(const struct sockaddr *a,
Harald Weltee4764422011-05-22 12:25:57 +02001069 const struct sockaddr *b, unsigned int len)
Harald Welte33cb71a2011-05-21 18:54:32 +02001070{
1071 struct sockaddr_in *sin_a, *sin_b;
1072 struct sockaddr_in6 *sin6_a, *sin6_b;
1073
1074 if (a->sa_family != b->sa_family)
1075 return 0;
1076
1077 switch (a->sa_family) {
1078 case AF_INET:
1079 sin_a = (struct sockaddr_in *)a;
1080 sin_b = (struct sockaddr_in *)b;
1081 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
1082 sizeof(struct in_addr)))
1083 return 1;
1084 break;
1085 case AF_INET6:
1086 sin6_a = (struct sockaddr_in6 *)a;
1087 sin6_b = (struct sockaddr_in6 *)b;
1088 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
1089 sizeof(struct in6_addr)))
1090 return 1;
1091 break;
1092 }
1093 return 0;
1094}
1095
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001096/*! Determine if the given address is a local address
Harald Welteba6988b2011-08-17 12:46:48 +02001097 * \param[in] addr Socket Address
1098 * \param[in] addrlen Length of socket address in bytes
1099 * \returns 1 if address is local, 0 otherwise.
1100 */
Harald Weltebc32d052012-04-08 11:31:32 +02001101int osmo_sockaddr_is_local(struct sockaddr *addr, unsigned int addrlen)
Harald Welte33cb71a2011-05-21 18:54:32 +02001102{
1103 struct ifaddrs *ifaddr, *ifa;
1104
1105 if (getifaddrs(&ifaddr) == -1) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001106 LOGP(DLGLOBAL, LOGL_ERROR, "getifaddrs:"
1107 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +02001108 return -EIO;
1109 }
1110
1111 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
Harald Welte4d3a7b12011-05-24 21:31:53 +02001112 if (!ifa->ifa_addr)
1113 continue;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001114 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen)) {
1115 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001116 return 1;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001117 }
Harald Welte33cb71a2011-05-21 18:54:32 +02001118 }
1119
Pau Espin Pedrol15753e92018-04-18 19:57:41 +02001120 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +02001121 return 0;
1122}
Harald Weltee4764422011-05-22 12:25:57 +02001123
Max9d7a2472018-11-20 15:18:31 +01001124/*! Convert sockaddr_in to IP address as char string and port as uint16_t.
1125 * \param[out] addr String buffer to write IP address to, or NULL.
1126 * \param[out] addr_len Size of \a addr.
1127 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1128 * \param[in] sin Sockaddr to convert.
1129 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1130 */
1131size_t osmo_sockaddr_in_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1132 const struct sockaddr_in *sin)
1133{
1134 if (port)
1135 *port = ntohs(sin->sin_port);
1136
1137 if (addr)
1138 return osmo_strlcpy(addr, inet_ntoa(sin->sin_addr), addr_len);
1139
1140 return 0;
1141}
1142
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001143/*! Convert sockaddr to IP address as char string and port as uint16_t.
1144 * \param[out] addr String buffer to write IP address to, or NULL.
1145 * \param[out] addr_len Size of \a addr.
1146 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
1147 * \param[in] sa Sockaddr to convert.
1148 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
1149 */
1150unsigned int osmo_sockaddr_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
1151 const struct sockaddr *sa)
1152{
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001153
Pau Espin Pedrol1a3d24e2020-08-28 18:31:32 +02001154 const struct sockaddr_in6 *sin6;
1155
1156 switch (sa->sa_family) {
1157 case AF_INET:
1158 return osmo_sockaddr_in_to_str_and_uint(addr, addr_len, port,
1159 (const struct sockaddr_in *)sa);
1160 case AF_INET6:
1161 sin6 = (const struct sockaddr_in6 *)sa;
1162 if (port)
1163 *port = ntohs(sin6->sin6_port);
1164 if (addr && inet_ntop(sa->sa_family, &sin6->sin6_addr, addr, addr_len))
1165 return strlen(addr);
1166 break;
1167 }
1168 return 0;
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +02001169}
1170
Pau Espin Pedrol5cc4fe42020-08-31 12:52:06 +02001171/*! inet_ntop() wrapper for a struct sockaddr.
1172 * \param[in] sa source sockaddr to get the address from.
1173 * \param[out] dst string buffer of at least INET6_ADDRSTRLEN size.
1174 * \returns returns a non-null pointer to dst. NULL is returned if there was an
1175 * error, with errno set to indicate the error.
1176 */
1177const char *osmo_sockaddr_ntop(const struct sockaddr *sa, char *dst)
1178{
1179 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1180 return inet_ntop(osa->u.sa.sa_family,
1181 osa->u.sa.sa_family == AF_INET6 ?
1182 (const void *)&osa->u.sin6.sin6_addr :
1183 (const void *)&osa->u.sin.sin_addr,
1184 dst, INET6_ADDRSTRLEN);
1185}
1186
1187/*! Get sockaddr port content (in host byte order)
1188 * \param[in] sa source sockaddr to get the port from.
1189 * \returns returns the sockaddr port in host byte order
1190 */
1191uint16_t osmo_sockaddr_port(const struct sockaddr *sa)
1192{
1193 const struct osmo_sockaddr *osa = (const struct osmo_sockaddr *)sa;
1194 switch (osa->u.sa.sa_family) {
1195 case AF_INET6:
1196 return ntohs(osa->u.sin6.sin6_port);
1197 case AF_INET:
1198 return ntohs(osa->u.sin.sin_port);
1199 }
1200 return 0;
1201}
1202
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001203/*! Initialize a unix domain socket (including bind/connect)
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001204 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1205 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1206 * \param[in] socket_path path to identify the socket
1207 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001208 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001209 *
1210 * This function creates a new unix domain socket, \a
1211 * type and \a proto and optionally binds or connects it, depending on
1212 * the value of \a flags parameter.
1213 */
Eric Wildeb5769b2019-06-27 15:31:17 +02001214#if defined(__clang__) && defined(SUN_LEN)
1215__attribute__((no_sanitize("undefined")))
1216#endif
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001217int osmo_sock_unix_init(uint16_t type, uint8_t proto,
1218 const char *socket_path, unsigned int flags)
1219{
1220 struct sockaddr_un local;
1221 int sfd, rc, on = 1;
1222 unsigned int namelen;
1223
1224 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
1225 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT))
1226 return -EINVAL;
1227
1228 local.sun_family = AF_UNIX;
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001229 /* When an AF_UNIX socket is bound, sun_path should be NUL-terminated. See unix(7) man page. */
1230 if (osmo_strlcpy(local.sun_path, socket_path, sizeof(local.sun_path)) >= sizeof(local.sun_path)) {
Stefan Sperling896ff6d2018-08-28 14:34:17 +02001231 LOGP(DLGLOBAL, LOGL_ERROR, "Socket path exceeds maximum length of %zd bytes: %s\n",
1232 sizeof(local.sun_path), socket_path);
1233 return -ENOSPC;
1234 }
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001235
1236#if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001237 local.sun_len = strlen(local.sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001238#endif
1239#if defined(BSD44SOCKETS) || defined(SUN_LEN)
1240 namelen = SUN_LEN(&local);
1241#else
Stefan Sperling6afb3f52018-09-20 17:21:05 +02001242 namelen = strlen(local.sun_path) +
1243 offsetof(struct sockaddr_un, sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001244#endif
1245
1246 sfd = socket(AF_UNIX, type, proto);
1247 if (sfd < 0)
1248 return -1;
1249
1250 if (flags & OSMO_SOCK_F_CONNECT) {
1251 rc = connect(sfd, (struct sockaddr *)&local, namelen);
1252 if (rc < 0)
1253 goto err;
1254 } else {
1255 unlink(local.sun_path);
1256 rc = bind(sfd, (struct sockaddr *)&local, namelen);
1257 if (rc < 0)
1258 goto err;
1259 }
1260
1261 if (flags & OSMO_SOCK_F_NONBLOCK) {
1262 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +01001263 LOGP(DLGLOBAL, LOGL_ERROR,
1264 "cannot set this socket unblocking: %s\n",
1265 strerror(errno));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001266 close(sfd);
1267 return -EINVAL;
1268 }
1269 }
1270
Harald Weltec47bbda2017-07-13 16:13:26 +02001271 rc = osmo_sock_init_tail(sfd, type, flags);
1272 if (rc < 0) {
1273 close(sfd);
1274 sfd = -1;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001275 }
1276
1277 return sfd;
1278err:
1279 close(sfd);
1280 return -1;
1281}
1282
Neels Hofmeyr87e45502017-06-20 00:17:59 +02001283/*! Initialize a unix domain socket and fill \ref osmo_fd
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001284 * \param[out] ofd file descriptor (will be filled in)
1285 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
1286 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
1287 * \param[in] socket_path path to identify the socket
1288 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +02001289 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001290 *
Vadim Yanitskiyb606d762019-06-01 19:02:47 +07001291 * This function creates (and optionally binds/connects) a socket
1292 * using osmo_sock_unix_init, but also fills the ofd structure.
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001293 */
1294int osmo_sock_unix_init_ofd(struct osmo_fd *ofd, uint16_t type, uint8_t proto,
1295 const char *socket_path, unsigned int flags)
1296{
Max862ba652014-10-13 14:54:25 +02001297 return osmo_fd_init_ofd(ofd, osmo_sock_unix_init(type, proto, socket_path, flags));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +01001298}
1299
Neels Hofmeyr01457512018-12-12 01:48:54 +01001300/*! Get the IP and/or port number on socket in separate string buffers.
Oliver Smith7acd5d02018-10-25 11:16:36 +02001301 * \param[in] fd file descriptor of socket
1302 * \param[out] ip IP address (will be filled in when not NULL)
1303 * \param[in] ip_len length of the ip buffer
1304 * \param[out] port number (will be filled in when not NULL)
1305 * \param[in] port_len length of the port buffer
1306 * \param[in] local (true) or remote (false) name will get looked at
1307 * \returns 0 on success; negative otherwise
1308 */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001309int 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 +02001310{
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001311 struct sockaddr_storage sa;
Oliver Smith7acd5d02018-10-25 11:16:36 +02001312 socklen_t len = sizeof(sa);
Oliver Smith860651e2018-10-30 14:31:57 +01001313 char ipbuf[INET6_ADDRSTRLEN], portbuf[6];
Oliver Smith7acd5d02018-10-25 11:16:36 +02001314 int rc;
1315
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001316 rc = local ? getsockname(fd, (struct sockaddr*)&sa, &len) : getpeername(fd, (struct sockaddr*)&sa, &len);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001317 if (rc < 0)
1318 return rc;
1319
Pau Espin Pedroled42a882020-08-21 15:39:17 +02001320 rc = getnameinfo((const struct sockaddr*)&sa, len, ipbuf, sizeof(ipbuf),
Oliver Smith7acd5d02018-10-25 11:16:36 +02001321 portbuf, sizeof(portbuf),
1322 NI_NUMERICHOST | NI_NUMERICSERV);
1323 if (rc < 0)
1324 return rc;
1325
1326 if (ip)
1327 strncpy(ip, ipbuf, ip_len);
1328 if (port)
1329 strncpy(port, portbuf, port_len);
1330 return 0;
1331}
1332
1333/*! Get local IP address on socket
1334 * \param[in] fd file descriptor of socket
1335 * \param[out] ip IP address (will be filled in)
1336 * \param[in] len length of the output buffer
1337 * \returns 0 on success; negative otherwise
1338 */
1339int osmo_sock_get_local_ip(int fd, char *ip, size_t len)
1340{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001341 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001342}
1343
1344/*! Get local port on socket
1345 * \param[in] fd file descriptor of socket
1346 * \param[out] port number (will be filled in)
1347 * \param[in] len length of the output buffer
1348 * \returns 0 on success; negative otherwise
1349 */
1350int osmo_sock_get_local_ip_port(int fd, char *port, size_t len)
1351{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001352 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001353}
1354
1355/*! Get remote IP address on socket
1356 * \param[in] fd file descriptor of socket
1357 * \param[out] ip IP address (will be filled in)
1358 * \param[in] len length of the output buffer
1359 * \returns 0 on success; negative otherwise
1360 */
1361int osmo_sock_get_remote_ip(int fd, char *ip, size_t len)
1362{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001363 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001364}
1365
1366/*! Get remote port on socket
1367 * \param[in] fd file descriptor of socket
1368 * \param[out] port number (will be filled in)
1369 * \param[in] len length of the output buffer
1370 * \returns 0 on success; negative otherwise
1371 */
1372int osmo_sock_get_remote_ip_port(int fd, char *port, size_t len)
1373{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001374 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001375}
1376
Neels Hofmeyr01457512018-12-12 01:48:54 +01001377/*! Get address/port information on socket in dyn-alloc string like "(r=1.2.3.4:5<->l=6.7.8.9:10)".
1378 * Usually, it is better to use osmo_sock_get_name2() for a static string buffer or osmo_sock_get_name_buf() for a
1379 * caller provided string buffer, to avoid the dynamic talloc allocation.
Harald Welte48f55832017-01-26 00:03:10 +01001380 * \param[in] ctx talloc context from which to allocate string buffer
1381 * \param[in] fd file descriptor of socket
Neels Hofmeyr01457512018-12-12 01:48:54 +01001382 * \returns string identifying the connection of this socket, talloc'd from ctx.
Harald Welte48f55832017-01-26 00:03:10 +01001383 */
Harald Weltec0dfc9d2019-03-18 18:29:43 +01001384char *osmo_sock_get_name(const void *ctx, int fd)
Harald Welte48f55832017-01-26 00:03:10 +01001385{
Philipp Maier64b51eb2019-01-14 11:59:11 +01001386 char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001387 int rc;
1388 rc = osmo_sock_get_name_buf(str, sizeof(str), fd);
1389 if (rc <= 0)
1390 return NULL;
1391 return talloc_asprintf(ctx, "(%s)", str);
1392}
1393
1394/*! Get address/port information on socket in provided string buffer, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1395 * This does not include braces like osmo_sock_get_name().
1396 * \param[out] str Destination string buffer.
1397 * \param[in] str_len sizeof(str).
1398 * \param[in] fd File descriptor of socket.
1399 * \return String length as returned by snprintf(), or negative on error.
1400 */
1401int osmo_sock_get_name_buf(char *str, size_t str_len, int fd)
1402{
Oliver Smith860651e2018-10-30 14:31:57 +01001403 char hostbuf_l[INET6_ADDRSTRLEN], hostbuf_r[INET6_ADDRSTRLEN];
1404 char portbuf_l[6], portbuf_r[6];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001405 int rc;
Harald Welte48f55832017-01-26 00:03:10 +01001406
Oliver Smith7acd5d02018-10-25 11:16:36 +02001407 /* get local */
Harald Welteea9ea522019-05-10 09:28:24 +02001408 if ((rc = osmo_sock_get_ip_and_port(fd, hostbuf_l, sizeof(hostbuf_l), portbuf_l, sizeof(portbuf_l), true))) {
1409 osmo_strlcpy(str, "<error-in-getsockname>", str_len);
Neels Hofmeyr01457512018-12-12 01:48:54 +01001410 return rc;
Harald Welteea9ea522019-05-10 09:28:24 +02001411 }
Harald Welte48f55832017-01-26 00:03:10 +01001412
Oliver Smith7acd5d02018-10-25 11:16:36 +02001413 /* get remote */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001414 if (osmo_sock_get_ip_and_port(fd, hostbuf_r, sizeof(hostbuf_r), portbuf_r, sizeof(portbuf_r), false) != 0)
1415 return snprintf(str, str_len, "r=NULL<->l=%s:%s", hostbuf_l, portbuf_l);
Harald Welte48f55832017-01-26 00:03:10 +01001416
Neels Hofmeyr01457512018-12-12 01:48:54 +01001417 return snprintf(str, str_len, "r=%s:%s<->l=%s:%s", hostbuf_r, portbuf_r, hostbuf_l, portbuf_l);
1418}
1419
1420/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1421 * This does not include braces like osmo_sock_get_name().
1422 * \param[in] fd File descriptor of socket.
1423 * \return Static string buffer containing the result.
1424 */
1425const char *osmo_sock_get_name2(int fd)
1426{
Harald Welte171ef822019-03-28 10:49:05 +01001427 static __thread char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001428 osmo_sock_get_name_buf(str, sizeof(str), fd);
1429 return str;
Harald Welte48f55832017-01-26 00:03:10 +01001430}
1431
Harald Welte179f3572019-03-18 18:38:47 +01001432/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1433 * This does not include braces like osmo_sock_get_name().
1434 * \param[in] fd File descriptor of socket.
1435 * \return Static string buffer containing the result.
1436 */
1437char *osmo_sock_get_name2_c(const void *ctx, int fd)
1438{
1439 char *str = talloc_size(ctx, OSMO_SOCK_NAME_MAXLEN);
1440 if (!str)
1441 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001442 osmo_sock_get_name_buf(str, OSMO_SOCK_NAME_MAXLEN, fd);
Harald Welte179f3572019-03-18 18:38:47 +01001443 return str;
1444}
1445
Harald Weltee30d7e62017-07-13 16:02:50 +02001446static int sock_get_domain(int fd)
1447{
1448 int domain;
1449#ifdef SO_DOMAIN
1450 socklen_t dom_len = sizeof(domain);
1451 int rc;
1452
1453 rc = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &dom_len);
1454 if (rc < 0)
1455 return rc;
1456#else
1457 /* This of course sucks, but what shall we do on OSs like
1458 * FreeBSD that don't seem to expose a method by which one can
1459 * learn the address family of a socket? */
1460 domain = AF_INET;
1461#endif
1462 return domain;
1463}
1464
1465
1466/*! Activate or de-activate local loop-back of transmitted multicast packets
1467 * \param[in] fd file descriptor of related socket
1468 * \param[in] enable Enable (true) or disable (false) loop-back
1469 * \returns 0 on success; negative otherwise */
1470int osmo_sock_mcast_loop_set(int fd, bool enable)
1471{
1472 int domain, loop = 0;
1473
1474 if (enable)
1475 loop = 1;
1476
1477 domain = sock_get_domain(fd);
1478 if (domain < 0)
1479 return domain;
1480
1481 switch (domain) {
1482 case AF_INET:
1483 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1484 case AF_INET6:
1485 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop));
1486 default:
1487 return -EINVAL;
1488 }
1489}
1490
1491/*! Set the TTL of outbound multicast packets
1492 * \param[in] fd file descriptor of related socket
1493 * \param[in] ttl TTL of to-be-sent multicast packets
1494 * \returns 0 on success; negative otherwise */
1495int osmo_sock_mcast_ttl_set(int fd, uint8_t ttl)
1496{
1497 int domain, ttli = ttl;
1498
1499 domain = sock_get_domain(fd);
1500 if (domain < 0)
1501 return domain;
1502
1503 switch (domain) {
1504 case AF_INET:
1505 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttli, sizeof(ttli));
1506 case AF_INET6:
1507 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttli, sizeof(ttli));
1508 default:
1509 return -EINVAL;
1510 }
1511}
1512
Harald Welte44b99262020-03-07 14:59:05 +01001513/*! Set the network device to which we should bind the multicast socket
1514 * \param[in] fd file descriptor of related socket
1515 * \param[in] ifname name of network interface to user for multicast
1516 * \returns 0 on success; negative otherwise */
1517int osmo_sock_mcast_iface_set(int fd, const char *ifname)
1518{
1519 unsigned int ifindex;
1520 struct ip_mreqn mr;
1521
1522 /* first, resolve interface name to ifindex */
1523 ifindex = if_nametoindex(ifname);
1524 if (ifindex == 0)
1525 return -errno;
1526
1527 /* next, configure kernel to use that ifindex for this sockets multicast traffic */
1528 memset(&mr, 0, sizeof(mr));
1529 mr.imr_ifindex = ifindex;
1530 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mr, sizeof(mr));
1531}
1532
1533
Harald Weltee30d7e62017-07-13 16:02:50 +02001534/*! Enable/disable receiving all multicast packets, even for non-subscribed groups
1535 * \param[in] fd file descriptor of related socket
1536 * \param[in] enable Enable or Disable receiving of all packets
1537 * \returns 0 on success; negative otherwise */
1538int osmo_sock_mcast_all_set(int fd, bool enable)
1539{
1540 int domain, all = 0;
1541
1542 if (enable)
1543 all = 1;
1544
1545 domain = sock_get_domain(fd);
1546 if (domain < 0)
1547 return domain;
1548
1549 switch (domain) {
1550 case AF_INET:
1551#ifdef IP_MULTICAST_ALL
1552 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_ALL, &all, sizeof(all));
1553#endif
1554 case AF_INET6:
1555 /* there seems no equivalent ?!? */
1556 default:
1557 return -EINVAL;
1558 }
1559}
1560
1561/* FreeBSD calls the socket option differently */
1562#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
1563#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1564#endif
1565
1566/*! Subscribe to the given IP multicast group
1567 * \param[in] fd file descriptor of related scoket
1568 * \param[in] grp_addr ASCII representation of the multicast group address
1569 * \returns 0 on success; negative otherwise */
1570int osmo_sock_mcast_subscribe(int fd, const char *grp_addr)
1571{
1572 int rc, domain;
1573 struct ip_mreq mreq;
1574 struct ipv6_mreq mreq6;
1575 struct in6_addr i6a;
1576
1577 domain = sock_get_domain(fd);
1578 if (domain < 0)
1579 return domain;
1580
1581 switch (domain) {
1582 case AF_INET:
1583 memset(&mreq, 0, sizeof(mreq));
1584 mreq.imr_multiaddr.s_addr = inet_addr(grp_addr);
1585 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1586 return setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
1587#ifdef IPV6_ADD_MEMBERSHIP
1588 case AF_INET6:
1589 memset(&mreq6, 0, sizeof(mreq6));
1590 rc = inet_pton(AF_INET6, grp_addr, (void *)&i6a);
1591 if (rc < 0)
1592 return -EINVAL;
1593 mreq6.ipv6mr_multiaddr = i6a;
1594 return setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
1595#endif
1596 default:
1597 return -EINVAL;
1598 }
1599}
1600
Philipp Maier2d2490e2017-10-20 19:41:26 +02001601/*! Determine the matching local IP-address for a given remote IP-Address.
1602 * \param[out] local_ip caller provided memory for resulting local IP-address
1603 * \param[in] remote_ip remote IP-address
Philipp Maier2d2490e2017-10-20 19:41:26 +02001604 * \returns 0 on success; negative otherwise
1605 *
1606 * The function accepts IPv4 and IPv6 address strings. The caller must provide
1607 * at least INET6_ADDRSTRLEN bytes for local_ip if an IPv6 is expected as
1608 * as result. For IPv4 addresses the required amount is INET_ADDRSTRLEN. */
1609int osmo_sock_local_ip(char *local_ip, const char *remote_ip)
1610{
1611 int sfd;
1612 int rc;
1613 struct addrinfo addrinfo_hint;
1614 struct addrinfo *addrinfo = NULL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001615 struct sockaddr_storage local_addr;
1616 struct sockaddr_in *sin;
1617 struct sockaddr_in6 *sin6;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001618 socklen_t local_addr_len;
1619 uint16_t family;
1620
1621 /* Find out the address family (AF_INET or AF_INET6?) */
1622 memset(&addrinfo_hint, '\0', sizeof(addrinfo_hint));
Pau Espin Pedrol308ab792020-08-28 19:47:25 +02001623 addrinfo_hint.ai_family = AF_UNSPEC;
Philipp Maier2d2490e2017-10-20 19:41:26 +02001624 addrinfo_hint.ai_flags = AI_NUMERICHOST;
1625 rc = getaddrinfo(remote_ip, NULL, &addrinfo_hint, &addrinfo);
1626 if (rc)
1627 return -EINVAL;
1628 family = addrinfo->ai_family;
1629 freeaddrinfo(addrinfo);
1630
1631 /* Connect a dummy socket to trick the kernel into determining the
1632 * ip-address of the interface that would be used if we would send
1633 * out an actual packet */
1634 sfd = osmo_sock_init2(family, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, remote_ip, 0, OSMO_SOCK_F_CONNECT);
1635 if (sfd < 0)
1636 return -EINVAL;
1637
1638 /* Request the IP address of the interface that the kernel has
1639 * actually choosen. */
1640 memset(&local_addr, 0, sizeof(local_addr));
1641 local_addr_len = sizeof(local_addr);
1642 rc = getsockname(sfd, (struct sockaddr *)&local_addr, &local_addr_len);
Philipp Maier8b7975b2018-01-22 15:38:07 +01001643 close(sfd);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001644 if (rc < 0)
1645 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001646
1647 switch (local_addr.ss_family) {
1648 case AF_INET:
1649 sin = (struct sockaddr_in*)&local_addr;
1650 if (!inet_ntop(AF_INET, &sin->sin_addr, local_ip, INET_ADDRSTRLEN))
1651 return -EINVAL;
1652 break;
1653 case AF_INET6:
1654 sin6 = (struct sockaddr_in6*)&local_addr;
Pau Espin Pedrol7bda8542020-08-31 11:21:30 +02001655 if (!inet_ntop(AF_INET6, &sin6->sin6_addr, local_ip, INET6_ADDRSTRLEN))
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001656 return -EINVAL;
1657 break;
1658 default:
Philipp Maier2d2490e2017-10-20 19:41:26 +02001659 return -EINVAL;
Pau Espin Pedrol81e7a6c2020-08-28 20:44:26 +02001660 }
Philipp Maier2d2490e2017-10-20 19:41:26 +02001661
1662 return 0;
1663}
1664
Alexander Couzens0f364212020-07-27 22:33:01 +02001665/*! Determine the matching local address for a given remote address.
1666 * \param[out] local_ip caller provided memory for resulting local address
1667 * \param[in] remote_ip remote address
1668 * \returns 0 on success; negative otherwise
1669 */
1670int osmo_sockaddr_local_ip(struct osmo_sockaddr *local_ip, const struct osmo_sockaddr *remote_ip)
1671{
1672 int sfd;
1673 int rc;
1674 socklen_t local_ip_len;
1675
1676 sfd = osmo_sock_init_osa(SOCK_DGRAM, IPPROTO_UDP, NULL, remote_ip, OSMO_SOCK_F_CONNECT);
1677 if (sfd < 0)
1678 return -EINVAL;
1679
1680 memset(local_ip, 0, sizeof(*local_ip));
1681 local_ip_len = sizeof(*local_ip);
1682 rc = getsockname(sfd, (struct sockaddr *)local_ip, &local_ip_len);
1683 close(sfd);
1684
1685 return rc;
1686}
1687
Alexander Couzense4181ea2020-07-20 00:03:16 +02001688/*! Compare two osmo_sockaddr.
1689 * \param[in] a
1690 * \param[in] b
1691 * \return 0 if a and b are equal. Otherwise it follows memcmp()
1692 */
Vadim Yanitskiydef5a402020-10-09 21:40:47 +07001693int osmo_sockaddr_cmp(const struct osmo_sockaddr *a,
1694 const struct osmo_sockaddr *b)
Alexander Couzense4181ea2020-07-20 00:03:16 +02001695{
1696 if (a == b)
1697 return 0;
1698 if (!a)
1699 return 1;
1700 if (!b)
1701 return -1;
1702
1703 if (a->u.sa.sa_family != b->u.sa.sa_family) {
1704 return OSMO_CMP(a->u.sa.sa_family, b->u.sa.sa_family);
1705 }
1706
1707 switch (a->u.sa.sa_family) {
1708 case AF_INET:
1709 return memcmp(&a->u.sin, &b->u.sin, sizeof(struct sockaddr_in));
1710 case AF_INET6:
1711 return memcmp(&a->u.sin6, &b->u.sin6, sizeof(struct sockaddr_in6));
1712 default:
1713 /* fallback to memcmp for remaining AF over the full osmo_sockaddr length */
1714 return memcmp(a, b, sizeof(struct osmo_sockaddr));
1715 }
1716}
1717
Alexander Couzens80788fa2020-10-12 01:11:20 +02001718/*! string-format a given osmo_sockaddr address
1719 * \param[in] sockaddr the osmo_sockaddr to print
1720 * \return pointer to the string on success; NULL on error
1721 */
1722const char *osmo_sockaddr_to_str(const struct osmo_sockaddr *sockaddr)
1723{
1724 /* INET6_ADDRSTRLEN contains already a null termination,
1725 * adding '[' ']' ':' '16 bit port' */
1726 static __thread char buf[INET6_ADDRSTRLEN + 8];
1727 return osmo_sockaddr_to_str_buf(buf, sizeof(buf), sockaddr);
1728}
1729
1730/*! string-format a given osmo_sockaddr address into a user-supplied buffer
1731 * \param[in] buf user-supplied output buffer
1732 * \param[in] buf_len size of the user-supplied output buffer in bytes
1733 * \param[in] sockaddr the osmo_sockaddr to print
1734 * \return pointer to the string on success; NULL on error
1735 */
1736char *osmo_sockaddr_to_str_buf(char *buf, size_t buf_len,
1737 const struct osmo_sockaddr *sockaddr)
1738{
1739 uint16_t port = 0;
1740 size_t written;
1741 if (buf_len < 5)
1742 return NULL;
1743
1744 if (!sockaddr)
1745 return NULL;
1746
1747 switch (sockaddr->u.sa.sa_family) {
1748 case AF_INET:
1749 written = osmo_sockaddr_to_str_and_uint(buf, buf_len, &port, &sockaddr->u.sa);
1750 if (written + 1 >= buf_len && port)
1751 return NULL;
1752 if (port)
1753 snprintf(buf + written, buf_len - written, ":%u", port);
1754 break;
1755 case AF_INET6:
1756 buf[0] = '[';
1757 written = osmo_sockaddr_to_str_and_uint(buf + 1, buf_len - 1, &port, &sockaddr->u.sa);
1758 if (written + 2 >= buf_len)
1759 return NULL;
1760
1761 if (written + 3 >= buf_len && port)
1762 return NULL;
1763
1764 if (port)
1765 snprintf(buf + 1 + written, buf_len - written - 1, "]:%u", port);
1766 else {
1767 buf[written + 1] = ']';
1768 buf[written + 2] = 0;
1769 }
1770 break;
1771 default:
1772 snprintf(buf, buf_len, "unsupported family %d", sockaddr->u.sa.sa_family);
1773 return buf;
1774 }
1775
1776 return buf;
1777}
1778
1779
Harald Weltee4764422011-05-22 12:25:57 +02001780#endif /* HAVE_SYS_SOCKET_H */
Harald Welteba6988b2011-08-17 12:46:48 +02001781
Sylvain Munautdca7d2c2012-04-18 21:53:23 +02001782/*! @} */