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