blob: 9b1d30ecc461717f21b965ecfd93fe33499c6490 [file] [log] [blame]
Harald Welte468b6432014-09-11 13:05:51 +08001/*
Harald Welte48f55832017-01-26 00:03:10 +01002 * (C) 2011-2017 by Harald Welte <laforge@gnumonks.org>
Harald Welte468b6432014-09-11 13:05:51 +08003 *
4 * All Rights Reserved
5 *
Harald Weltee08da972017-11-13 01:00:26 +09006 * SPDX-License-Identifier: GPL-2.0+
7 *
Harald Welte468b6432014-09-11 13:05:51 +08008 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 */
23
Harald Welte33cb71a2011-05-21 18:54:32 +020024#include "../config.h"
25
Harald Welteba6988b2011-08-17 12:46:48 +020026/*! \addtogroup socket
27 * @{
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020028 * Osmocom socket convenience functions.
29 *
30 * \file socket.c */
Harald Welte96e2a002017-06-12 21:44:18 +020031
Harald Weltee4764422011-05-22 12:25:57 +020032#ifdef HAVE_SYS_SOCKET_H
33
Harald Welte33cb71a2011-05-21 18:54:32 +020034#include <osmocom/core/logging.h>
35#include <osmocom/core/select.h>
36#include <osmocom/core/socket.h>
Harald Welte48f55832017-01-26 00:03:10 +010037#include <osmocom/core/talloc.h>
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +020038#include <osmocom/core/utils.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020039
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +020040#include <sys/ioctl.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020041#include <sys/socket.h>
42#include <sys/types.h>
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +010043#include <sys/un.h>
Harald Welte33cb71a2011-05-21 18:54:32 +020044
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010045#include <netinet/in.h>
Harald Weltee30d7e62017-07-13 16:02:50 +020046#include <arpa/inet.h>
Holger Hans Peter Freyther47723482011-11-09 11:26:15 +010047
Harald Welte33cb71a2011-05-21 18:54:32 +020048#include <stdio.h>
49#include <unistd.h>
50#include <stdint.h>
51#include <string.h>
52#include <errno.h>
53#include <netdb.h>
54#include <ifaddrs.h>
55
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +020056#ifdef HAVE_LIBSCTP
57#include <netinet/sctp.h>
58#endif
59
Harald Weltedda70fc2017-04-08 20:52:33 +020060static struct addrinfo *addrinfo_helper(uint16_t family, uint16_t type, uint8_t proto,
61 const char *host, uint16_t port, bool passive)
62{
Pau Espin Pedrolff428522019-10-10 17:38:16 +020063 struct addrinfo hints, *result, *rp;
Oliver Smith860651e2018-10-30 14:31:57 +010064 char portbuf[6];
Harald Weltedda70fc2017-04-08 20:52:33 +020065 int rc;
66
67 snprintf(portbuf, sizeof(portbuf), "%u", port);
68 memset(&hints, 0, sizeof(struct addrinfo));
69 hints.ai_family = family;
70 if (type == SOCK_RAW) {
71 /* Workaround for glibc, that returns EAI_SERVICE (-8) if
72 * SOCK_RAW and IPPROTO_GRE is used.
Pau Espin Pedrolff428522019-10-10 17:38:16 +020073 * http://sourceware.org/bugzilla/show_bug.cgi?id=15015
Harald Weltedda70fc2017-04-08 20:52:33 +020074 */
75 hints.ai_socktype = SOCK_DGRAM;
76 hints.ai_protocol = IPPROTO_UDP;
77 } else {
78 hints.ai_socktype = type;
79 hints.ai_protocol = proto;
80 }
81
82 if (passive)
83 hints.ai_flags |= AI_PASSIVE;
84
85 rc = getaddrinfo(host, portbuf, &hints, &result);
86 if (rc != 0) {
87 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo returned NULL: %s:%u: %s\n",
88 host, port, strerror(errno));
89 return NULL;
90 }
91
Pau Espin Pedrolff428522019-10-10 17:38:16 +020092 for (rp = result; rp != NULL; rp = rp->ai_next) {
93 /* Workaround for glibc again */
94 if (type == SOCK_RAW) {
95 rp->ai_socktype = SOCK_RAW;
96 rp->ai_protocol = proto;
97 }
98 }
99
Harald Weltedda70fc2017-04-08 20:52:33 +0200100 return result;
101}
102
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200103#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200104/*! Retrieve an array of addrinfo with specified hints, one for each host in the hosts array.
105 * \param[out] addrinfo array of addrinfo pointers, will be filled by the function on success.
106 * Its size must be at least the one of hosts.
107 * \param[in] family Socket family like AF_INET, AF_INET6.
108 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM.
109 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP.
110 * \param[in] hosts array of char pointers (strings) containing the addresses to query.
111 * \param[in] host_cnt length of the hosts array (in items).
112 * \param[in] port port number in host byte order.
113 * \param[in] passive whether to include the AI_PASSIVE flag in getaddrinfo() hints.
114 * \returns 0 is returned on success together with a filled addrinfo array; negative on error
115 */
116static int addrinfo_helper_multi(struct addrinfo **addrinfo, uint16_t family, uint16_t type, uint8_t proto,
117 const char **hosts, size_t host_cnt, uint16_t port, bool passive)
118{
119 int i, j;
120
121 for (i = 0; i < host_cnt; i++) {
122 addrinfo[i] = addrinfo_helper(family, type, proto, hosts[i], port, passive);
123 if (!addrinfo[i]) {
124 for (j = 0; j < i; j++)
125 freeaddrinfo(addrinfo[j]);
126 return -EINVAL;
127 }
128 }
129 return 0;
130}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200131#endif /* HAVE_LIBSCTP*/
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200132
Harald Weltedda70fc2017-04-08 20:52:33 +0200133static int socket_helper(const struct addrinfo *rp, unsigned int flags)
134{
135 int sfd, on = 1;
136
137 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200138 if (sfd == -1) {
139 LOGP(DLGLOBAL, LOGL_ERROR,
140 "unable to create socket: %s\n", strerror(errno));
Harald Weltedda70fc2017-04-08 20:52:33 +0200141 return sfd;
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200142 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200143 if (flags & OSMO_SOCK_F_NONBLOCK) {
144 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
145 LOGP(DLGLOBAL, LOGL_ERROR,
146 "cannot set this socket unblocking: %s\n",
147 strerror(errno));
148 close(sfd);
149 sfd = -EINVAL;
150 }
151 }
152 return sfd;
153}
154
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200155#ifdef HAVE_LIBSCTP
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200156/* Fill buf with a string representation of the address set, in the form:
157 * buf_len == 0: "()"
158 * buf_len == 1: "hostA"
159 * buf_len >= 2: (hostA|hostB|...|...)
160 */
161static int multiaddr_snprintf(char* buf, size_t buf_len, const char **hosts, size_t host_cnt)
162{
163 int len = 0, offset = 0, rem = buf_len;
164 int ret, i;
165 char *after;
166
167 if (buf_len < 3)
168 return -EINVAL;
169
170 if (host_cnt != 1) {
171 ret = snprintf(buf, rem, "(");
172 if (ret < 0)
173 return ret;
174 OSMO_SNPRINTF_RET(ret, rem, offset, len);
175 }
176 for (i = 0; i < host_cnt; i++) {
177 if (host_cnt == 1)
178 after = "";
179 else
180 after = (i == (host_cnt - 1)) ? ")" : "|";
181 ret = snprintf(buf + offset, rem, "%s%s", hosts[i] ? : "0.0.0.0", after);
182 OSMO_SNPRINTF_RET(ret, rem, offset, len);
183 }
184
185 return len;
186}
Pau Espin Pedrol8fac5112019-10-24 15:39:25 +0200187#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200188
Harald Weltec47bbda2017-07-13 16:13:26 +0200189static int osmo_sock_init_tail(int fd, uint16_t type, unsigned int flags)
190{
Harald Weltebc43a622017-07-13 16:20:21 +0200191 int rc;
Harald Weltec47bbda2017-07-13 16:13:26 +0200192
193 /* Make sure to call 'listen' on a bound, connection-oriented sock */
194 if ((flags & (OSMO_SOCK_F_BIND|OSMO_SOCK_F_CONNECT)) == OSMO_SOCK_F_BIND) {
195 switch (type) {
196 case SOCK_STREAM:
197 case SOCK_SEQPACKET:
198 rc = listen(fd, 10);
Harald Weltebc43a622017-07-13 16:20:21 +0200199 if (rc < 0) {
200 LOGP(DLGLOBAL, LOGL_ERROR, "unable to listen on socket: %s\n",
201 strerror(errno));
202 return rc;
203 }
204 break;
Harald Weltec47bbda2017-07-13 16:13:26 +0200205 }
206 }
207
Harald Weltebc43a622017-07-13 16:20:21 +0200208 if (flags & OSMO_SOCK_F_NO_MCAST_LOOP) {
209 rc = osmo_sock_mcast_loop_set(fd, false);
210 if (rc < 0) {
211 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable multicast loop: %s\n",
212 strerror(errno));
213 return rc;
214 }
215 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200216
Harald Welte37d204a2017-07-13 16:33:16 +0200217 if (flags & OSMO_SOCK_F_NO_MCAST_ALL) {
218 rc = osmo_sock_mcast_all_set(fd, false);
219 if (rc < 0) {
220 LOGP(DLGLOBAL, LOGL_ERROR, "unable to disable receive of all multicast: %s\n",
221 strerror(errno));
222 /* do not abort here, as this is just an
223 * optional additional optimization that only
224 * exists on Linux only */
225 }
226 }
Harald Weltebc43a622017-07-13 16:20:21 +0200227 return 0;
Harald Weltec47bbda2017-07-13 16:13:26 +0200228}
229
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200230/*! Initialize a socket (including bind and/or connect)
Harald Weltedda70fc2017-04-08 20:52:33 +0200231 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
232 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
233 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
234 * \param[in] local_host local host name or IP address in string form
235 * \param[in] local_port local port number in host byte order
236 * \param[in] remote_host remote host name or IP address in string form
237 * \param[in] remote_port remote port number in host byte order
238 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
239 * \returns socket file descriptor on success; negative on error
240 *
241 * This function creates a new socket of the designated \a family, \a
242 * type and \a proto and optionally binds it to the \a local_host and \a
243 * local_port as well as optionally connects it to the \a remote_host
244 * and \q remote_port, depending on the value * of \a flags parameter.
245 *
246 * As opposed to \ref osmo_sock_init(), this function allows to combine
247 * the \ref OSMO_SOCK_F_BIND and \ref OSMO_SOCK_F_CONNECT flags. This
248 * is useful if you want to connect to a remote host/port, but still
249 * want to bind that socket to either a specific local alias IP and/or a
250 * specific local source port.
251 *
252 * You must specify either \ref OSMO_SOCK_F_BIND, or \ref
253 * OSMO_SOCK_F_CONNECT, or both.
254 *
255 * If \ref OSMO_SOCK_F_NONBLOCK is specified, the socket will be set to
256 * non-blocking mode.
257 */
258int osmo_sock_init2(uint16_t family, uint16_t type, uint8_t proto,
259 const char *local_host, uint16_t local_port,
260 const char *remote_host, uint16_t remote_port, unsigned int flags)
261{
262 struct addrinfo *result, *rp;
263 int sfd = -1, rc, on = 1;
264
265 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
266 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
267 "BIND or CONNECT flags\n");
268 return -EINVAL;
269 }
270
271 /* figure out local side of socket */
272 if (flags & OSMO_SOCK_F_BIND) {
273 result = addrinfo_helper(family, type, proto, local_host, local_port, true);
274 if (!result)
275 return -EINVAL;
276
277 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200278 sfd = socket_helper(rp, flags);
279 if (sfd < 0)
280 continue;
281
Philipp Maier73196e72018-08-23 20:11:50 +0200282 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200283 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
284 &on, sizeof(on));
285 if (rc < 0) {
286 LOGP(DLGLOBAL, LOGL_ERROR,
287 "cannot setsockopt socket:"
288 " %s:%u: %s\n",
289 local_host, local_port,
290 strerror(errno));
291 close(sfd);
292 continue;
293 }
Harald Weltedda70fc2017-04-08 20:52:33 +0200294 }
Philipp Maier99f706d2018-08-01 12:40:36 +0200295
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200296 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
297 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket: %s:%u: %s\n",
298 local_host, local_port, strerror(errno));
299 close(sfd);
300 continue;
301 }
302 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200303 }
304 freeaddrinfo(result);
305 if (rp == NULL) {
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200306 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable local addr found for: %s:%u\n",
307 local_host, local_port);
Harald Weltedda70fc2017-04-08 20:52:33 +0200308 return -ENODEV;
309 }
310 }
311
Pau Espin Pedrol5d50fa52018-04-05 17:00:22 +0200312 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
313 was already closed and func returned. If OSMO_SOCK_F_BIND is not
314 set, then sfd = -1 */
315
Harald Weltedda70fc2017-04-08 20:52:33 +0200316 /* figure out remote side of socket */
317 if (flags & OSMO_SOCK_F_CONNECT) {
318 result = addrinfo_helper(family, type, proto, remote_host, remote_port, false);
319 if (!result) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200320 if (sfd >= 0)
321 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200322 return -EINVAL;
323 }
324
325 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Welte5cfa6dc2017-07-21 16:52:29 +0200326 if (sfd < 0) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200327 sfd = socket_helper(rp, flags);
328 if (sfd < 0)
329 continue;
330 }
331
332 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200333 if (rc != 0 && errno != EINPROGRESS) {
334 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
335 remote_host, remote_port, strerror(errno));
336 /* We want to maintain the bind socket if bind was enabled */
337 if (!(flags & OSMO_SOCK_F_BIND)) {
338 close(sfd);
339 sfd = -1;
340 }
341 continue;
342 }
343 break;
Harald Weltedda70fc2017-04-08 20:52:33 +0200344 }
345 freeaddrinfo(result);
346 if (rp == NULL) {
Pau Espin Pedrol27cf8df2018-04-05 17:49:08 +0200347 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable remote addr found for: %s:%u\n",
348 remote_host, remote_port);
349 if (sfd >= 0)
350 close(sfd);
Harald Weltedda70fc2017-04-08 20:52:33 +0200351 return -ENODEV;
352 }
353 }
354
Harald Weltec47bbda2017-07-13 16:13:26 +0200355 rc = osmo_sock_init_tail(sfd, type, flags);
356 if (rc < 0) {
357 close(sfd);
358 sfd = -1;
Harald Weltedda70fc2017-04-08 20:52:33 +0200359 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200360
Harald Weltedda70fc2017-04-08 20:52:33 +0200361 return sfd;
362}
363
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200364#ifdef HAVE_LIBSCTP
365
366
367/* Build array of addresses taking first addrinfo result of the requested family
368 * for each host in hosts. addrs4 or addrs6 are filled based on family type. */
369static int addrinfo_to_sockaddr(uint16_t family, const struct addrinfo **result,
370 const char **hosts, int host_cont,
371 struct sockaddr_in *addrs4, struct sockaddr_in6 *addrs6) {
372 size_t host_idx;
373 const struct addrinfo *rp;
374 OSMO_ASSERT(family == AF_INET || family == AF_INET6);
375
376 for (host_idx = 0; host_idx < host_cont; host_idx++) {
377 for (rp = result[host_idx]; rp != NULL; rp = rp->ai_next) {
378 if (rp->ai_family != family)
379 continue;
380 if (family == AF_INET)
381 memcpy(&addrs4[host_idx], rp->ai_addr, sizeof(addrs4[host_idx]));
382 else
383 memcpy(&addrs6[host_idx], rp->ai_addr, sizeof(addrs6[host_idx]));
384 break;
385 }
386 if (!rp) { /* No addr could be bound for this host! */
387 LOGP(DLGLOBAL, LOGL_ERROR, "No suitable remote address found for host: %s\n",
388 hosts[host_idx]);
389 return -ENODEV;
390 }
391 }
392 return 0;
393}
394
395/*! Initialize a socket (including bind and/or connect) with multiple local or remote addresses.
396 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
397 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
398 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
399 * \param[in] local_hosts array of char pointers (strings), each containing local host name or IP address in string form
400 * \param[in] local_hosts_cnt length of local_hosts (in items)
401 * \param[in] local_port local port number in host byte order
402 * \param[in] remote_host array of char pointers (strings), each containing remote host name or IP address in string form
403 * \param[in] remote_hosts_cnt length of remote_hosts (in items)
404 * \param[in] remote_port remote port number in host byte order
405 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
406 * \returns socket file descriptor on success; negative on error
407 *
408 * This function is similar to \ref osmo_sock_init2(), but can be passed an
409 * array of local or remote addresses for protocols supporting multiple
410 * addresses per socket, like SCTP (currently only one supported). This function
411 * should not be used by protocols not supporting this kind of features, but
412 * rather \ref osmo_sock_init2() should be used instead.
413 * See \ref osmo_sock_init2() for more information on flags and general behavior.
414 */
415int osmo_sock_init2_multiaddr(uint16_t family, uint16_t type, uint8_t proto,
416 const char **local_hosts, size_t local_hosts_cnt, uint16_t local_port,
417 const char **remote_hosts, size_t remote_hosts_cnt, uint16_t remote_port,
418 unsigned int flags)
419
420{
421 struct addrinfo *result[OSMO_SOCK_MAX_ADDRS];
422 int sfd = -1, rc, on = 1;
423 int i;
424 struct sockaddr_in addrs4[OSMO_SOCK_MAX_ADDRS];
425 struct sockaddr_in6 addrs6[OSMO_SOCK_MAX_ADDRS];
426 struct sockaddr *addrs;
427 char strbuf[512];
428
429 /* TODO: So far this function is only aimed for SCTP, but could be
430 reused in the future for other protocols with multi-addr support */
431 if (proto != IPPROTO_SCTP)
432 return -ENOTSUP;
433
434 /* TODO: Let's not support AF_UNSPEC for now. sctp_bindx() actually
435 supports binding both types of addresses on a AF_INET6 soscket, but
436 that would mean we could get both AF_INET and AF_INET6 addresses for
437 each host, and makes complexity of this function increase a lot since
438 we'd need to find out which subsets to use, use v4v6 mapped socket,
439 etc. */
440 if (family == AF_UNSPEC)
441 return -ENOTSUP;
442
443 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) == 0) {
444 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: you have to specify either "
445 "BIND or CONNECT flags\n");
446 return -EINVAL;
447 }
448
449 if (((flags & OSMO_SOCK_F_BIND) && !local_hosts_cnt) ||
450 ((flags & OSMO_SOCK_F_CONNECT) && !remote_hosts_cnt) ||
451 local_hosts_cnt > OSMO_SOCK_MAX_ADDRS ||
452 remote_hosts_cnt > OSMO_SOCK_MAX_ADDRS)
453 return -EINVAL;
454
455 /* figure out local side of socket */
456 if (flags & OSMO_SOCK_F_BIND) {
457 rc = addrinfo_helper_multi(result, family, type, proto, local_hosts,
458 local_hosts_cnt, local_port, true);
459 if (rc < 0)
460 return -EINVAL;
461
462 /* Since addrinfo_helper sets ai_family, socktype and
463 ai_protocol in hints, we know all results will use same
464 values, so simply pick the first one and pass it to create
465 the socket:
466 */
467 sfd = socket_helper(result[0], flags);
468 if (sfd < 0) {
469 for (i = 0; i < local_hosts_cnt; i++)
470 freeaddrinfo(result[i]);
471 return sfd;
472 }
473
Pau Espin Pedrol272dfc12019-10-21 11:11:27 +0200474 /* Since so far we only allow IPPROTO_SCTP in this function,
475 no need to check below for "proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR" */
476 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
477 &on, sizeof(on));
478 if (rc < 0) {
479 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
480 LOGP(DLGLOBAL, LOGL_ERROR,
481 "cannot setsockopt socket:"
482 " %s:%u: %s\n",
483 strbuf, local_port,
484 strerror(errno));
485 for (i = 0; i < local_hosts_cnt; i++)
486 freeaddrinfo(result[i]);
487 close(sfd);
488 return rc;
Pau Espin Pedrol3f464fc2019-10-10 17:38:35 +0200489 }
490
491 /* Build array of addresses taking first of same family for each host.
492 TODO: Ideally we should use backtracking storing last used
493 indexes and trying next combination if connect() fails .*/
494 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)result,
495 local_hosts, local_hosts_cnt, addrs4, addrs6);
496 if (rc < 0) {
497 for (i = 0; i < local_hosts_cnt; i++)
498 freeaddrinfo(result[i]);
499 close(sfd);
500 return -ENODEV;
501 }
502
503 if (family == AF_INET)
504 addrs = (struct sockaddr *)addrs4;
505 else
506 addrs = (struct sockaddr *)addrs6;
507 if (sctp_bindx(sfd, addrs, local_hosts_cnt, SCTP_BINDX_ADD_ADDR) == -1) {
508 multiaddr_snprintf(strbuf, sizeof(strbuf), local_hosts, local_hosts_cnt);
509 LOGP(DLGLOBAL, LOGL_NOTICE, "unable to bind socket: %s:%u: %s\n",
510 strbuf, local_port, strerror(errno));
511 for (i = 0; i < local_hosts_cnt; i++)
512 freeaddrinfo(result[i]);
513 close(sfd);
514 return -ENODEV;
515 }
516 for (i = 0; i < local_hosts_cnt; i++)
517 freeaddrinfo(result[i]);
518 }
519
520 /* Reached this point, if OSMO_SOCK_F_BIND then sfd is valid (>=0) or it
521 was already closed and func returned. If OSMO_SOCK_F_BIND is not
522 set, then sfd = -1 */
523
524 /* figure out remote side of socket */
525 if (flags & OSMO_SOCK_F_CONNECT) {
526 rc = addrinfo_helper_multi(result, family, type, proto, remote_hosts,
527 remote_hosts_cnt, remote_port, false);
528 if (rc < 0) {
529 if (sfd >= 0)
530 close(sfd);
531 return -EINVAL;
532 }
533
534 if (sfd < 0) {
535 /* Since addrinfo_helper sets ai_family, socktype and
536 ai_protocol in hints, we know all results will use same
537 values, so simply pick the first one and pass it to create
538 the socket:
539 */
540 sfd = socket_helper(result[0], flags);
541 if (sfd < 0) {
542 for (i = 0; i < remote_hosts_cnt; i++)
543 freeaddrinfo(result[i]);
544 return sfd;
545 }
546 }
547
548 /* Build array of addresses taking first of same family for each host.
549 TODO: Ideally we should use backtracking storing last used
550 indexes and trying next combination if connect() fails .*/
551 rc = addrinfo_to_sockaddr(family, (const struct addrinfo **)result,
552 remote_hosts, remote_hosts_cnt, addrs4, addrs6);
553 if (rc < 0) {
554 for (i = 0; i < remote_hosts_cnt; i++)
555 freeaddrinfo(result[i]);
556 close(sfd);
557 return -ENODEV;
558 }
559
560 if (family == AF_INET)
561 addrs = (struct sockaddr *)addrs4;
562 else
563 addrs = (struct sockaddr *)addrs6;
564 rc = sctp_connectx(sfd, addrs, remote_hosts_cnt, NULL);
565 if (rc != 0 && errno != EINPROGRESS) {
566 multiaddr_snprintf(strbuf, sizeof(strbuf), remote_hosts, remote_hosts_cnt);
567 LOGP(DLGLOBAL, LOGL_ERROR, "unable to connect socket: %s:%u: %s\n",
568 strbuf, remote_port, strerror(errno));
569 for (i = 0; i < remote_hosts_cnt; i++)
570 freeaddrinfo(result[i]);
571 close(sfd);
572 return -ENODEV;
573 }
574 for (i = 0; i < remote_hosts_cnt; i++)
575 freeaddrinfo(result[i]);
576 }
577
578 rc = osmo_sock_init_tail(sfd, type, flags);
579 if (rc < 0) {
580 close(sfd);
581 sfd = -1;
582 }
583
584 return sfd;
585}
586#endif /* HAVE_LIBSCTP */
Harald Weltedda70fc2017-04-08 20:52:33 +0200587
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200588/*! Initialize a socket (including bind/connect)
Harald Welteba6988b2011-08-17 12:46:48 +0200589 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
590 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
591 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
592 * \param[in] host remote host name or IP address in string form
593 * \param[in] port remote port number in host byte order
594 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200595 * \returns socket file descriptor on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200596 *
597 * This function creates a new socket of the designated \a family, \a
598 * type and \a proto and optionally binds or connects it, depending on
599 * the value of \a flags parameter.
600 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200601int osmo_sock_init(uint16_t family, uint16_t type, uint8_t proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200602 const char *host, uint16_t port, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200603{
Harald Weltedda70fc2017-04-08 20:52:33 +0200604 struct addrinfo *result, *rp;
Harald Welte68b15742011-05-22 21:47:29 +0200605 int sfd, rc, on = 1;
Harald Welte33cb71a2011-05-21 18:54:32 +0200606
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200607 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200608 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100609 LOGP(DLGLOBAL, LOGL_ERROR, "invalid: both bind and connect flags set:"
Neels Hofmeyrb7f191f2016-08-29 11:22:03 +0200610 " %s:%u\n", host, port);
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200611 return -EINVAL;
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200612 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200613
Harald Weltedda70fc2017-04-08 20:52:33 +0200614 result = addrinfo_helper(family, type, proto, host, port, flags & OSMO_SOCK_F_BIND);
615 if (!result) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100616 LOGP(DLGLOBAL, LOGL_ERROR, "getaddrinfo returned NULL: %s:%u: %s\n",
Neels Hofmeyrf0f07d92016-08-22 13:34:23 +0200617 host, port, strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200618 return -EINVAL;
619 }
620
621 for (rp = result; rp != NULL; rp = rp->ai_next) {
Harald Weltedda70fc2017-04-08 20:52:33 +0200622 sfd = socket_helper(rp, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200623 if (sfd == -1)
624 continue;
Harald Weltedda70fc2017-04-08 20:52:33 +0200625
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200626 if (flags & OSMO_SOCK_F_CONNECT) {
627 rc = connect(sfd, rp->ai_addr, rp->ai_addrlen);
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200628 if (rc != 0 && errno != EINPROGRESS) {
629 close(sfd);
630 continue;
631 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200632 } else {
Philipp Maier73196e72018-08-23 20:11:50 +0200633 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200634 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,
635 &on, sizeof(on));
636 if (rc < 0) {
637 LOGP(DLGLOBAL, LOGL_ERROR,
638 "cannot setsockopt socket:"
639 " %s:%u: %s\n",
640 host, port, strerror(errno));
641 close(sfd);
642 continue;
643 }
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200644 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200645 if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == -1) {
646 LOGP(DLGLOBAL, LOGL_ERROR, "unable to bind socket:"
647 "%s:%u: %s\n",
648 host, port, strerror(errno));
649 close(sfd);
650 continue;
651 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200652 }
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200653 break;
Harald Welte33cb71a2011-05-21 18:54:32 +0200654 }
655 freeaddrinfo(result);
656
657 if (rp == NULL) {
Pau Espin Pedrol3a321472018-04-05 17:49:40 +0200658 LOGP(DLGLOBAL, LOGL_ERROR, "no suitable addr found for: %s:%u\n",
659 host, port);
Harald Welte33cb71a2011-05-21 18:54:32 +0200660 return -ENODEV;
661 }
Harald Welte68b15742011-05-22 21:47:29 +0200662
Philipp Maier73196e72018-08-23 20:11:50 +0200663 if (proto != IPPROTO_UDP || flags & OSMO_SOCK_F_UDP_REUSEADDR) {
Philipp Maier99f706d2018-08-01 12:40:36 +0200664 rc = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
665 if (rc < 0) {
666 LOGP(DLGLOBAL, LOGL_ERROR,
667 "cannot setsockopt socket: %s:%u: %s\n", host,
668 port, strerror(errno));
669 close(sfd);
670 sfd = -1;
671 }
Philipp Maier0659c5d2018-08-01 12:43:08 +0200672 }
Harald Welte68b15742011-05-22 21:47:29 +0200673
Harald Weltec47bbda2017-07-13 16:13:26 +0200674 rc = osmo_sock_init_tail(sfd, type, flags);
675 if (rc < 0) {
676 close(sfd);
677 sfd = -1;
Harald Welte68b15742011-05-22 21:47:29 +0200678 }
Harald Weltec47bbda2017-07-13 16:13:26 +0200679
Harald Welte68b15742011-05-22 21:47:29 +0200680 return sfd;
681}
682
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200683/*! fill \ref osmo_fd for a give sfd
Max862ba652014-10-13 14:54:25 +0200684 * \param[out] ofd file descriptor (will be filled in)
685 * \param[in] sfd socket file descriptor
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200686 * \returns socket fd on success; negative on error
Max862ba652014-10-13 14:54:25 +0200687 *
688 * This function fills the \a ofd structure.
689 */
690static inline int osmo_fd_init_ofd(struct osmo_fd *ofd, int sfd)
691{
692 int rc;
693
694 if (sfd < 0)
695 return sfd;
696
697 ofd->fd = sfd;
Harald Welte16886992019-03-20 10:26:39 +0100698 ofd->when = OSMO_FD_READ;
Max862ba652014-10-13 14:54:25 +0200699
700 rc = osmo_fd_register(ofd);
701 if (rc < 0) {
702 close(sfd);
703 return rc;
704 }
705
706 return sfd;
707}
708
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200709/*! Initialize a socket and fill \ref osmo_fd
Katerina Barone-Adesic28c6a02013-02-15 13:27:59 +0100710 * \param[out] ofd file descriptor (will be filled in)
Harald Welteba6988b2011-08-17 12:46:48 +0200711 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
712 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
713 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
714 * \param[in] host remote host name or IP address in string form
715 * \param[in] port remote port number in host byte order
716 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200717 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200718 *
719 * This function creates (and optionall binds/connects) a socket using
720 * \ref osmo_sock_init, but also fills the \a ofd structure.
721 */
Harald Welte68b15742011-05-22 21:47:29 +0200722int osmo_sock_init_ofd(struct osmo_fd *ofd, int family, int type, int proto,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200723 const char *host, uint16_t port, unsigned int flags)
Harald Welte68b15742011-05-22 21:47:29 +0200724{
Max862ba652014-10-13 14:54:25 +0200725 return osmo_fd_init_ofd(ofd, osmo_sock_init(family, type, proto, host, port, flags));
Harald Welte33cb71a2011-05-21 18:54:32 +0200726}
727
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200728/*! Initialize a socket and fill \ref osmo_fd
Pau Espin Pedrol75989e62017-05-26 12:39:53 +0200729 * \param[out] ofd file descriptor (will be filled in)
730 * \param[in] family Address Family like AF_INET, AF_INET6, AF_UNSPEC
731 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
732 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
733 * \param[in] local_host local host name or IP address in string form
734 * \param[in] local_port local port number in host byte order
735 * \param[in] remote_host remote host name or IP address in string form
736 * \param[in] remote_port remote port number in host byte order
737 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
738 * \returns socket fd on success; negative on error
739 *
740 * This function creates (and optionall binds/connects) a socket using
741 * \ref osmo_sock_init2, but also fills the \a ofd structure.
742 */
743int osmo_sock_init2_ofd(struct osmo_fd *ofd, int family, int type, int proto,
744 const char *local_host, uint16_t local_port,
745 const char *remote_host, uint16_t remote_port, unsigned int flags)
746{
747 return osmo_fd_init_ofd(ofd, osmo_sock_init2(family, type, proto, local_host,
748 local_port, remote_host, remote_port, flags));
749}
750
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200751/*! Initialize a socket and fill \ref sockaddr
Harald Welteba6988b2011-08-17 12:46:48 +0200752 * \param[out] ss socket address (will be filled in)
753 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
754 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
755 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200756 * \returns socket fd on success; negative on error
Harald Welteba6988b2011-08-17 12:46:48 +0200757 *
758 * This function creates (and optionall binds/connects) a socket using
759 * \ref osmo_sock_init, but also fills the \a ss structure.
760 */
Harald Welte33cb71a2011-05-21 18:54:32 +0200761int osmo_sock_init_sa(struct sockaddr *ss, uint16_t type,
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200762 uint8_t proto, unsigned int flags)
Harald Welte33cb71a2011-05-21 18:54:32 +0200763{
764 char host[NI_MAXHOST];
765 uint16_t port;
766 struct sockaddr_in *sin;
767 struct sockaddr_in6 *sin6;
768 int s, sa_len;
769
770 /* determine port and host from ss */
771 switch (ss->sa_family) {
772 case AF_INET:
773 sin = (struct sockaddr_in *) ss;
774 sa_len = sizeof(struct sockaddr_in);
775 port = ntohs(sin->sin_port);
776 break;
777 case AF_INET6:
778 sin6 = (struct sockaddr_in6 *) ss;
779 sa_len = sizeof(struct sockaddr_in6);
780 port = ntohs(sin6->sin6_port);
781 break;
782 default:
783 return -EINVAL;
784 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200785
786 s = getnameinfo(ss, sa_len, host, NI_MAXHOST,
787 NULL, 0, NI_NUMERICHOST);
788 if (s != 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100789 LOGP(DLGLOBAL, LOGL_ERROR, "getnameinfo failed:"
790 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200791 return s;
792 }
793
Pablo Neira Ayuso0849c9a2011-06-09 15:04:30 +0200794 return osmo_sock_init(ss->sa_family, type, proto, host, port, flags);
Harald Welte33cb71a2011-05-21 18:54:32 +0200795}
796
797static int sockaddr_equal(const struct sockaddr *a,
Harald Weltee4764422011-05-22 12:25:57 +0200798 const struct sockaddr *b, unsigned int len)
Harald Welte33cb71a2011-05-21 18:54:32 +0200799{
800 struct sockaddr_in *sin_a, *sin_b;
801 struct sockaddr_in6 *sin6_a, *sin6_b;
802
803 if (a->sa_family != b->sa_family)
804 return 0;
805
806 switch (a->sa_family) {
807 case AF_INET:
808 sin_a = (struct sockaddr_in *)a;
809 sin_b = (struct sockaddr_in *)b;
810 if (!memcmp(&sin_a->sin_addr, &sin_b->sin_addr,
811 sizeof(struct in_addr)))
812 return 1;
813 break;
814 case AF_INET6:
815 sin6_a = (struct sockaddr_in6 *)a;
816 sin6_b = (struct sockaddr_in6 *)b;
817 if (!memcmp(&sin6_a->sin6_addr, &sin6_b->sin6_addr,
818 sizeof(struct in6_addr)))
819 return 1;
820 break;
821 }
822 return 0;
823}
824
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200825/*! Determine if the given address is a local address
Harald Welteba6988b2011-08-17 12:46:48 +0200826 * \param[in] addr Socket Address
827 * \param[in] addrlen Length of socket address in bytes
828 * \returns 1 if address is local, 0 otherwise.
829 */
Harald Weltebc32d052012-04-08 11:31:32 +0200830int osmo_sockaddr_is_local(struct sockaddr *addr, unsigned int addrlen)
Harald Welte33cb71a2011-05-21 18:54:32 +0200831{
832 struct ifaddrs *ifaddr, *ifa;
833
834 if (getifaddrs(&ifaddr) == -1) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100835 LOGP(DLGLOBAL, LOGL_ERROR, "getifaddrs:"
836 " %s\n", strerror(errno));
Harald Welte33cb71a2011-05-21 18:54:32 +0200837 return -EIO;
838 }
839
840 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
Harald Welte4d3a7b12011-05-24 21:31:53 +0200841 if (!ifa->ifa_addr)
842 continue;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200843 if (sockaddr_equal(ifa->ifa_addr, addr, addrlen)) {
844 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +0200845 return 1;
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200846 }
Harald Welte33cb71a2011-05-21 18:54:32 +0200847 }
848
Pau Espin Pedrol15753e92018-04-18 19:57:41 +0200849 freeifaddrs(ifaddr);
Harald Welte33cb71a2011-05-21 18:54:32 +0200850 return 0;
851}
Harald Weltee4764422011-05-22 12:25:57 +0200852
Max9d7a2472018-11-20 15:18:31 +0100853/*! Convert sockaddr_in to IP address as char string and port as uint16_t.
854 * \param[out] addr String buffer to write IP address to, or NULL.
855 * \param[out] addr_len Size of \a addr.
856 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
857 * \param[in] sin Sockaddr to convert.
858 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
859 */
860size_t osmo_sockaddr_in_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
861 const struct sockaddr_in *sin)
862{
863 if (port)
864 *port = ntohs(sin->sin_port);
865
866 if (addr)
867 return osmo_strlcpy(addr, inet_ntoa(sin->sin_addr), addr_len);
868
869 return 0;
870}
871
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +0200872/*! Convert sockaddr to IP address as char string and port as uint16_t.
873 * \param[out] addr String buffer to write IP address to, or NULL.
874 * \param[out] addr_len Size of \a addr.
875 * \param[out] port Pointer to uint16_t to write the port number to, or NULL.
876 * \param[in] sa Sockaddr to convert.
877 * \returns the required string buffer size, like osmo_strlcpy(), or 0 if \a addr is NULL.
878 */
879unsigned int osmo_sockaddr_to_str_and_uint(char *addr, unsigned int addr_len, uint16_t *port,
880 const struct sockaddr *sa)
881{
882 const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
883
Max9d7a2472018-11-20 15:18:31 +0100884 return osmo_sockaddr_in_to_str_and_uint(addr, addr_len, port, sin);
Neels Hofmeyr59f4caf2018-07-19 22:13:19 +0200885}
886
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200887/*! Initialize a unix domain socket (including bind/connect)
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100888 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
889 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
890 * \param[in] socket_path path to identify the socket
891 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200892 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100893 *
894 * This function creates a new unix domain socket, \a
895 * type and \a proto and optionally binds or connects it, depending on
896 * the value of \a flags parameter.
897 */
Eric Wildeb5769b2019-06-27 15:31:17 +0200898#if defined(__clang__) && defined(SUN_LEN)
899__attribute__((no_sanitize("undefined")))
900#endif
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100901int osmo_sock_unix_init(uint16_t type, uint8_t proto,
902 const char *socket_path, unsigned int flags)
903{
904 struct sockaddr_un local;
905 int sfd, rc, on = 1;
906 unsigned int namelen;
907
908 if ((flags & (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT)) ==
909 (OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT))
910 return -EINVAL;
911
912 local.sun_family = AF_UNIX;
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200913 /* When an AF_UNIX socket is bound, sun_path should be NUL-terminated. See unix(7) man page. */
914 if (osmo_strlcpy(local.sun_path, socket_path, sizeof(local.sun_path)) >= sizeof(local.sun_path)) {
Stefan Sperling896ff6d2018-08-28 14:34:17 +0200915 LOGP(DLGLOBAL, LOGL_ERROR, "Socket path exceeds maximum length of %zd bytes: %s\n",
916 sizeof(local.sun_path), socket_path);
917 return -ENOSPC;
918 }
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100919
920#if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200921 local.sun_len = strlen(local.sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100922#endif
923#if defined(BSD44SOCKETS) || defined(SUN_LEN)
924 namelen = SUN_LEN(&local);
925#else
Stefan Sperling6afb3f52018-09-20 17:21:05 +0200926 namelen = strlen(local.sun_path) +
927 offsetof(struct sockaddr_un, sun_path);
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100928#endif
929
930 sfd = socket(AF_UNIX, type, proto);
931 if (sfd < 0)
932 return -1;
933
934 if (flags & OSMO_SOCK_F_CONNECT) {
935 rc = connect(sfd, (struct sockaddr *)&local, namelen);
936 if (rc < 0)
937 goto err;
938 } else {
939 unlink(local.sun_path);
940 rc = bind(sfd, (struct sockaddr *)&local, namelen);
941 if (rc < 0)
942 goto err;
943 }
944
945 if (flags & OSMO_SOCK_F_NONBLOCK) {
946 if (ioctl(sfd, FIONBIO, (unsigned char *)&on) < 0) {
Philipp Maier6f0f5602017-02-09 14:09:06 +0100947 LOGP(DLGLOBAL, LOGL_ERROR,
948 "cannot set this socket unblocking: %s\n",
949 strerror(errno));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100950 close(sfd);
951 return -EINVAL;
952 }
953 }
954
Harald Weltec47bbda2017-07-13 16:13:26 +0200955 rc = osmo_sock_init_tail(sfd, type, flags);
956 if (rc < 0) {
957 close(sfd);
958 sfd = -1;
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100959 }
960
961 return sfd;
962err:
963 close(sfd);
964 return -1;
965}
966
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200967/*! Initialize a unix domain socket and fill \ref osmo_fd
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100968 * \param[out] ofd file descriptor (will be filled in)
969 * \param[in] type Socket type like SOCK_DGRAM, SOCK_STREAM
970 * \param[in] proto Protocol like IPPROTO_TCP, IPPROTO_UDP
971 * \param[in] socket_path path to identify the socket
972 * \param[in] flags flags like \ref OSMO_SOCK_F_CONNECT
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200973 * \returns socket fd on success; negative on error
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100974 *
Vadim Yanitskiyb606d762019-06-01 19:02:47 +0700975 * This function creates (and optionally binds/connects) a socket
976 * using osmo_sock_unix_init, but also fills the ofd structure.
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100977 */
978int osmo_sock_unix_init_ofd(struct osmo_fd *ofd, uint16_t type, uint8_t proto,
979 const char *socket_path, unsigned int flags)
980{
Max862ba652014-10-13 14:54:25 +0200981 return osmo_fd_init_ofd(ofd, osmo_sock_unix_init(type, proto, socket_path, flags));
Álvaro Neira Ayuso5ade61a2014-03-24 13:02:00 +0100982}
983
Neels Hofmeyr01457512018-12-12 01:48:54 +0100984/*! Get the IP and/or port number on socket in separate string buffers.
Oliver Smith7acd5d02018-10-25 11:16:36 +0200985 * \param[in] fd file descriptor of socket
986 * \param[out] ip IP address (will be filled in when not NULL)
987 * \param[in] ip_len length of the ip buffer
988 * \param[out] port number (will be filled in when not NULL)
989 * \param[in] port_len length of the port buffer
990 * \param[in] local (true) or remote (false) name will get looked at
991 * \returns 0 on success; negative otherwise
992 */
Neels Hofmeyr01457512018-12-12 01:48:54 +0100993int 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 +0200994{
995 struct sockaddr sa;
996 socklen_t len = sizeof(sa);
Oliver Smith860651e2018-10-30 14:31:57 +0100997 char ipbuf[INET6_ADDRSTRLEN], portbuf[6];
Oliver Smith7acd5d02018-10-25 11:16:36 +0200998 int rc;
999
1000 rc = local ? getsockname(fd, &sa, &len) : getpeername(fd, &sa, &len);
1001 if (rc < 0)
1002 return rc;
1003
1004 rc = getnameinfo(&sa, len, ipbuf, sizeof(ipbuf),
1005 portbuf, sizeof(portbuf),
1006 NI_NUMERICHOST | NI_NUMERICSERV);
1007 if (rc < 0)
1008 return rc;
1009
1010 if (ip)
1011 strncpy(ip, ipbuf, ip_len);
1012 if (port)
1013 strncpy(port, portbuf, port_len);
1014 return 0;
1015}
1016
1017/*! Get local IP address on socket
1018 * \param[in] fd file descriptor of socket
1019 * \param[out] ip IP address (will be filled in)
1020 * \param[in] len length of the output buffer
1021 * \returns 0 on success; negative otherwise
1022 */
1023int osmo_sock_get_local_ip(int fd, char *ip, size_t len)
1024{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001025 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001026}
1027
1028/*! Get local port on socket
1029 * \param[in] fd file descriptor of socket
1030 * \param[out] port number (will be filled in)
1031 * \param[in] len length of the output buffer
1032 * \returns 0 on success; negative otherwise
1033 */
1034int osmo_sock_get_local_ip_port(int fd, char *port, size_t len)
1035{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001036 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, true);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001037}
1038
1039/*! Get remote IP address on socket
1040 * \param[in] fd file descriptor of socket
1041 * \param[out] ip IP address (will be filled in)
1042 * \param[in] len length of the output buffer
1043 * \returns 0 on success; negative otherwise
1044 */
1045int osmo_sock_get_remote_ip(int fd, char *ip, size_t len)
1046{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001047 return osmo_sock_get_ip_and_port(fd, ip, len, NULL, 0, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001048}
1049
1050/*! Get remote port on socket
1051 * \param[in] fd file descriptor of socket
1052 * \param[out] port number (will be filled in)
1053 * \param[in] len length of the output buffer
1054 * \returns 0 on success; negative otherwise
1055 */
1056int osmo_sock_get_remote_ip_port(int fd, char *port, size_t len)
1057{
Neels Hofmeyr01457512018-12-12 01:48:54 +01001058 return osmo_sock_get_ip_and_port(fd, NULL, 0, port, len, false);
Oliver Smith7acd5d02018-10-25 11:16:36 +02001059}
1060
Neels Hofmeyr01457512018-12-12 01:48:54 +01001061/*! Get address/port information on socket in dyn-alloc string like "(r=1.2.3.4:5<->l=6.7.8.9:10)".
1062 * Usually, it is better to use osmo_sock_get_name2() for a static string buffer or osmo_sock_get_name_buf() for a
1063 * caller provided string buffer, to avoid the dynamic talloc allocation.
Harald Welte48f55832017-01-26 00:03:10 +01001064 * \param[in] ctx talloc context from which to allocate string buffer
1065 * \param[in] fd file descriptor of socket
Neels Hofmeyr01457512018-12-12 01:48:54 +01001066 * \returns string identifying the connection of this socket, talloc'd from ctx.
Harald Welte48f55832017-01-26 00:03:10 +01001067 */
Harald Weltec0dfc9d2019-03-18 18:29:43 +01001068char *osmo_sock_get_name(const void *ctx, int fd)
Harald Welte48f55832017-01-26 00:03:10 +01001069{
Philipp Maier64b51eb2019-01-14 11:59:11 +01001070 char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001071 int rc;
1072 rc = osmo_sock_get_name_buf(str, sizeof(str), fd);
1073 if (rc <= 0)
1074 return NULL;
1075 return talloc_asprintf(ctx, "(%s)", str);
1076}
1077
1078/*! Get address/port information on socket in provided string buffer, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1079 * This does not include braces like osmo_sock_get_name().
1080 * \param[out] str Destination string buffer.
1081 * \param[in] str_len sizeof(str).
1082 * \param[in] fd File descriptor of socket.
1083 * \return String length as returned by snprintf(), or negative on error.
1084 */
1085int osmo_sock_get_name_buf(char *str, size_t str_len, int fd)
1086{
Oliver Smith860651e2018-10-30 14:31:57 +01001087 char hostbuf_l[INET6_ADDRSTRLEN], hostbuf_r[INET6_ADDRSTRLEN];
1088 char portbuf_l[6], portbuf_r[6];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001089 int rc;
Harald Welte48f55832017-01-26 00:03:10 +01001090
Oliver Smith7acd5d02018-10-25 11:16:36 +02001091 /* get local */
Harald Welteea9ea522019-05-10 09:28:24 +02001092 if ((rc = osmo_sock_get_ip_and_port(fd, hostbuf_l, sizeof(hostbuf_l), portbuf_l, sizeof(portbuf_l), true))) {
1093 osmo_strlcpy(str, "<error-in-getsockname>", str_len);
Neels Hofmeyr01457512018-12-12 01:48:54 +01001094 return rc;
Harald Welteea9ea522019-05-10 09:28:24 +02001095 }
Harald Welte48f55832017-01-26 00:03:10 +01001096
Oliver Smith7acd5d02018-10-25 11:16:36 +02001097 /* get remote */
Neels Hofmeyr01457512018-12-12 01:48:54 +01001098 if (osmo_sock_get_ip_and_port(fd, hostbuf_r, sizeof(hostbuf_r), portbuf_r, sizeof(portbuf_r), false) != 0)
1099 return snprintf(str, str_len, "r=NULL<->l=%s:%s", hostbuf_l, portbuf_l);
Harald Welte48f55832017-01-26 00:03:10 +01001100
Neels Hofmeyr01457512018-12-12 01:48:54 +01001101 return snprintf(str, str_len, "r=%s:%s<->l=%s:%s", hostbuf_r, portbuf_r, hostbuf_l, portbuf_l);
1102}
1103
1104/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1105 * This does not include braces like osmo_sock_get_name().
1106 * \param[in] fd File descriptor of socket.
1107 * \return Static string buffer containing the result.
1108 */
1109const char *osmo_sock_get_name2(int fd)
1110{
Harald Welte171ef822019-03-28 10:49:05 +01001111 static __thread char str[OSMO_SOCK_NAME_MAXLEN];
Neels Hofmeyr01457512018-12-12 01:48:54 +01001112 osmo_sock_get_name_buf(str, sizeof(str), fd);
1113 return str;
Harald Welte48f55832017-01-26 00:03:10 +01001114}
1115
Harald Welte179f3572019-03-18 18:38:47 +01001116/*! Get address/port information on socket in static string, like "r=1.2.3.4:5<->l=6.7.8.9:10".
1117 * This does not include braces like osmo_sock_get_name().
1118 * \param[in] fd File descriptor of socket.
1119 * \return Static string buffer containing the result.
1120 */
1121char *osmo_sock_get_name2_c(const void *ctx, int fd)
1122{
1123 char *str = talloc_size(ctx, OSMO_SOCK_NAME_MAXLEN);
1124 if (!str)
1125 return NULL;
Vadim Yanitskiy4f619c22019-04-12 21:48:07 +07001126 osmo_sock_get_name_buf(str, OSMO_SOCK_NAME_MAXLEN, fd);
Harald Welte179f3572019-03-18 18:38:47 +01001127 return str;
1128}
1129
Harald Weltee30d7e62017-07-13 16:02:50 +02001130static int sock_get_domain(int fd)
1131{
1132 int domain;
1133#ifdef SO_DOMAIN
1134 socklen_t dom_len = sizeof(domain);
1135 int rc;
1136
1137 rc = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &dom_len);
1138 if (rc < 0)
1139 return rc;
1140#else
1141 /* This of course sucks, but what shall we do on OSs like
1142 * FreeBSD that don't seem to expose a method by which one can
1143 * learn the address family of a socket? */
1144 domain = AF_INET;
1145#endif
1146 return domain;
1147}
1148
1149
1150/*! Activate or de-activate local loop-back of transmitted multicast packets
1151 * \param[in] fd file descriptor of related socket
1152 * \param[in] enable Enable (true) or disable (false) loop-back
1153 * \returns 0 on success; negative otherwise */
1154int osmo_sock_mcast_loop_set(int fd, bool enable)
1155{
1156 int domain, loop = 0;
1157
1158 if (enable)
1159 loop = 1;
1160
1161 domain = sock_get_domain(fd);
1162 if (domain < 0)
1163 return domain;
1164
1165 switch (domain) {
1166 case AF_INET:
1167 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1168 case AF_INET6:
1169 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop));
1170 default:
1171 return -EINVAL;
1172 }
1173}
1174
1175/*! Set the TTL of outbound multicast packets
1176 * \param[in] fd file descriptor of related socket
1177 * \param[in] ttl TTL of to-be-sent multicast packets
1178 * \returns 0 on success; negative otherwise */
1179int osmo_sock_mcast_ttl_set(int fd, uint8_t ttl)
1180{
1181 int domain, ttli = ttl;
1182
1183 domain = sock_get_domain(fd);
1184 if (domain < 0)
1185 return domain;
1186
1187 switch (domain) {
1188 case AF_INET:
1189 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttli, sizeof(ttli));
1190 case AF_INET6:
1191 return setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttli, sizeof(ttli));
1192 default:
1193 return -EINVAL;
1194 }
1195}
1196
1197/*! Enable/disable receiving all multicast packets, even for non-subscribed groups
1198 * \param[in] fd file descriptor of related socket
1199 * \param[in] enable Enable or Disable receiving of all packets
1200 * \returns 0 on success; negative otherwise */
1201int osmo_sock_mcast_all_set(int fd, bool enable)
1202{
1203 int domain, all = 0;
1204
1205 if (enable)
1206 all = 1;
1207
1208 domain = sock_get_domain(fd);
1209 if (domain < 0)
1210 return domain;
1211
1212 switch (domain) {
1213 case AF_INET:
1214#ifdef IP_MULTICAST_ALL
1215 return setsockopt(fd, IPPROTO_IP, IP_MULTICAST_ALL, &all, sizeof(all));
1216#endif
1217 case AF_INET6:
1218 /* there seems no equivalent ?!? */
1219 default:
1220 return -EINVAL;
1221 }
1222}
1223
1224/* FreeBSD calls the socket option differently */
1225#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
1226#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
1227#endif
1228
1229/*! Subscribe to the given IP multicast group
1230 * \param[in] fd file descriptor of related scoket
1231 * \param[in] grp_addr ASCII representation of the multicast group address
1232 * \returns 0 on success; negative otherwise */
1233int osmo_sock_mcast_subscribe(int fd, const char *grp_addr)
1234{
1235 int rc, domain;
1236 struct ip_mreq mreq;
1237 struct ipv6_mreq mreq6;
1238 struct in6_addr i6a;
1239
1240 domain = sock_get_domain(fd);
1241 if (domain < 0)
1242 return domain;
1243
1244 switch (domain) {
1245 case AF_INET:
1246 memset(&mreq, 0, sizeof(mreq));
1247 mreq.imr_multiaddr.s_addr = inet_addr(grp_addr);
1248 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1249 return setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
1250#ifdef IPV6_ADD_MEMBERSHIP
1251 case AF_INET6:
1252 memset(&mreq6, 0, sizeof(mreq6));
1253 rc = inet_pton(AF_INET6, grp_addr, (void *)&i6a);
1254 if (rc < 0)
1255 return -EINVAL;
1256 mreq6.ipv6mr_multiaddr = i6a;
1257 return setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6));
1258#endif
1259 default:
1260 return -EINVAL;
1261 }
1262}
1263
Philipp Maier2d2490e2017-10-20 19:41:26 +02001264/*! Determine the matching local IP-address for a given remote IP-Address.
1265 * \param[out] local_ip caller provided memory for resulting local IP-address
1266 * \param[in] remote_ip remote IP-address
1267 * \param[in] fd file descriptor of related scoket
1268 * \returns 0 on success; negative otherwise
1269 *
1270 * The function accepts IPv4 and IPv6 address strings. The caller must provide
1271 * at least INET6_ADDRSTRLEN bytes for local_ip if an IPv6 is expected as
1272 * as result. For IPv4 addresses the required amount is INET_ADDRSTRLEN. */
1273int osmo_sock_local_ip(char *local_ip, const char *remote_ip)
1274{
1275 int sfd;
1276 int rc;
1277 struct addrinfo addrinfo_hint;
1278 struct addrinfo *addrinfo = NULL;
1279 struct sockaddr_in local_addr;
1280 socklen_t local_addr_len;
1281 uint16_t family;
1282
1283 /* Find out the address family (AF_INET or AF_INET6?) */
1284 memset(&addrinfo_hint, '\0', sizeof(addrinfo_hint));
1285 addrinfo_hint.ai_family = PF_UNSPEC;
1286 addrinfo_hint.ai_flags = AI_NUMERICHOST;
1287 rc = getaddrinfo(remote_ip, NULL, &addrinfo_hint, &addrinfo);
1288 if (rc)
1289 return -EINVAL;
1290 family = addrinfo->ai_family;
1291 freeaddrinfo(addrinfo);
1292
1293 /* Connect a dummy socket to trick the kernel into determining the
1294 * ip-address of the interface that would be used if we would send
1295 * out an actual packet */
1296 sfd = osmo_sock_init2(family, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, remote_ip, 0, OSMO_SOCK_F_CONNECT);
1297 if (sfd < 0)
1298 return -EINVAL;
1299
1300 /* Request the IP address of the interface that the kernel has
1301 * actually choosen. */
1302 memset(&local_addr, 0, sizeof(local_addr));
1303 local_addr_len = sizeof(local_addr);
1304 rc = getsockname(sfd, (struct sockaddr *)&local_addr, &local_addr_len);
Philipp Maier8b7975b2018-01-22 15:38:07 +01001305 close(sfd);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001306 if (rc < 0)
1307 return -EINVAL;
1308 if (local_addr.sin_family == AF_INET)
Philipp Maier91cfda82018-01-22 16:56:27 +01001309 inet_ntop(AF_INET, &local_addr.sin_addr, local_ip, INET_ADDRSTRLEN);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001310 else if (local_addr.sin_family == AF_INET6)
Philipp Maier91cfda82018-01-22 16:56:27 +01001311 inet_ntop(AF_INET6, &local_addr.sin_addr, local_ip, INET6_ADDRSTRLEN);
Philipp Maier2d2490e2017-10-20 19:41:26 +02001312 else
1313 return -EINVAL;
1314
1315 return 0;
1316}
1317
Harald Weltee4764422011-05-22 12:25:57 +02001318#endif /* HAVE_SYS_SOCKET_H */
Harald Welteba6988b2011-08-17 12:46:48 +02001319
Sylvain Munautdca7d2c2012-04-18 21:53:23 +02001320/*! @} */