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