chiark / gitweb /
tree-wide: drop license boilerplate
[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
691         *ret = p;
692         return 0;
693 }
694
695 int getpeername_pretty(int fd, bool include_port, char **ret) {
696         union sockaddr_union sa;
697         socklen_t salen = sizeof(sa);
698         int r;
699
700         assert(fd >= 0);
701         assert(ret);
702
703         if (getpeername(fd, &sa.sa, &salen) < 0)
704                 return -errno;
705
706         if (sa.sa.sa_family == AF_UNIX) {
707                 struct ucred ucred = {};
708
709                 /* UNIX connection sockets are anonymous, so let's use
710                  * PID/UID as pretty credentials instead */
711
712                 r = getpeercred(fd, &ucred);
713                 if (r < 0)
714                         return r;
715
716                 if (asprintf(ret, "PID "PID_FMT"/UID "UID_FMT, ucred.pid, ucred.uid) < 0)
717                         return -ENOMEM;
718
719                 return 0;
720         }
721
722         /* For remote sockets we translate IPv6 addresses back to IPv4
723          * if applicable, since that's nicer. */
724
725         return sockaddr_pretty(&sa.sa, salen, true, include_port, ret);
726 }
727
728 int getsockname_pretty(int fd, char **ret) {
729         union sockaddr_union sa;
730         socklen_t salen = sizeof(sa);
731
732         assert(fd >= 0);
733         assert(ret);
734
735         if (getsockname(fd, &sa.sa, &salen) < 0)
736                 return -errno;
737
738         /* For local sockets we do not translate IPv6 addresses back
739          * to IPv6 if applicable, since this is usually used for
740          * listening sockets where the difference between IPv4 and
741          * IPv6 matters. */
742
743         return sockaddr_pretty(&sa.sa, salen, false, true, ret);
744 }
745
746 int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret) {
747         int r;
748         char host[NI_MAXHOST], *ret;
749
750         assert(_ret);
751
752         r = getnameinfo(&sa->sa, salen, host, sizeof(host), NULL, 0, IDN_FLAGS);
753         if (r != 0) {
754                 int saved_errno = errno;
755
756                 r = sockaddr_pretty(&sa->sa, salen, true, true, &ret);
757                 if (r < 0)
758                         return r;
759
760                 log_debug_errno(saved_errno, "getnameinfo(%s) failed: %m", ret);
761         } else {
762                 ret = strdup(host);
763                 if (!ret)
764                         return -ENOMEM;
765         }
766
767         *_ret = ret;
768         return 0;
769 }
770
771 int socket_address_unlink(SocketAddress *a) {
772         assert(a);
773
774         if (socket_address_family(a) != AF_UNIX)
775                 return 0;
776
777         if (a->sockaddr.un.sun_path[0] == 0)
778                 return 0;
779
780         if (unlink(a->sockaddr.un.sun_path) < 0)
781                 return -errno;
782
783         return 1;
784 }
785
786 static const char* const netlink_family_table[] = {
787         [NETLINK_ROUTE] = "route",
788         [NETLINK_FIREWALL] = "firewall",
789         [NETLINK_INET_DIAG] = "inet-diag",
790         [NETLINK_NFLOG] = "nflog",
791         [NETLINK_XFRM] = "xfrm",
792         [NETLINK_SELINUX] = "selinux",
793         [NETLINK_ISCSI] = "iscsi",
794         [NETLINK_AUDIT] = "audit",
795         [NETLINK_FIB_LOOKUP] = "fib-lookup",
796         [NETLINK_CONNECTOR] = "connector",
797         [NETLINK_NETFILTER] = "netfilter",
798         [NETLINK_IP6_FW] = "ip6-fw",
799         [NETLINK_DNRTMSG] = "dnrtmsg",
800         [NETLINK_KOBJECT_UEVENT] = "kobject-uevent",
801         [NETLINK_GENERIC] = "generic",
802         [NETLINK_SCSITRANSPORT] = "scsitransport",
803         [NETLINK_ECRYPTFS] = "ecryptfs",
804         [NETLINK_RDMA] = "rdma",
805 };
806
807 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(netlink_family, int, INT_MAX);
808
809 static const char* const socket_address_bind_ipv6_only_table[_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX] = {
810         [SOCKET_ADDRESS_DEFAULT] = "default",
811         [SOCKET_ADDRESS_BOTH] = "both",
812         [SOCKET_ADDRESS_IPV6_ONLY] = "ipv6-only"
813 };
814
815 DEFINE_STRING_TABLE_LOOKUP(socket_address_bind_ipv6_only, SocketAddressBindIPv6Only);
816
817 SocketAddressBindIPv6Only parse_socket_address_bind_ipv6_only_or_bool(const char *n) {
818         int r;
819
820         r = parse_boolean(n);
821         if (r > 0)
822                 return SOCKET_ADDRESS_IPV6_ONLY;
823         if (r == 0)
824                 return SOCKET_ADDRESS_BOTH;
825
826         return socket_address_bind_ipv6_only_from_string(n);
827 }
828
829 bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b) {
830         assert(a);
831         assert(b);
832
833         if (a->sa.sa_family != b->sa.sa_family)
834                 return false;
835
836         if (a->sa.sa_family == AF_INET)
837                 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
838
839         if (a->sa.sa_family == AF_INET6)
840                 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
841
842         if (a->sa.sa_family == AF_VSOCK)
843                 return a->vm.svm_cid == b->vm.svm_cid;
844
845         return false;
846 }
847 #endif // 0
848
849 int fd_inc_sndbuf(int fd, size_t n) {
850         int r, value;
851         socklen_t l = sizeof(value);
852
853         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
854         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
855                 return 0;
856
857         /* If we have the privileges we will ignore the kernel limit. */
858
859         value = (int) n;
860         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
861                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
862                         return -errno;
863
864         return 1;
865 }
866
867 int fd_inc_rcvbuf(int fd, size_t n) {
868         int r, value;
869         socklen_t l = sizeof(value);
870
871         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
872         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
873                 return 0;
874
875         /* If we have the privileges we will ignore the kernel limit. */
876
877         value = (int) n;
878         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
879                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
880                         return -errno;
881         return 1;
882 }
883
884 #if 0 /// UNNEEDED by elogind
885 static const char* const ip_tos_table[] = {
886         [IPTOS_LOWDELAY] = "low-delay",
887         [IPTOS_THROUGHPUT] = "throughput",
888         [IPTOS_RELIABILITY] = "reliability",
889         [IPTOS_LOWCOST] = "low-cost",
890 };
891
892 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
893
894 bool ifname_valid(const char *p) {
895         bool numeric = true;
896
897         /* Checks whether a network interface name is valid. This is inspired by dev_valid_name() in the kernel sources
898          * but slightly stricter, as we only allow non-control, non-space ASCII characters in the interface name. We
899          * also don't permit names that only container numbers, to avoid confusion with numeric interface indexes. */
900
901         if (isempty(p))
902                 return false;
903
904         if (strlen(p) >= IFNAMSIZ)
905                 return false;
906
907         if (dot_or_dot_dot(p))
908                 return false;
909
910         while (*p) {
911                 if ((unsigned char) *p >= 127U)
912                         return false;
913
914                 if ((unsigned char) *p <= 32U)
915                         return false;
916
917                 if (IN_SET(*p, ':', '/'))
918                         return false;
919
920                 numeric = numeric && (*p >= '0' && *p <= '9');
921                 p++;
922         }
923
924         if (numeric)
925                 return false;
926
927         return true;
928 }
929
930 bool address_label_valid(const char *p) {
931
932         if (isempty(p))
933                 return false;
934
935         if (strlen(p) >= IFNAMSIZ)
936                 return false;
937
938         while (*p) {
939                 if ((uint8_t) *p >= 127U)
940                         return false;
941
942                 if ((uint8_t) *p <= 31U)
943                         return false;
944                 p++;
945         }
946
947         return true;
948 }
949 #endif // 0
950
951 int getpeercred(int fd, struct ucred *ucred) {
952         socklen_t n = sizeof(struct ucred);
953         struct ucred u;
954         int r;
955
956         assert(fd >= 0);
957         assert(ucred);
958
959         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
960         if (r < 0)
961                 return -errno;
962
963         if (n != sizeof(struct ucred))
964                 return -EIO;
965
966         /* Check if the data is actually useful and not suppressed due to namespacing issues */
967         if (!pid_is_valid(u.pid))
968                 return -ENODATA;
969
970         /* Note that we don't check UID/GID here, as namespace translation works differently there: instead of
971          * receiving in "invalid" user/group we get the overflow UID/GID. */
972
973         *ucred = u;
974         return 0;
975 }
976
977 int getpeersec(int fd, char **ret) {
978         _cleanup_free_ char *s = NULL;
979         socklen_t n = 64;
980
981         assert(fd >= 0);
982         assert(ret);
983
984         for (;;) {
985                 s = new0(char, n+1);
986                 if (!s)
987                         return -ENOMEM;
988
989                 if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n) >= 0)
990                         break;
991
992                 if (errno != ERANGE)
993                         return -errno;
994
995                 s = mfree(s);
996         }
997
998         if (isempty(s))
999                 return -EOPNOTSUPP;
1000
1001         *ret = TAKE_PTR(s);
1002
1003         return 0;
1004 }
1005
1006 int getpeergroups(int fd, gid_t **ret) {
1007         socklen_t n = sizeof(gid_t) * 64;
1008         _cleanup_free_ gid_t *d = NULL;
1009
1010         assert(fd >= 0);
1011         assert(ret);
1012
1013         for (;;) {
1014                 d = malloc(n);
1015                 if (!d)
1016                         return -ENOMEM;
1017
1018                 if (getsockopt(fd, SOL_SOCKET, SO_PEERGROUPS, d, &n) >= 0)
1019                         break;
1020
1021                 if (errno != ERANGE)
1022                         return -errno;
1023
1024                 d = mfree(d);
1025         }
1026
1027         assert_se(n % sizeof(gid_t) == 0);
1028         n /= sizeof(gid_t);
1029
1030         if ((socklen_t) (int) n != n)
1031                 return -E2BIG;
1032
1033         *ret = TAKE_PTR(d);
1034
1035         return (int) n;
1036 }
1037
1038 int send_one_fd_sa(
1039                 int transport_fd,
1040                 int fd,
1041                 const struct sockaddr *sa, socklen_t len,
1042                 int flags) {
1043
1044         union {
1045                 struct cmsghdr cmsghdr;
1046                 uint8_t buf[CMSG_SPACE(sizeof(int))];
1047         } control = {};
1048         struct msghdr mh = {
1049                 .msg_name = (struct sockaddr*) sa,
1050                 .msg_namelen = len,
1051                 .msg_control = &control,
1052                 .msg_controllen = sizeof(control),
1053         };
1054         struct cmsghdr *cmsg;
1055
1056         assert(transport_fd >= 0);
1057         assert(fd >= 0);
1058
1059         cmsg = CMSG_FIRSTHDR(&mh);
1060         cmsg->cmsg_level = SOL_SOCKET;
1061         cmsg->cmsg_type = SCM_RIGHTS;
1062         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1063         memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1064
1065         mh.msg_controllen = CMSG_SPACE(sizeof(int));
1066         if (sendmsg(transport_fd, &mh, MSG_NOSIGNAL | flags) < 0)
1067                 return -errno;
1068
1069         return 0;
1070 }
1071
1072 #if 0 /// UNNEEDED by elogind
1073 int receive_one_fd(int transport_fd, int flags) {
1074         union {
1075                 struct cmsghdr cmsghdr;
1076                 uint8_t buf[CMSG_SPACE(sizeof(int))];
1077         } control = {};
1078         struct msghdr mh = {
1079                 .msg_control = &control,
1080                 .msg_controllen = sizeof(control),
1081         };
1082         struct cmsghdr *cmsg, *found = NULL;
1083
1084         assert(transport_fd >= 0);
1085
1086         /*
1087          * Receive a single FD via @transport_fd. We don't care for
1088          * the transport-type. We retrieve a single FD at most, so for
1089          * packet-based transports, the caller must ensure to send
1090          * only a single FD per packet.  This is best used in
1091          * combination with send_one_fd().
1092          */
1093
1094         if (recvmsg(transport_fd, &mh, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC | flags) < 0)
1095                 return -errno;
1096
1097         CMSG_FOREACH(cmsg, &mh) {
1098                 if (cmsg->cmsg_level == SOL_SOCKET &&
1099                     cmsg->cmsg_type == SCM_RIGHTS &&
1100                     cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
1101                         assert(!found);
1102                         found = cmsg;
1103                         break;
1104                 }
1105         }
1106
1107         if (!found) {
1108                 cmsg_close_all(&mh);
1109                 return -EIO;
1110         }
1111
1112         return *(int*) CMSG_DATA(found);
1113 }
1114
1115 ssize_t next_datagram_size_fd(int fd) {
1116         ssize_t l;
1117         int k;
1118
1119         /* This is a bit like FIONREAD/SIOCINQ, however a bit more powerful. The difference being: recv(MSG_PEEK) will
1120          * actually cause the next datagram in the queue to be validated regarding checksums, which FIONREAD doesn't
1121          * do. This difference is actually of major importance as we need to be sure that the size returned here
1122          * actually matches what we will read with recvmsg() next, as otherwise we might end up allocating a buffer of
1123          * the wrong size. */
1124
1125         l = recv(fd, NULL, 0, MSG_PEEK|MSG_TRUNC);
1126         if (l < 0) {
1127                 if (IN_SET(errno, EOPNOTSUPP, EFAULT))
1128                         goto fallback;
1129
1130                 return -errno;
1131         }
1132         if (l == 0)
1133                 goto fallback;
1134
1135         return l;
1136
1137 fallback:
1138         k = 0;
1139
1140         /* Some sockets (AF_PACKET) do not support null-sized recv() with MSG_TRUNC set, let's fall back to FIONREAD
1141          * for them. Checksums don't matter for raw sockets anyway, hence this should be fine. */
1142
1143         if (ioctl(fd, FIONREAD, &k) < 0)
1144                 return -errno;
1145
1146         return (ssize_t) k;
1147 }
1148
1149 int flush_accept(int fd) {
1150
1151         struct pollfd pollfd = {
1152                 .fd = fd,
1153                 .events = POLLIN,
1154         };
1155         int r;
1156
1157
1158         /* Similar to flush_fd() but flushes all incoming connection by accepting them and immediately closing them. */
1159
1160         for (;;) {
1161                 int cfd;
1162
1163                 r = poll(&pollfd, 1, 0);
1164                 if (r < 0) {
1165                         if (errno == EINTR)
1166                                 continue;
1167
1168                         return -errno;
1169
1170                 } else if (r == 0)
1171                         return 0;
1172
1173                 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
1174                 if (cfd < 0) {
1175                         if (errno == EINTR)
1176                                 continue;
1177
1178                         if (errno == EAGAIN)
1179                                 return 0;
1180
1181                         return -errno;
1182                 }
1183
1184                 close(cfd);
1185         }
1186 }
1187
1188 struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length) {
1189         struct cmsghdr *cmsg;
1190
1191         assert(mh);
1192
1193         CMSG_FOREACH(cmsg, mh)
1194                 if (cmsg->cmsg_level == level &&
1195                     cmsg->cmsg_type == type &&
1196                     (length == (socklen_t) -1 || length == cmsg->cmsg_len))
1197                         return cmsg;
1198
1199         return NULL;
1200 }
1201
1202 int socket_ioctl_fd(void) {
1203         int fd;
1204
1205         /* Create a socket to invoke the various network interface ioctl()s on. Traditionally only AF_INET was good for
1206          * that. Since kernel 4.6 AF_NETLINK works for this too. We first try to use AF_INET hence, but if that's not
1207          * available (for example, because it is made unavailable via SECCOMP or such), we'll fall back to the more
1208          * generic AF_NETLINK. */
1209
1210         fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
1211         if (fd < 0)
1212                 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_GENERIC);
1213         if (fd < 0)
1214                 return -errno;
1215
1216         return fd;
1217 }
1218 #endif // 0