chiark / gitweb /
177f2aa4ff0a4e2cfc4ca59fde76f6627521c0e6
[elogind.git] / src / basic / socket-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <arpa/inet.h>
9 #include <errno.h>
10 #include <limits.h>
11 #include <net/if.h>
12 #include <netdb.h>
13 #include <netinet/ip.h>
14 #include <poll.h>
15 #include <stddef.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21
22 #include "alloc-util.h"
23 #include "fd-util.h"
24 #include "fileio.h"
25 #include "format-util.h"
26 #include "log.h"
27 #include "macro.h"
28 #include "missing.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "socket-util.h"
33 #include "string-table.h"
34 #include "string-util.h"
35 #include "strv.h"
36 #include "user-util.h"
37 //#include "utf8.h"
38 #include "util.h"
39
40 #if 0 /// UNNEEDED by elogind
41 #if ENABLE_IDN
42 #  define IDN_FLAGS NI_IDN
43 #else
44 #  define IDN_FLAGS 0
45 #endif
46
47 static const char* const socket_address_type_table[] = {
48         [SOCK_STREAM] = "Stream",
49         [SOCK_DGRAM] = "Datagram",
50         [SOCK_RAW] = "Raw",
51         [SOCK_RDM] = "ReliableDatagram",
52         [SOCK_SEQPACKET] = "SequentialPacket",
53         [SOCK_DCCP] = "DatagramCongestionControl",
54 };
55
56 DEFINE_STRING_TABLE_LOOKUP(socket_address_type, int);
57
58 int socket_address_parse(SocketAddress *a, const char *s) {
59         char *e, *n;
60         unsigned u;
61         int r;
62
63         assert(a);
64         assert(s);
65
66         zero(*a);
67         a->type = SOCK_STREAM;
68
69         if (*s == '[') {
70                 uint16_t port;
71
72                 /* IPv6 in [x:.....:z]:p notation */
73
74                 e = strchr(s+1, ']');
75                 if (!e)
76                         return -EINVAL;
77
78                 n = strndupa(s+1, e-s-1);
79
80                 errno = 0;
81                 if (inet_pton(AF_INET6, n, &a->sockaddr.in6.sin6_addr) <= 0)
82                         return errno > 0 ? -errno : -EINVAL;
83
84                 e++;
85                 if (*e != ':')
86                         return -EINVAL;
87
88                 e++;
89                 r = safe_atou(e, &u);
90                 r = parse_ip_port(e, &port);
91                 if (r < 0)
92                         return r;
93
94                 if (u <= 0 || u > 0xFFFF)
95                         return -EINVAL;
96
97                 a->sockaddr.in6.sin6_family = AF_INET6;
98                 a->sockaddr.in6.sin6_port = htobe16((uint16_t)u);
99                 a->sockaddr.in6.sin6_port = htobe16(port);
100                 a->size = sizeof(struct sockaddr_in6);
101
102         } else if (*s == '/') {
103                 /* AF_UNIX socket */
104
105                 size_t l;
106
107                 l = strlen(s);
108                 if (l >= sizeof(a->sockaddr.un.sun_path))
109                         return -EINVAL;
110
111                 a->sockaddr.un.sun_family = AF_UNIX;
112                 memcpy(a->sockaddr.un.sun_path, s, l);
113                 a->size = offsetof(struct sockaddr_un, sun_path) + l + 1;
114
115         } else if (*s == '@') {
116                 /* Abstract AF_UNIX socket */
117                 size_t l;
118
119                 l = strlen(s+1);
120                 if (l >= sizeof(a->sockaddr.un.sun_path) - 1)
121                         return -EINVAL;
122
123                 a->sockaddr.un.sun_family = AF_UNIX;
124                 memcpy(a->sockaddr.un.sun_path+1, s+1, l);
125                 a->size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
126
127         } else if (startswith(s, "vsock:")) {
128                 /* AF_VSOCK socket in vsock:cid:port notation */
129                 const char *cid_start = s + STRLEN("vsock:");
130                 unsigned port;
131
132                 e = strchr(cid_start, ':');
133                 if (!e)
134                         return -EINVAL;
135
136                 r = safe_atou(e+1, &u);
137                 r = safe_atou(e+1, &port);
138                 if (r < 0)
139                         return r;
140
141                 n = strndupa(cid_start, e - cid_start);
142                 if (!isempty(n)) {
143                         r = safe_atou(n, &a->sockaddr.vm.svm_cid);
144                         if (r < 0)
145                                 return r;
146                 } else
147                         a->sockaddr.vm.svm_cid = VMADDR_CID_ANY;
148
149                 a->sockaddr.vm.svm_family = AF_VSOCK;
150                 a->sockaddr.vm.svm_port = u;
151                 a->sockaddr.vm.svm_port = port;
152                 a->size = sizeof(struct sockaddr_vm);
153
154         } else {
155                 uint16_t port;
156
157                 e = strchr(s, ':');
158                 if (e) {
159                         r = safe_atou(e+1, &u);
160                         r = parse_ip_port(e + 1, &port);
161                         if (r < 0)
162                                 return r;
163
164                         if (u <= 0 || u > 0xFFFF)
165                                 return -EINVAL;
166
167                         n = strndupa(s, e-s);
168
169                         /* IPv4 in w.x.y.z:p notation? */
170                         r = inet_pton(AF_INET, n, &a->sockaddr.in.sin_addr);
171                         if (r < 0)
172                                 return -errno;
173
174                         if (r > 0) {
175                                 /* Gotcha, it's a traditional IPv4 address */
176                                 a->sockaddr.in.sin_family = AF_INET;
177                                 a->sockaddr.in.sin_port = htobe16((uint16_t)u);
178                                 a->sockaddr.in.sin_port = htobe16(port);
179                                 a->size = sizeof(struct sockaddr_in);
180                         } else {
181                                 unsigned idx;
182
183                                 if (strlen(n) > IF_NAMESIZE-1)
184                                         return -EINVAL;
185
186                                 /* Uh, our last resort, an interface name */
187                                 idx = if_nametoindex(n);
188                                 if (idx == 0)
189                                         return -EINVAL;
190
191                                 a->sockaddr.in6.sin6_family = AF_INET6;
192                                 a->sockaddr.in6.sin6_port = htobe16((uint16_t)u);
193                                 a->sockaddr.in6.sin6_port = htobe16(port);
194                                 a->sockaddr.in6.sin6_scope_id = idx;
195                                 a->sockaddr.in6.sin6_addr = in6addr_any;
196                                 a->size = sizeof(struct sockaddr_in6);
197                         }
198                 } else {
199
200                         /* Just a port */
201                         r = safe_atou(s, &u);
202                         r = parse_ip_port(s, &port);
203                         if (r < 0)
204                                 return r;
205
206                         if (u <= 0 || u > 0xFFFF)
207                                 return -EINVAL;
208
209                         if (socket_ipv6_is_supported()) {
210                                 a->sockaddr.in6.sin6_family = AF_INET6;
211                                 a->sockaddr.in6.sin6_port = htobe16((uint16_t)u);
212                                 a->sockaddr.in6.sin6_port = htobe16(port);
213                                 a->sockaddr.in6.sin6_addr = in6addr_any;
214                                 a->size = sizeof(struct sockaddr_in6);
215                         } else {
216                                 a->sockaddr.in.sin_family = AF_INET;
217                                 a->sockaddr.in.sin_port = htobe16((uint16_t)u);
218                                 a->sockaddr.in.sin_port = htobe16(port);
219                                 a->sockaddr.in.sin_addr.s_addr = INADDR_ANY;
220                                 a->size = sizeof(struct sockaddr_in);
221                         }
222                 }
223         }
224
225         return 0;
226 }
227
228 int socket_address_parse_and_warn(SocketAddress *a, const char *s) {
229         SocketAddress b;
230         int r;
231
232         /* Similar to socket_address_parse() but warns for IPv6 sockets when we don't support them. */
233
234         r = socket_address_parse(&b, s);
235         if (r < 0)
236                 return r;
237
238         if (!socket_ipv6_is_supported() && b.sockaddr.sa.sa_family == AF_INET6) {
239                 log_warning("Binding to IPv6 address not available since kernel does not support IPv6.");
240                 return -EAFNOSUPPORT;
241         }
242
243         *a = b;
244         return 0;
245 }
246
247 int socket_address_parse_netlink(SocketAddress *a, const char *s) {
248         int family;
249         unsigned group = 0;
250         _cleanup_free_ char *sfamily = NULL;
251         assert(a);
252         assert(s);
253
254         zero(*a);
255         a->type = SOCK_RAW;
256
257         errno = 0;
258         if (sscanf(s, "%ms %u", &sfamily, &group) < 1)
259                 return errno > 0 ? -errno : -EINVAL;
260
261         family = netlink_family_from_string(sfamily);
262         if (family < 0)
263                 return -EINVAL;
264
265         a->sockaddr.nl.nl_family = AF_NETLINK;
266         a->sockaddr.nl.nl_groups = group;
267
268         a->type = SOCK_RAW;
269         a->size = sizeof(struct sockaddr_nl);
270         a->protocol = family;
271
272         return 0;
273 }
274
275 int socket_address_verify(const SocketAddress *a) {
276         assert(a);
277
278         switch (socket_address_family(a)) {
279
280         case AF_INET:
281                 if (a->size != sizeof(struct sockaddr_in))
282                         return -EINVAL;
283
284                 if (a->sockaddr.in.sin_port == 0)
285                         return -EINVAL;
286
287                 if (!IN_SET(a->type, SOCK_STREAM, SOCK_DGRAM))
288                         return -EINVAL;
289
290                 return 0;
291
292         case AF_INET6:
293                 if (a->size != sizeof(struct sockaddr_in6))
294                         return -EINVAL;
295
296                 if (a->sockaddr.in6.sin6_port == 0)
297                         return -EINVAL;
298
299                 if (!IN_SET(a->type, SOCK_STREAM, SOCK_DGRAM))
300                         return -EINVAL;
301
302                 return 0;
303
304         case AF_UNIX:
305                 if (a->size < offsetof(struct sockaddr_un, sun_path))
306                         return -EINVAL;
307
308                 if (a->size > offsetof(struct sockaddr_un, sun_path)) {
309
310                         if (a->sockaddr.un.sun_path[0] != 0) {
311                                 char *e;
312
313                                 /* path */
314                                 e = memchr(a->sockaddr.un.sun_path, 0, sizeof(a->sockaddr.un.sun_path));
315                                 if (!e)
316                                         return -EINVAL;
317
318                                 if (a->size != offsetof(struct sockaddr_un, sun_path) + (e - a->sockaddr.un.sun_path) + 1)
319                                         return -EINVAL;
320                         }
321                 }
322
323                 if (!IN_SET(a->type, SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET))
324                         return -EINVAL;
325
326                 return 0;
327
328         case AF_NETLINK:
329
330                 if (a->size != sizeof(struct sockaddr_nl))
331                         return -EINVAL;
332
333                 if (!IN_SET(a->type, SOCK_RAW, SOCK_DGRAM))
334                         return -EINVAL;
335
336                 return 0;
337
338         case AF_VSOCK:
339                 if (a->size != sizeof(struct sockaddr_vm))
340                         return -EINVAL;
341
342                 if (!IN_SET(a->type, SOCK_STREAM, SOCK_DGRAM))
343                         return -EINVAL;
344
345                 return 0;
346
347         default:
348                 return -EAFNOSUPPORT;
349         }
350 }
351
352 int socket_address_print(const SocketAddress *a, char **ret) {
353         int r;
354
355         assert(a);
356         assert(ret);
357
358         r = socket_address_verify(a);
359         if (r < 0)
360                 return r;
361
362         if (socket_address_family(a) == AF_NETLINK) {
363                 _cleanup_free_ char *sfamily = NULL;
364
365                 r = netlink_family_to_string_alloc(a->protocol, &sfamily);
366                 if (r < 0)
367                         return r;
368
369                 r = asprintf(ret, "%s %u", sfamily, a->sockaddr.nl.nl_groups);
370                 if (r < 0)
371                         return -ENOMEM;
372
373                 return 0;
374         }
375
376         return sockaddr_pretty(&a->sockaddr.sa, a->size, false, true, ret);
377 }
378
379 bool socket_address_can_accept(const SocketAddress *a) {
380         assert(a);
381
382         return
383                 IN_SET(a->type, SOCK_STREAM, SOCK_SEQPACKET);
384 }
385
386 bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) {
387         assert(a);
388         assert(b);
389
390         /* Invalid addresses are unequal to all */
391         if (socket_address_verify(a) < 0 ||
392             socket_address_verify(b) < 0)
393                 return false;
394
395         if (a->type != b->type)
396                 return false;
397
398         if (socket_address_family(a) != socket_address_family(b))
399                 return false;
400
401         switch (socket_address_family(a)) {
402
403         case AF_INET:
404                 if (a->sockaddr.in.sin_addr.s_addr != b->sockaddr.in.sin_addr.s_addr)
405                         return false;
406
407                 if (a->sockaddr.in.sin_port != b->sockaddr.in.sin_port)
408                         return false;
409
410                 break;
411
412         case AF_INET6:
413                 if (memcmp(&a->sockaddr.in6.sin6_addr, &b->sockaddr.in6.sin6_addr, sizeof(a->sockaddr.in6.sin6_addr)) != 0)
414                         return false;
415
416                 if (a->sockaddr.in6.sin6_port != b->sockaddr.in6.sin6_port)
417                         return false;
418
419                 break;
420
421         case AF_UNIX:
422                 if (a->size <= offsetof(struct sockaddr_un, sun_path) ||
423                     b->size <= offsetof(struct sockaddr_un, sun_path))
424                         return false;
425
426                 if ((a->sockaddr.un.sun_path[0] == 0) != (b->sockaddr.un.sun_path[0] == 0))
427                         return false;
428
429                 if (a->sockaddr.un.sun_path[0]) {
430                         if (!path_equal_or_files_same(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, 0))
431                                 return false;
432                 } else {
433                         if (a->size != b->size)
434                                 return false;
435
436                         if (memcmp(a->sockaddr.un.sun_path, b->sockaddr.un.sun_path, a->size) != 0)
437                                 return false;
438                 }
439
440                 break;
441
442         case AF_NETLINK:
443                 if (a->protocol != b->protocol)
444                         return false;
445
446                 if (a->sockaddr.nl.nl_groups != b->sockaddr.nl.nl_groups)
447                         return false;
448
449                 break;
450
451         case AF_VSOCK:
452                 if (a->sockaddr.vm.svm_cid != b->sockaddr.vm.svm_cid)
453                         return false;
454
455                 if (a->sockaddr.vm.svm_port != b->sockaddr.vm.svm_port)
456                         return false;
457
458                 break;
459
460         default:
461                 /* Cannot compare, so we assume the addresses are different */
462                 return false;
463         }
464
465         return true;
466 }
467
468 bool socket_address_is(const SocketAddress *a, const char *s, int type) {
469         struct SocketAddress b;
470
471         assert(a);
472         assert(s);
473
474         if (socket_address_parse(&b, s) < 0)
475                 return false;
476
477         b.type = type;
478
479         return socket_address_equal(a, &b);
480 }
481
482 bool socket_address_is_netlink(const SocketAddress *a, const char *s) {
483         struct SocketAddress b;
484
485         assert(a);
486         assert(s);
487
488         if (socket_address_parse_netlink(&b, s) < 0)
489                 return false;
490
491         return socket_address_equal(a, &b);
492 }
493
494 const char* socket_address_get_path(const SocketAddress *a) {
495         assert(a);
496
497         if (socket_address_family(a) != AF_UNIX)
498                 return NULL;
499
500         if (a->sockaddr.un.sun_path[0] == 0)
501                 return NULL;
502
503         return a->sockaddr.un.sun_path;
504 }
505
506 bool socket_ipv6_is_supported(void) {
507         if (access("/proc/net/if_inet6", F_OK) != 0)
508                 return false;
509
510         return true;
511 }
512
513 bool socket_address_matches_fd(const SocketAddress *a, int fd) {
514         SocketAddress b;
515         socklen_t solen;
516
517         assert(a);
518         assert(fd >= 0);
519
520         b.size = sizeof(b.sockaddr);
521         if (getsockname(fd, &b.sockaddr.sa, &b.size) < 0)
522                 return false;
523
524         if (b.sockaddr.sa.sa_family != a->sockaddr.sa.sa_family)
525                 return false;
526
527         solen = sizeof(b.type);
528         if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &b.type, &solen) < 0)
529                 return false;
530
531         if (b.type != a->type)
532                 return false;
533
534         if (a->protocol != 0)  {
535                 solen = sizeof(b.protocol);
536                 if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &b.protocol, &solen) < 0)
537                         return false;
538
539                 if (b.protocol != a->protocol)
540                         return false;
541         }
542
543         return socket_address_equal(a, &b);
544 }
545 #endif // 0
546
547 int sockaddr_port(const struct sockaddr *_sa, unsigned *ret_port) {
548         union sockaddr_union *sa = (union sockaddr_union*) _sa;
549
550         /* Note, this returns the port as 'unsigned' rather than 'uint16_t', as AF_VSOCK knows larger ports */
551
552         assert(sa);
553
554         switch (sa->sa.sa_family) {
555
556         case AF_INET:
557                 *ret_port = be16toh(sa->in.sin_port);
558                 return 0;
559
560         case AF_INET6:
561                 *ret_port = be16toh(sa->in6.sin6_port);
562                 return 0;
563
564         case AF_VSOCK:
565                 *ret_port = sa->vm.svm_port;
566                 return 0;
567
568         default:
569                 return -EAFNOSUPPORT;
570         }
571 }
572
573 #if 0 /// UNNEEDED by elogind
574 int sockaddr_pretty(const struct sockaddr *_sa, socklen_t salen, bool translate_ipv6, bool include_port, char **ret) {
575         union sockaddr_union *sa = (union sockaddr_union*) _sa;
576         char *p;
577         int r;
578
579         assert(sa);
580         assert(salen >= sizeof(sa->sa.sa_family));
581
582         switch (sa->sa.sa_family) {
583
584         case AF_INET: {
585                 uint32_t a;
586
587                 a = be32toh(sa->in.sin_addr.s_addr);
588
589                 if (include_port)
590                         r = asprintf(&p,
591                                      "%u.%u.%u.%u:%u",
592                                      a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
593                                      be16toh(sa->in.sin_port));
594                 else
595                         r = asprintf(&p,
596                                      "%u.%u.%u.%u",
597                                      a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF);
598                 if (r < 0)
599                         return -ENOMEM;
600                 break;
601         }
602
603         case AF_INET6: {
604                 static const unsigned char ipv4_prefix[] = {
605                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
606                 };
607
608                 if (translate_ipv6 &&
609                     memcmp(&sa->in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
610                         const uint8_t *a = sa->in6.sin6_addr.s6_addr+12;
611                         if (include_port)
612                                 r = asprintf(&p,
613                                              "%u.%u.%u.%u:%u",
614                                              a[0], a[1], a[2], a[3],
615                                              be16toh(sa->in6.sin6_port));
616                         else
617                                 r = asprintf(&p,
618                                              "%u.%u.%u.%u",
619                                              a[0], a[1], a[2], a[3]);
620                         if (r < 0)
621                                 return -ENOMEM;
622                 } else {
623                         char a[INET6_ADDRSTRLEN];
624
625                         inet_ntop(AF_INET6, &sa->in6.sin6_addr, a, sizeof(a));
626
627                         if (include_port) {
628                                 r = asprintf(&p,
629                                              "[%s]:%u",
630                                              a,
631                                              be16toh(sa->in6.sin6_port));
632                                 if (r < 0)
633                                         return -ENOMEM;
634                         } else {
635                                 p = strdup(a);
636                                 if (!p)
637                                         return -ENOMEM;
638                         }
639                 }
640
641                 break;
642         }
643
644         case AF_UNIX:
645                 if (salen <= offsetof(struct sockaddr_un, sun_path)) {
646                         p = strdup("<unnamed>");
647                         if (!p)
648                                 return -ENOMEM;
649
650                 } else if (sa->un.sun_path[0] == 0) {
651                         /* abstract */
652
653                         /* FIXME: We assume we can print the
654                          * socket path here and that it hasn't
655                          * more than one NUL byte. That is
656                          * actually an invalid assumption */
657
658                         p = new(char, sizeof(sa->un.sun_path)+1);
659                         if (!p)
660                                 return -ENOMEM;
661
662                         p[0] = '@';
663                         memcpy(p+1, sa->un.sun_path+1, sizeof(sa->un.sun_path)-1);
664                         p[sizeof(sa->un.sun_path)] = 0;
665
666                 } else {
667                         p = strndup(sa->un.sun_path, sizeof(sa->un.sun_path));
668                         if (!p)
669                                 return -ENOMEM;
670                 }
671
672                 break;
673
674         case AF_VSOCK:
675                 if (include_port)
676                         r = asprintf(&p,
677                                      "vsock:%u:%u",
678                                      sa->vm.svm_cid,
679                                      sa->vm.svm_port);
680                 else
681                         r = asprintf(&p, "vsock:%u", sa->vm.svm_cid);
682                 if (r < 0)
683                         return -ENOMEM;
684                 break;
685
686         default:
687                 return -EOPNOTSUPP;
688         }
689
690         *ret = p;
691         return 0;
692 }
693
694 int getpeername_pretty(int fd, bool include_port, char **ret) {
695         union sockaddr_union sa;
696         socklen_t salen = sizeof(sa);
697         int r;
698
699         assert(fd >= 0);
700         assert(ret);
701
702         if (getpeername(fd, &sa.sa, &salen) < 0)
703                 return -errno;
704
705         if (sa.sa.sa_family == AF_UNIX) {
706                 struct ucred ucred = {};
707
708                 /* UNIX connection sockets are anonymous, so let's use
709                  * PID/UID as pretty credentials instead */
710
711                 r = getpeercred(fd, &ucred);
712                 if (r < 0)
713                         return r;
714
715                 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
716                         return -ENOMEM;
717
718                 return 0;
719         }
720
721         /* For remote sockets we translate IPv6 addresses back to IPv4
722          * if applicable, since that's nicer. */
723
724         return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
725 }
726
727 int getsockname_pretty(int fd, char **ret) {
728         union sockaddr_union sa;
729         socklen_t salen = sizeof(sa);
730
731         assert(fd >= 0);
732         assert(ret);
733
734         if (getsockname(fd, &sa.sa, &salen) < 0)
735                 return -errno;
736
737         /* For local sockets we do not translate IPv6 addresses back
738          * to IPv6 if applicable, since this is usually used for
739          * listening sockets where the difference between IPv4 and
740          * IPv6 matters. */
741
742         return sockaddr_pretty(&sa.sa, salen, false, true, ret);
743 }
744
745 int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret) {
746         int r;
747         char host[NI_MAXHOST], *ret;
748
749         assert(_ret);
750
751         r = getnameinfo(&sa->sa, salen, host, sizeof(host), NULL, 0, IDN_FLAGS);
752         if (r != 0) {
753                 int saved_errno = errno;
754
755                 r = sockaddr_pretty(&sa->sa, salen, true, true, &ret);
756                 if (r < 0)
757                         return r;
758
759                 log_debug_errno(saved_errno, "getnameinfo(%s) failed: %m", ret);
760         } else {
761                 ret = strdup(host);
762                 if (!ret)
763                         return -ENOMEM;
764         }
765
766         *_ret = ret;
767         return 0;
768 }
769
770 int socket_address_unlink(SocketAddress *a) {
771         assert(a);
772
773         if (socket_address_family(a) != AF_UNIX)
774                 return 0;
775
776         if (a->sockaddr.un.sun_path[0] == 0)
777                 return 0;
778
779         if (unlink(a->sockaddr.un.sun_path) < 0)
780                 return -errno;
781
782         return 1;
783 }
784
785 static const char* const netlink_family_table[] = {
786         [NETLINK_ROUTE] = "route",
787         [NETLINK_FIREWALL] = "firewall",
788         [NETLINK_INET_DIAG] = "inet-diag",
789         [NETLINK_NFLOG] = "nflog",
790         [NETLINK_XFRM] = "xfrm",
791         [NETLINK_SELINUX] = "selinux",
792         [NETLINK_ISCSI] = "iscsi",
793         [NETLINK_AUDIT] = "audit",
794         [NETLINK_FIB_LOOKUP] = "fib-lookup",
795         [NETLINK_CONNECTOR] = "connector",
796         [NETLINK_NETFILTER] = "netfilter",
797         [NETLINK_IP6_FW] = "ip6-fw",
798         [NETLINK_DNRTMSG] = "dnrtmsg",
799         [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
800         [NETLINK_GENERIC] = "generic",
801         [NETLINK_SCSITRANSPORT] = "scsitransport",
802         [NETLINK_ECRYPTFS] = "ecryptfs",
803         [NETLINK_RDMA] = "rdma",
804 };
805
806 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
807
808 static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
809         [SOCKET_ADDRESS_DEFAULT] = "default",
810         [SOCKET_ADDRESS_BOTH] = "both",
811         [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
812 };
813
814 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
815
816 SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *n) {
817         int r;
818
819         r = parse_boolean(n);
820         if (r > 0)
821                 return SOCKET_ADDRESS_IPV6_ONLY;
822         if (r == 0)
823                 return SOCKET_ADDRESS_BOTH;
824
825         return socket_address_bind_ipv6_only_from_string(n);
826 }
827
828 bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
829         assert(a);
830         assert(b);
831
832         if (a->sa.sa_family != b->sa.sa_family)
833                 return false;
834
835         if (a->sa.sa_family == AF_INET)
836                 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
837
838         if (a->sa.sa_family == AF_INET6)
839                 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
840
841         if (a->sa.sa_family == AF_VSOCK)
842                 return a->vm.svm_cid == b->vm.svm_cid;
843
844         return false;
845 }
846 #endif // 0
847
848 int fd_inc_sndbuf(int fd, size_t n) {
849         int r, value;
850         socklen_t l = sizeof(value);
851
852         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
853         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
854                 return 0;
855
856         /* If we have the privileges we will ignore the kernel limit. */
857
858         value = (int) n;
859         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
860                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
861                         return -errno;
862
863         return 1;
864 }
865
866 int fd_inc_rcvbuf(int fd, size_t n) {
867         int r, value;
868         socklen_t l = sizeof(value);
869
870         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
871         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
872                 return 0;
873
874         /* If we have the privileges we will ignore the kernel limit. */
875
876         value = (int) n;
877         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
878                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
879                         return -errno;
880         return 1;
881 }
882
883 #if 0 /// UNNEEDED by elogind
884 static const char* const ip_tos_table[] = {
885         [IPTOS_LOWDELAY] = "low-delay",
886         [IPTOS_THROUGHPUT] = "throughput",
887         [IPTOS_RELIABILITY] = "reliability",
888         [IPTOS_LOWCOST] = "low-cost",
889 };
890
891 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
892
893 bool ifname_valid(const char *p) {
894         bool numeric = true;
895
896         /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
897          * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
898          * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
899
900         if (isempty(p))
901                 return false;
902
903         if (strlen(p) >= IFNAMSIZ)
904                 return false;
905
906         if (dot_or_dot_dot(p))
907                 return false;
908
909         while (*p) {
910                 if ((unsigned char) *p >= 127U)
911                         return false;
912
913                 if ((unsigned char) *p <= 32U)
914                         return false;
915
916                 if (IN_SET(*p, ':', '/'))
917                         return false;
918
919                 numeric = numeric && (*p >= '0' && *p <= '9');
920                 p++;
921         }
922
923         if (numeric)
924                 return false;
925
926         return true;
927 }
928
929 bool address_label_valid(const char *p) {
930
931         if (isempty(p))
932                 return false;
933
934         if (strlen(p) >= IFNAMSIZ)
935                 return false;
936
937         while (*p) {
938                 if ((uint8_t) *p >= 127U)
939                         return false;
940
941                 if ((uint8_t) *p <= 31U)
942                         return false;
943                 p++;
944         }
945
946         return true;
947 }
948 #endif // 0
949
950 int getpeercred(int fd, struct ucred *ucred) {
951         socklen_t n = sizeof(struct ucred);
952         struct ucred u;
953         int r;
954
955         assert(fd >= 0);
956         assert(ucred);
957
958         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
959         if (r < 0)
960                 return -errno;
961
962         if (n != sizeof(struct ucred))
963                 return -EIO;
964
965         /* Check if the data is actually useful and not suppressed due to namespacing issues */
966         if (!pid_is_valid(u.pid))
967                 return -ENODATA;
968
969         /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
970          * receiving in "invalid" user/group we get the overflow UID/GID. */
971
972         *ucred = u;
973         return 0;
974 }
975
976 int getpeersec(int fd, char **ret) {
977         _cleanup_free_ char *s = NULL;
978         socklen_t n = 64;
979
980         assert(fd >= 0);
981         assert(ret);
982
983         for (;;) {
984                 s = new0(char, n+1);
985                 if (!s)
986                         return -ENOMEM;
987
988                 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0)
989                         break;
990
991                 if (errno != ERANGE)
992                         return -errno;
993
994                 s = mfree(s);
995         }
996
997         if (isempty(s))
998                 return -EOPNOTSUPP;
999
1000         *ret = TAKE_PTR(s);
1001
1002         return 0;
1003 }
1004
1005 int getpeergroups(int fd, gid_t **ret) {
1006         socklen_t n = sizeof(gid_t) * 64;
1007         _cleanup_free_ gid_t *d = NULL;
1008
1009         assert(fd >= 0);
1010         assert(ret);
1011
1012         for (;;) {
1013                 d = malloc(n);
1014                 if (!d)
1015                         return -ENOMEM;
1016
1017                 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
1018                         break;
1019
1020                 if (errno != ERANGE)
1021                         return -errno;
1022
1023                 d = mfree(d);
1024         }
1025
1026         assert_se(n % sizeof(gid_t) == 0);
1027         n /= sizeof(gid_t);
1028
1029         if ((socklen_t) (int) n != n)
1030                 return -E2BIG;
1031
1032         *ret = TAKE_PTR(d);
1033
1034         return (int) n;
1035 }
1036
1037 int send_one_fd_sa(
1038                 int transport_fd,
1039                 int fd,
1040                 const struct sockaddr *sa, socklen_t len,
1041                 int flags) {
1042
1043         union {
1044                 struct cmsghdr cmsghdr;
1045                 uint8_t buf[CMSG_SPACE(sizeof(int))];
1046         } control = {};
1047         struct msghdr mh = {
1048                 .msg_name = (struct sockaddr*) sa,
1049                 .msg_namelen = len,
1050                 .msg_control = &control,
1051                 .msg_controllen = sizeof(control),
1052         };
1053         struct cmsghdr *cmsg;
1054
1055         assert(transport_fd >= 0);
1056         assert(fd >= 0);
1057
1058         cmsg = CMSG_FIRSTHDR(&mh);
1059         cmsg->cmsg_level = SOL_SOCKET;
1060         cmsg->cmsg_type = SCM_RIGHTS;
1061         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1062         memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1063
1064         mh.msg_controllen = CMSG_SPACE(sizeof(int));
1065         if (sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags) < 0)
1066                 return -errno;
1067
1068         return 0;
1069 }
1070
1071 #if 0 /// UNNEEDED by elogind
1072 int receive_one_fd(int transport_fd, int flags) {
1073         union {
1074                 struct cmsghdr cmsghdr;
1075                 uint8_t buf[CMSG_SPACE(sizeof(int))];
1076         } control = {};
1077         struct msghdr mh = {
1078                 .msg_control = &control,
1079                 .msg_controllen = sizeof(control),
1080         };
1081         struct cmsghdr *cmsg, *found = NULL;
1082
1083         assert(transport_fd >= 0);
1084
1085         /*
1086          * Receive a single FD via @transport_fd. We don't care for
1087          * the transport-type. We retrieve a single FD at most, so for
1088          * packet-based transports, the caller must ensure to send
1089          * only a single FD per packet.  This is best used in
1090          * combination with send_one_fd().
1091          */
1092
1093         if (recvmsg(transport_fd, &mh, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC | flags) < 0)
1094                 return -errno;
1095
1096         CMSG_FOREACH(cmsg, &mh) {
1097                 if (cmsg->cmsg_level == SOL_SOCKET &&
1098                     cmsg->cmsg_type == SCM_RIGHTS &&
1099                     cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
1100                         assert(!found);
1101                         found = cmsg;
1102                         break;
1103                 }
1104         }
1105
1106         if (!found) {
1107                 cmsg_close_all(&mh);
1108                 return -EIO;
1109         }
1110
1111         return *(int*) CMSG_DATA(found);
1112 }
1113
1114 ssize_t next_datagram_size_fd(int fd) {
1115         ssize_t l;
1116         int k;
1117
1118         /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1119          * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1120          * do. This difference is actually of major importance as we need to be sure that the size returned here
1121          * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1122          * the wrong size. */
1123
1124         l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1125         if (l < 0) {
1126                 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
1127                         goto fallback;
1128
1129                 return -errno;
1130         }
1131         if (l == 0)
1132                 goto fallback;
1133
1134         return l;
1135
1136 fallback:
1137         k = 0;
1138
1139         /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1140          * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1141
1142         if (ioctl(fd, FIONREAD, &k) < 0)
1143                 return -errno;
1144
1145         return (ssize_t) k;
1146 }
1147
1148 int flush_accept(int fd) {
1149
1150         struct pollfd pollfd = {
1151                 .fd = fd,
1152                 .events = POLLIN,
1153         };
1154         int r;
1155
1156         /* Similar to flush_fd() but flushes all incoming connection by accepting them and immediately closing them. */
1157
1158         for (;;) {
1159                 int cfd;
1160
1161                 r = poll(&pollfd, 1, 0);
1162                 if (r < 0) {
1163                         if (errno == EINTR)
1164                                 continue;
1165
1166                         return -errno;
1167
1168                 } else if (r == 0)
1169                         return 0;
1170
1171                 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1172                 if (cfd < 0) {
1173                         if (errno == EINTR)
1174                                 continue;
1175
1176                         if (errno == EAGAIN)
1177                                 return 0;
1178
1179                         return -errno;
1180                 }
1181
1182                 close(cfd);
1183         }
1184 }
1185
1186 struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1187         struct cmsghdr *cmsg;
1188
1189         assert(mh);
1190
1191         CMSG_FOREACH(cmsg, mh)
1192                 if (cmsg->cmsg_level == level &&
1193                     cmsg->cmsg_type == type &&
1194                     (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1195                         return cmsg;
1196
1197         return NULL;
1198 }
1199
1200 int socket_ioctl_fd(void) {
1201         int fd;
1202
1203         /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1204          * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1205          * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1206          * generic AF_NETLINK. */
1207
1208         fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1209         if (fd < 0)
1210                 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1211         if (fd < 0)
1212                 return -errno;
1213
1214         return fd;
1215 }
1216 #endif // 0