chiark / gitweb /
sd-bus: get rid of kdbus flags cruft
[elogind.git] / src / libelogind / sd-bus / bus-socket.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2013 Lennart Poettering
6
7   systemd is free software; you can redistribute it and/or modify it
8   under the terms of the GNU Lesser General Public License as published by
9   the Free Software Foundation; either version 2.1 of the License, or
10   (at your option) any later version.
11
12   systemd is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   Lesser General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <endian.h>
22 #include <poll.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25
26 #include "sd-bus.h"
27 #include "sd-daemon.h"
28
29 #include "alloc-util.h"
30 #include "bus-internal.h"
31 #include "bus-message.h"
32 #include "bus-socket.h"
33 #include "fd-util.h"
34 #include "format-util.h"
35 //#include "fs-util.h"
36 #include "hexdecoct.h"
37 //#include "io-util.h"
38 #include "macro.h"
39 #include "missing.h"
40 //#include "path-util.h"
41 #include "selinux-util.h"
42 #include "signal-util.h"
43 #include "stdio-util.h"
44 #include "string-util.h"
45 #include "user-util.h"
46 #include "utf8.h"
47 #include "util.h"
48
49 #define SNDBUF_SIZE (8*1024*1024)
50
51 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
52
53         while (size > 0) {
54                 struct iovec *i = iov + *idx;
55
56                 if (i->iov_len > size) {
57                         i->iov_base = (uint8_t*) i->iov_base + size;
58                         i->iov_len -= size;
59                         return;
60                 }
61
62                 size -= i->iov_len;
63
64                 i->iov_base = NULL;
65                 i->iov_len = 0;
66
67                 (*idx)++;
68         }
69 }
70
71 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
72         assert(m);
73         assert(p);
74         assert(sz > 0);
75
76         m->iovec[m->n_iovec].iov_base = (void*) p;
77         m->iovec[m->n_iovec].iov_len = sz;
78         m->n_iovec++;
79
80         return 0;
81 }
82
83 static int bus_message_setup_iovec(sd_bus_message *m) {
84         struct bus_body_part *part;
85         unsigned n, i;
86         int r;
87
88         assert(m);
89         assert(m->sealed);
90
91         if (m->n_iovec > 0)
92                 return 0;
93
94         assert(!m->iovec);
95
96         n = 1 + m->n_body_parts;
97         if (n < ELEMENTSOF(m->iovec_fixed))
98                 m->iovec = m->iovec_fixed;
99         else {
100                 m->iovec = new(struct iovec, n);
101                 if (!m->iovec) {
102                         r = -ENOMEM;
103                         goto fail;
104                 }
105         }
106
107         r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
108         if (r < 0)
109                 goto fail;
110
111         MESSAGE_FOREACH_PART(part, i, m)  {
112                 r = bus_body_part_map(part);
113                 if (r < 0)
114                         goto fail;
115
116                 r = append_iovec(m, part->data, part->size);
117                 if (r < 0)
118                         goto fail;
119         }
120
121         assert(n == m->n_iovec);
122
123         return 0;
124
125 fail:
126         m->poisoned = true;
127         return r;
128 }
129
130 bool bus_socket_auth_needs_write(sd_bus *b) {
131
132         unsigned i;
133
134         if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
135                 return false;
136
137         for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
138                 struct iovec *j = b->auth_iovec + i;
139
140                 if (j->iov_len > 0)
141                         return true;
142         }
143
144         return false;
145 }
146
147 static int bus_socket_write_auth(sd_bus *b) {
148         ssize_t k;
149
150         assert(b);
151         assert(b->state == BUS_AUTHENTICATING);
152
153         if (!bus_socket_auth_needs_write(b))
154                 return 0;
155
156         if (b->prefer_writev)
157                 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
158         else {
159                 struct msghdr mh;
160                 zero(mh);
161
162                 mh.msg_iov = b->auth_iovec + b->auth_index;
163                 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
164
165                 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
166                 if (k < 0 && errno == ENOTSOCK) {
167                         b->prefer_writev = true;
168                         k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
169                 }
170         }
171
172         if (k < 0)
173                 return errno == EAGAIN ? 0 : -errno;
174
175         iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
176         return 1;
177 }
178
179 static int bus_socket_auth_verify_client(sd_bus *b) {
180         char *e, *f, *start;
181         sd_id128_t peer;
182         unsigned i;
183         int r;
184
185         assert(b);
186
187         /* We expect two response lines: "OK" and possibly
188          * "AGREE_UNIX_FD" */
189
190         e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
191         if (!e)
192                 return 0;
193
194         if (b->accept_fd) {
195                 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
196                 if (!f)
197                         return 0;
198
199                 start = f + 2;
200         } else {
201                 f = NULL;
202                 start = e + 2;
203         }
204
205         /* Nice! We got all the lines we need. First check the OK
206          * line */
207
208         if (e - (char*) b->rbuffer != 3 + 32)
209                 return -EPERM;
210
211         if (memcmp(b->rbuffer, "OK ", 3))
212                 return -EPERM;
213
214         b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
215
216         for (i = 0; i < 32; i += 2) {
217                 int x, y;
218
219                 x = unhexchar(((char*) b->rbuffer)[3 + i]);
220                 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
221
222                 if (x < 0 || y < 0)
223                         return -EINVAL;
224
225                 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
226         }
227
228         if (!sd_id128_is_null(b->server_id) &&
229             !sd_id128_equal(b->server_id, peer))
230                 return -EPERM;
231
232         b->server_id = peer;
233
234         /* And possibly check the second line, too */
235
236         if (f)
237                 b->can_fds =
238                         (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
239                         memcmp(e + 2, "AGREE_UNIX_FD",
240                                STRLEN("AGREE_UNIX_FD")) == 0;
241
242         b->rbuffer_size -= (start - (char*) b->rbuffer);
243         memmove(b->rbuffer, start, b->rbuffer_size);
244
245         r = bus_start_running(b);
246         if (r < 0)
247                 return r;
248
249         return 1;
250 }
251
252 static bool line_equals(const char *s, size_t m, const char *line) {
253         size_t l;
254
255         l = strlen(line);
256         if (l != m)
257                 return false;
258
259         return memcmp(s, line, l) == 0;
260 }
261
262 static bool line_begins(const char *s, size_t m, const char *word) {
263         size_t l;
264
265         l = strlen(word);
266         if (m < l)
267                 return false;
268
269         if (memcmp(s, word, l) != 0)
270                 return false;
271
272         return m == l || (m > l && s[l] == ' ');
273 }
274
275 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
276         _cleanup_free_ char *token = NULL;
277         size_t len;
278         int r;
279
280         if (!b->anonymous_auth)
281                 return 0;
282
283         if (l <= 0)
284                 return 1;
285
286         assert(p[0] == ' ');
287         p++; l--;
288
289         if (l % 2 != 0)
290                 return 0;
291
292         r = unhexmem(p, l, (void **) &token, &len);
293         if (r < 0)
294                 return 0;
295
296         if (memchr(token, 0, len))
297                 return 0;
298
299         return !!utf8_is_valid(token);
300 }
301
302 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
303         _cleanup_free_ char *token = NULL;
304         size_t len;
305         uid_t u;
306         int r;
307
308         /* We don't do any real authentication here. Instead, we if
309          * the owner of this bus wanted authentication he should have
310          * checked SO_PEERCRED before even creating the bus object. */
311
312         if (!b->anonymous_auth && !b->ucred_valid)
313                 return 0;
314
315         if (l <= 0)
316                 return 1;
317
318         assert(p[0] == ' ');
319         p++; l--;
320
321         if (l % 2 != 0)
322                 return 0;
323
324         r = unhexmem(p, l, (void**) &token, &len);
325         if (r < 0)
326                 return 0;
327
328         if (memchr(token, 0, len))
329                 return 0;
330
331         r = parse_uid(token, &u);
332         if (r < 0)
333                 return 0;
334
335         /* We ignore the passed value if anonymous authentication is
336          * on anyway. */
337         if (!b->anonymous_auth && u != b->ucred.uid)
338                 return 0;
339
340         return 1;
341 }
342
343 static int bus_socket_auth_write(sd_bus *b, const char *t) {
344         char *p;
345         size_t l;
346
347         assert(b);
348         assert(t);
349
350         /* We only make use of the first iovec */
351         assert(IN_SET(b->auth_index, 0, 1));
352
353         l = strlen(t);
354         p = malloc(b->auth_iovec[0].iov_len + l);
355         if (!p)
356                 return -ENOMEM;
357
358         memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
359         memcpy(p + b->auth_iovec[0].iov_len, t, l);
360
361         b->auth_iovec[0].iov_base = p;
362         b->auth_iovec[0].iov_len += l;
363
364         free(b->auth_buffer);
365         b->auth_buffer = p;
366         b->auth_index = 0;
367         return 0;
368 }
369
370 static int bus_socket_auth_write_ok(sd_bus *b) {
371         char t[3 + 32 + 2 + 1];
372
373         assert(b);
374
375         xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
376
377         return bus_socket_auth_write(b, t);
378 }
379
380 static int bus_socket_auth_verify_server(sd_bus *b) {
381         char *e;
382         const char *line;
383         size_t l;
384         bool processed = false;
385         int r;
386
387         assert(b);
388
389         if (b->rbuffer_size < 1)
390                 return 0;
391
392         /* First char must be a NUL byte */
393         if (*(char*) b->rbuffer != 0)
394                 return -EIO;
395
396         if (b->rbuffer_size < 3)
397                 return 0;
398
399         /* Begin with the first line */
400         if (b->auth_rbegin <= 0)
401                 b->auth_rbegin = 1;
402
403         for (;;) {
404                 /* Check if line is complete */
405                 line = (char*) b->rbuffer + b->auth_rbegin;
406                 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
407                 if (!e)
408                         return processed;
409
410                 l = e - line;
411
412                 if (line_begins(line, l, "AUTH ANONYMOUS")) {
413
414                         r = verify_anonymous_token(b, line + 14, l - 14);
415                         if (r < 0)
416                                 return r;
417                         if (r == 0)
418                                 r = bus_socket_auth_write(b, "REJECTED\r\n");
419                         else {
420                                 b->auth = BUS_AUTH_ANONYMOUS;
421                                 r = bus_socket_auth_write_ok(b);
422                         }
423
424                 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
425
426                         r = verify_external_token(b, line + 13, l - 13);
427                         if (r < 0)
428                                 return r;
429                         if (r == 0)
430                                 r = bus_socket_auth_write(b, "REJECTED\r\n");
431                         else {
432                                 b->auth = BUS_AUTH_EXTERNAL;
433                                 r = bus_socket_auth_write_ok(b);
434                         }
435
436                 } else if (line_begins(line, l, "AUTH"))
437                         r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
438                 else if (line_equals(line, l, "CANCEL") ||
439                          line_begins(line, l, "ERROR")) {
440
441                         b->auth = _BUS_AUTH_INVALID;
442                         r = bus_socket_auth_write(b, "REJECTED\r\n");
443
444                 } else if (line_equals(line, l, "BEGIN")) {
445
446                         if (b->auth == _BUS_AUTH_INVALID)
447                                 r = bus_socket_auth_write(b, "ERROR\r\n");
448                         else {
449                                 /* We can't leave from the auth phase
450                                  * before we haven't written
451                                  * everything queued, so let's check
452                                  * that */
453
454                                 if (bus_socket_auth_needs_write(b))
455                                         return 1;
456
457                                 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
458                                 memmove(b->rbuffer, e + 2, b->rbuffer_size);
459                                 return bus_start_running(b);
460                         }
461
462                 } else if (line_begins(line, l, "DATA")) {
463
464                         if (b->auth == _BUS_AUTH_INVALID)
465                                 r = bus_socket_auth_write(b, "ERROR\r\n");
466                         else {
467                                 if (b->auth == BUS_AUTH_ANONYMOUS)
468                                         r = verify_anonymous_token(b, line + 4, l - 4);
469                                 else
470                                         r = verify_external_token(b, line + 4, l - 4);
471
472                                 if (r < 0)
473                                         return r;
474                                 if (r == 0) {
475                                         b->auth = _BUS_AUTH_INVALID;
476                                         r = bus_socket_auth_write(b, "REJECTED\r\n");
477                                 } else
478                                         r = bus_socket_auth_write_ok(b);
479                         }
480                 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
481                         if (b->auth == _BUS_AUTH_INVALID || !b->accept_fd)
482                                 r = bus_socket_auth_write(b, "ERROR\r\n");
483                         else {
484                                 b->can_fds = true;
485                                 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
486                         }
487                 } else
488                         r = bus_socket_auth_write(b, "ERROR\r\n");
489
490                 if (r < 0)
491                         return r;
492
493                 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
494
495                 processed = true;
496         }
497 }
498
499 static int bus_socket_auth_verify(sd_bus *b) {
500         assert(b);
501
502         if (b->is_server)
503                 return bus_socket_auth_verify_server(b);
504         else
505                 return bus_socket_auth_verify_client(b);
506 }
507
508 static int bus_socket_read_auth(sd_bus *b) {
509         struct msghdr mh;
510         struct iovec iov = {};
511         size_t n;
512         ssize_t k;
513         int r;
514         void *p;
515         union {
516                 struct cmsghdr cmsghdr;
517                 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
518         } control;
519         bool handle_cmsg = false;
520
521         assert(b);
522         assert(b->state == BUS_AUTHENTICATING);
523
524         r = bus_socket_auth_verify(b);
525         if (r != 0)
526                 return r;
527
528         n = MAX(256u, b->rbuffer_size * 2);
529
530         if (n > BUS_AUTH_SIZE_MAX)
531                 n = BUS_AUTH_SIZE_MAX;
532
533         if (b->rbuffer_size >= n)
534                 return -ENOBUFS;
535
536         p = realloc(b->rbuffer, n);
537         if (!p)
538                 return -ENOMEM;
539
540         b->rbuffer = p;
541
542         iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
543         iov.iov_len = n - b->rbuffer_size;
544
545         if (b->prefer_readv)
546                 k = readv(b->input_fd, &iov, 1);
547         else {
548                 zero(mh);
549                 mh.msg_iov = &iov;
550                 mh.msg_iovlen = 1;
551                 mh.msg_control = &control;
552                 mh.msg_controllen = sizeof(control);
553
554                 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
555                 if (k < 0 && errno == ENOTSOCK) {
556                         b->prefer_readv = true;
557                         k = readv(b->input_fd, &iov, 1);
558                 } else
559                         handle_cmsg = true;
560         }
561         if (k < 0)
562                 return errno == EAGAIN ? 0 : -errno;
563         if (k == 0)
564                 return -ECONNRESET;
565
566         b->rbuffer_size += k;
567
568         if (handle_cmsg) {
569                 struct cmsghdr *cmsg;
570
571                 CMSG_FOREACH(cmsg, &mh)
572                         if (cmsg->cmsg_level == SOL_SOCKET &&
573                             cmsg->cmsg_type == SCM_RIGHTS) {
574                                 int j;
575
576                                 /* Whut? We received fds during the auth
577                                  * protocol? Somebody is playing games with
578                                  * us. Close them all, and fail */
579                                 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
580                                 close_many((int*) CMSG_DATA(cmsg), j);
581                                 return -EIO;
582                         } else
583                                 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
584                                           cmsg->cmsg_level, cmsg->cmsg_type);
585         }
586
587         r = bus_socket_auth_verify(b);
588         if (r != 0)
589                 return r;
590
591         return 1;
592 }
593
594 void bus_socket_setup(sd_bus *b) {
595         assert(b);
596
597         /* Increase the buffers to 8 MB */
598         (void) fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
599         (void) fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
600
601         b->message_version = 1;
602         b->message_endian = 0;
603 }
604
605 static void bus_get_peercred(sd_bus *b) {
606         int r;
607
608         assert(b);
609         assert(!b->ucred_valid);
610         assert(!b->label);
611         assert(b->n_groups == (size_t) -1);
612
613         /* Get the peer for socketpair() sockets */
614         b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
615
616         /* Get the SELinux context of the peer */
617         r = getpeersec(b->input_fd, &b->label);
618         if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
619                 log_debug_errno(r, "Failed to determine peer security context: %m");
620
621         /* Get the list of auxiliary groups of the peer */
622         r = getpeergroups(b->input_fd, &b->groups);
623         if (r < 0) {
624                 if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
625                         log_debug_errno(r, "Failed to determine peer groups list: %m");
626
627                 b->n_groups = (size_t) -1;
628         } else
629                 b->n_groups = (size_t) r;
630 }
631
632 static int bus_socket_start_auth_client(sd_bus *b) {
633         size_t l;
634         const char *auth_suffix, *auth_prefix;
635
636         assert(b);
637
638         if (b->anonymous_auth) {
639                 auth_prefix = "\0AUTH ANONYMOUS ";
640
641                 /* For ANONYMOUS auth we send some arbitrary "trace" string */
642                 l = 9;
643                 b->auth_buffer = hexmem("anonymous", l);
644         } else {
645                 char text[DECIMAL_STR_MAX(uid_t) + 1];
646
647                 auth_prefix = "\0AUTH EXTERNAL ";
648
649                 xsprintf(text, UID_FMT, geteuid());
650
651                 l = strlen(text);
652                 b->auth_buffer = hexmem(text, l);
653         }
654
655         if (!b->auth_buffer)
656                 return -ENOMEM;
657
658         if (b->accept_fd)
659                 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
660         else
661                 auth_suffix = "\r\nBEGIN\r\n";
662
663         b->auth_iovec[0].iov_base = (void*) auth_prefix;
664         b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
665         b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
666         b->auth_iovec[1].iov_len = l * 2;
667         b->auth_iovec[2].iov_base = (void*) auth_suffix;
668         b->auth_iovec[2].iov_len = strlen(auth_suffix);
669
670         return bus_socket_write_auth(b);
671 }
672
673 int bus_socket_start_auth(sd_bus *b) {
674         assert(b);
675
676         bus_get_peercred(b);
677
678         b->state = BUS_AUTHENTICATING;
679         b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
680
681         if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
682                 b->accept_fd = false;
683
684         if (b->output_fd != b->input_fd)
685                 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
686                         b->accept_fd = false;
687
688         if (b->is_server)
689                 return bus_socket_read_auth(b);
690         else
691                 return bus_socket_start_auth_client(b);
692 }
693
694 static int bus_socket_inotify_setup(sd_bus *b) {
695         _cleanup_free_ int *new_watches = NULL;
696         _cleanup_free_ char *absolute = NULL;
697         size_t n_allocated = 0, n = 0, done = 0, i;
698         unsigned max_follow = 32;
699         const char *p;
700         int wd, r;
701
702         assert(b);
703         assert(b->watch_bind);
704         assert(b->sockaddr.sa.sa_family == AF_UNIX);
705         assert(b->sockaddr.un.sun_path[0] != 0);
706
707         /* Sets up an inotify fd in case watch_bind is enabled: wait until the configured AF_UNIX file system socket
708          * appears before connecting to it. The implemented is pretty simplistic: we just subscribe to relevant changes
709          * to all prefix components of the path, and every time we get an event for that we try to reconnect again,
710          * without actually caring what precisely the event we got told us. If we still can't connect we re-subscribe
711          * to all relevant changes of anything in the path, so that our watches include any possibly newly created path
712          * components. */
713
714         if (b->inotify_fd < 0) {
715                 b->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
716                 if (b->inotify_fd < 0)
717                         return -errno;
718         }
719
720         /* Make sure the path is NUL terminated */
721         p = strndupa(b->sockaddr.un.sun_path, sizeof(b->sockaddr.un.sun_path));
722
723         /* Make sure the path is absolute */
724         r = path_make_absolute_cwd(p, &absolute);
725         if (r < 0)
726                 goto fail;
727
728         /* Watch all parent directories, and don't mind any prefix that doesn't exist yet. For the innermost directory
729          * that exists we want to know when files are created or moved into it. For all parents of it we just care if
730          * they are removed or renamed. */
731
732         if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
733                 r = -ENOMEM;
734                 goto fail;
735         }
736
737         /* Start with the top-level directory, which is a bit simpler than the rest, since it can't be a symlink, and
738          * always exists */
739         wd = inotify_add_watch(b->inotify_fd, "/", IN_CREATE|IN_MOVED_TO);
740         if (wd < 0) {
741                 r = log_debug_errno(errno, "Failed to add inotify watch on /: %m");
742                 goto fail;
743         } else
744                 new_watches[n++] = wd;
745
746         for (;;) {
747                 _cleanup_free_ char *component = NULL, *prefix = NULL, *destination = NULL;
748                 size_t n_slashes, n_component;
749                 char *c = NULL;
750
751                 n_slashes = strspn(absolute + done, "/");
752                 n_component = n_slashes + strcspn(absolute + done + n_slashes, "/");
753
754                 if (n_component == 0) /* The end */
755                         break;
756
757                 component = strndup(absolute + done, n_component);
758                 if (!component) {
759                         r = -ENOMEM;
760                         goto fail;
761                 }
762
763                 /* A trailing slash? That's a directory, and not a socket then */
764                 if (path_equal(component, "/")) {
765                         r = -EISDIR;
766                         goto fail;
767                 }
768
769                 /* A single dot? Let's eat this up */
770                 if (path_equal(component, "/.")) {
771                         done += n_component;
772                         continue;
773                 }
774
775                 prefix = strndup(absolute, done + n_component);
776                 if (!prefix) {
777                         r = -ENOMEM;
778                         goto fail;
779                 }
780
781                 if (!GREEDY_REALLOC(new_watches, n_allocated, n + 1)) {
782                         r = -ENOMEM;
783                         goto fail;
784                 }
785
786                 wd = inotify_add_watch(b->inotify_fd, prefix, IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO|IN_DONT_FOLLOW);
787                 log_debug("Added inotify watch for %s on bus %s: %i", prefix, strna(b->description), wd);
788
789                 if (wd < 0) {
790                         if (IN_SET(errno, ENOENT, ELOOP))
791                                 break; /* This component doesn't exist yet, or the path contains a cyclic symlink right now */
792
793                         r = log_debug_errno(errno, "Failed to add inotify watch on %s: %m", isempty(prefix) ? "/" : prefix);
794                         goto fail;
795                 } else
796                         new_watches[n++] = wd;
797
798                 /* Check if this is possibly a symlink. If so, let's follow it and watch it too. */
799                 r = readlink_malloc(prefix, &destination);
800                 if (r == -EINVAL) { /* not a symlink */
801                         done += n_component;
802                         continue;
803                 }
804                 if (r < 0)
805                         goto fail;
806
807                 if (isempty(destination)) { /* Empty symlink target? Yuck! */
808                         r = -EINVAL;
809                         goto fail;
810                 }
811
812                 if (max_follow <= 0) { /* Let's make sure we don't follow symlinks forever */
813                         r = -ELOOP;
814                         goto fail;
815                 }
816
817                 if (path_is_absolute(destination)) {
818                         /* For absolute symlinks we build the new path and start anew */
819                         c = strjoin(destination, absolute + done + n_component);
820                         done = 0;
821                 } else {
822                         _cleanup_free_ char *t = NULL;
823
824                         /* For relative symlinks we replace the last component, and try again */
825                         t = strndup(absolute, done);
826                         if (!t)
827                                 return -ENOMEM;
828
829                         c = strjoin(t, "/", destination, absolute + done + n_component);
830                 }
831                 if (!c) {
832                         r = -ENOMEM;
833                         goto fail;
834                 }
835
836                 free(absolute);
837                 absolute = c;
838
839                 max_follow--;
840         }
841
842         /* And now, let's remove all watches from the previous iteration we don't need anymore */
843         for (i = 0; i < b->n_inotify_watches; i++) {
844                 bool found = false;
845                 size_t j;
846
847                 for (j = 0; j < n; j++)
848                         if (new_watches[j] == b->inotify_watches[i]) {
849                                 found = true;
850                                 break;
851                         }
852
853                 if (found)
854                         continue;
855
856                 (void) inotify_rm_watch(b->inotify_fd, b->inotify_watches[i]);
857         }
858
859         free_and_replace(b->inotify_watches, new_watches);
860         b->n_inotify_watches = n;
861
862         return 0;
863
864 fail:
865         bus_close_inotify_fd(b);
866         return r;
867 }
868
869 int bus_socket_connect(sd_bus *b) {
870         bool inotify_done = false;
871         int r;
872
873         assert(b);
874
875         for (;;) {
876                 assert(b->input_fd < 0);
877                 assert(b->output_fd < 0);
878                 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
879
880                 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
881                 if (b->input_fd < 0)
882                         return -errno;
883
884                 b->output_fd = b->input_fd;
885                 bus_socket_setup(b);
886
887                 if (connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size) < 0) {
888                         if (errno == EINPROGRESS) {
889
890                                 /* If we have any inotify watches open, close them now, we don't need them anymore, as
891                                  * we have successfully initiated a connection */
892                                 bus_close_inotify_fd(b);
893
894                                 /* Note that very likely we are already in BUS_OPENING state here, as we enter it when
895                                  * we start parsing the address string. The only reason we set the state explicitly
896                                  * here, is to undo BUS_WATCH_BIND, in case we did the inotify magic. */
897                                 b->state = BUS_OPENING;
898                                 return 1;
899                         }
900
901                         if (IN_SET(errno, ENOENT, ECONNREFUSED) &&  /* ENOENT â†’ unix socket doesn't exist at all; ECONNREFUSED â†’ unix socket stale */
902                             b->watch_bind &&
903                             b->sockaddr.sa.sa_family == AF_UNIX &&
904                             b->sockaddr.un.sun_path[0] != 0) {
905
906                                 /* This connection attempt failed, let's release the socket for now, and start with a
907                                  * fresh one when reconnecting. */
908                                 bus_close_io_fds(b);
909
910                                 if (inotify_done) {
911                                         /* inotify set up already, don't do it again, just return now, and remember
912                                          * that we are waiting for inotify events now. */
913                                         b->state = BUS_WATCH_BIND;
914                                         return 1;
915                                 }
916
917                                 /* This is a file system socket, and the inotify logic is enabled. Let's create the necessary inotify fd. */
918                                 r = bus_socket_inotify_setup(b);
919                                 if (r < 0)
920                                         return r;
921
922                                 /* Let's now try to connect a second time, because in theory there's otherwise a race
923                                  * here: the socket might have been created in the time between our first connect() and
924                                  * the time we set up the inotify logic. But let's remember that we set up inotify now,
925                                  * so that we don't do the connect() more than twice. */
926                                 inotify_done = true;
927
928                         } else
929                                 return -errno;
930                 } else
931                         break;
932         }
933
934         /* Yay, established, we don't need no inotify anymore! */
935         bus_close_inotify_fd(b);
936
937         return bus_socket_start_auth(b);
938 }
939
940 int bus_socket_exec(sd_bus *b) {
941         int s[2], r;
942         pid_t pid;
943
944         assert(b);
945         assert(b->input_fd < 0);
946         assert(b->output_fd < 0);
947         assert(b->exec_path);
948
949         r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
950         if (r < 0)
951                 return -errno;
952
953         r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &pid);
954         if (r < 0) {
955                 safe_close_pair(s);
956                 return r;
957         }
958         if (r == 0) {
959                 /* Child */
960
961                 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
962                 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
963
964                 if (!IN_SET(s[1], STDIN_FILENO, STDOUT_FILENO))
965                         safe_close(s[1]);
966
967                 (void) fd_cloexec(STDIN_FILENO, false);
968                 (void) fd_cloexec(STDOUT_FILENO, false);
969                 (void) fd_nonblock(STDIN_FILENO, false);
970                 (void) fd_nonblock(STDOUT_FILENO, false);
971
972                 if (b->exec_argv)
973                         execvp(b->exec_path, b->exec_argv);
974                 else {
975                         const char *argv[] = { b->exec_path, NULL };
976                         execvp(b->exec_path, (char**) argv);
977                 }
978
979                 _exit(EXIT_FAILURE);
980         }
981
982         safe_close(s[1]);
983         b->output_fd = b->input_fd = s[0];
984
985         bus_socket_setup(b);
986
987         return bus_socket_start_auth(b);
988 }
989
990 int bus_socket_take_fd(sd_bus *b) {
991         assert(b);
992
993         bus_socket_setup(b);
994
995         return bus_socket_start_auth(b);
996 }
997
998 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
999         struct iovec *iov;
1000         ssize_t k;
1001         size_t n;
1002         unsigned j;
1003         int r;
1004
1005         assert(bus);
1006         assert(m);
1007         assert(idx);
1008         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1009
1010         if (*idx >= BUS_MESSAGE_SIZE(m))
1011                 return 0;
1012
1013         r = bus_message_setup_iovec(m);
1014         if (r < 0)
1015                 return r;
1016
1017         n = m->n_iovec * sizeof(struct iovec);
1018         iov = alloca(n);
1019         memcpy_safe(iov, m->iovec, n);
1020
1021         j = 0;
1022         iovec_advance(iov, &j, *idx);
1023
1024         if (bus->prefer_writev)
1025                 k = writev(bus->output_fd, iov, m->n_iovec);
1026         else {
1027                 struct msghdr mh = {
1028                         .msg_iov = iov,
1029                         .msg_iovlen = m->n_iovec,
1030                 };
1031
1032                 if (m->n_fds > 0 && *idx == 0) {
1033                         struct cmsghdr *control;
1034
1035                         mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
1036                         mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
1037                         control->cmsg_level = SOL_SOCKET;
1038                         control->cmsg_type = SCM_RIGHTS;
1039                         memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
1040                 }
1041
1042                 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
1043                 if (k < 0 && errno == ENOTSOCK) {
1044                         bus->prefer_writev = true;
1045                         k = writev(bus->output_fd, iov, m->n_iovec);
1046                 }
1047         }
1048
1049         if (k < 0)
1050                 return errno == EAGAIN ? 0 : -errno;
1051
1052         *idx += (size_t) k;
1053         return 1;
1054 }
1055
1056 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
1057         uint32_t a, b;
1058         uint8_t e;
1059         uint64_t sum;
1060
1061         assert(bus);
1062         assert(need);
1063         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1064
1065         if (bus->rbuffer_size < sizeof(struct bus_header)) {
1066                 *need = sizeof(struct bus_header) + 8;
1067
1068                 /* Minimum message size:
1069                  *
1070                  * Header +
1071                  *
1072                  *  Method Call: +2 string headers
1073                  *       Signal: +3 string headers
1074                  * Method Error: +1 string headers
1075                  *               +1 uint32 headers
1076                  * Method Reply: +1 uint32 headers
1077                  *
1078                  * A string header is at least 9 bytes
1079                  * A uint32 header is at least 8 bytes
1080                  *
1081                  * Hence the minimum message size of a valid message
1082                  * is header + 8 bytes */
1083
1084                 return 0;
1085         }
1086
1087         a = ((const uint32_t*) bus->rbuffer)[1];
1088         b = ((const uint32_t*) bus->rbuffer)[3];
1089
1090         e = ((const uint8_t*) bus->rbuffer)[0];
1091         if (e == BUS_LITTLE_ENDIAN) {
1092                 a = le32toh(a);
1093                 b = le32toh(b);
1094         } else if (e == BUS_BIG_ENDIAN) {
1095                 a = be32toh(a);
1096                 b = be32toh(b);
1097         } else
1098                 return -EBADMSG;
1099
1100         sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
1101         if (sum >= BUS_MESSAGE_SIZE_MAX)
1102                 return -ENOBUFS;
1103
1104         *need = (size_t) sum;
1105         return 0;
1106 }
1107
1108 static int bus_socket_make_message(sd_bus *bus, size_t size) {
1109         sd_bus_message *t;
1110         void *b;
1111         int r;
1112
1113         assert(bus);
1114         assert(bus->rbuffer_size >= size);
1115         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1116
1117         r = bus_rqueue_make_room(bus);
1118         if (r < 0)
1119                 return r;
1120
1121         if (bus->rbuffer_size > size) {
1122                 b = memdup((const uint8_t*) bus->rbuffer + size,
1123                            bus->rbuffer_size - size);
1124                 if (!b)
1125                         return -ENOMEM;
1126         } else
1127                 b = NULL;
1128
1129         r = bus_message_from_malloc(bus,
1130                                     bus->rbuffer, size,
1131                                     bus->fds, bus->n_fds,
1132                                     NULL,
1133                                     &t);
1134         if (r < 0) {
1135                 free(b);
1136                 return r;
1137         }
1138
1139         bus->rbuffer = b;
1140         bus->rbuffer_size -= size;
1141
1142         bus->fds = NULL;
1143         bus->n_fds = 0;
1144
1145         bus->rqueue[bus->rqueue_size++] = t;
1146
1147         return 1;
1148 }
1149
1150 int bus_socket_read_message(sd_bus *bus) {
1151         struct msghdr mh;
1152         struct iovec iov = {};
1153         ssize_t k;
1154         size_t need;
1155         int r;
1156         void *b;
1157         union {
1158                 struct cmsghdr cmsghdr;
1159                 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
1160         } control;
1161         bool handle_cmsg = false;
1162
1163         assert(bus);
1164         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1165
1166         r = bus_socket_read_message_need(bus, &need);
1167         if (r < 0)
1168                 return r;
1169
1170         if (bus->rbuffer_size >= need)
1171                 return bus_socket_make_message(bus, need);
1172
1173         b = realloc(bus->rbuffer, need);
1174         if (!b)
1175                 return -ENOMEM;
1176
1177         bus->rbuffer = b;
1178
1179         iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
1180         iov.iov_len = need - bus->rbuffer_size;
1181
1182         if (bus->prefer_readv)
1183                 k = readv(bus->input_fd, &iov, 1);
1184         else {
1185                 zero(mh);
1186                 mh.msg_iov = &iov;
1187                 mh.msg_iovlen = 1;
1188                 mh.msg_control = &control;
1189                 mh.msg_controllen = sizeof(control);
1190
1191                 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
1192                 if (k < 0 && errno == ENOTSOCK) {
1193                         bus->prefer_readv = true;
1194                         k = readv(bus->input_fd, &iov, 1);
1195                 } else
1196                         handle_cmsg = true;
1197         }
1198         if (k < 0)
1199                 return errno == EAGAIN ? 0 : -errno;
1200         if (k == 0)
1201                 return -ECONNRESET;
1202
1203         bus->rbuffer_size += k;
1204
1205         if (handle_cmsg) {
1206                 struct cmsghdr *cmsg;
1207
1208                 CMSG_FOREACH(cmsg, &mh)
1209                         if (cmsg->cmsg_level == SOL_SOCKET &&
1210                             cmsg->cmsg_type == SCM_RIGHTS) {
1211                                 int n, *f;
1212
1213                                 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1214
1215                                 if (!bus->can_fds) {
1216                                         /* Whut? We received fds but this
1217                                          * isn't actually enabled? Close them,
1218                                          * and fail */
1219
1220                                         close_many((int*) CMSG_DATA(cmsg), n);
1221                                         return -EIO;
1222                                 }
1223
1224                                 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
1225                                 if (!f) {
1226                                         close_many((int*) CMSG_DATA(cmsg), n);
1227                                         return -ENOMEM;
1228                                 }
1229
1230                                 memcpy_safe(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
1231                                 bus->fds = f;
1232                                 bus->n_fds += n;
1233                         } else
1234                                 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1235                                           cmsg->cmsg_level, cmsg->cmsg_type);
1236         }
1237
1238         r = bus_socket_read_message_need(bus, &need);
1239         if (r < 0)
1240                 return r;
1241
1242         if (bus->rbuffer_size >= need)
1243                 return bus_socket_make_message(bus, need);
1244
1245         return 1;
1246 }
1247
1248 int bus_socket_process_opening(sd_bus *b) {
1249         int error = 0;
1250         socklen_t slen = sizeof(error);
1251         struct pollfd p = {
1252                 .fd = b->output_fd,
1253                 .events = POLLOUT,
1254         };
1255         int r;
1256
1257         assert(b->state == BUS_OPENING);
1258
1259         r = poll(&p, 1, 0);
1260         if (r < 0)
1261                 return -errno;
1262
1263         if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1264                 return 0;
1265
1266         r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1267         if (r < 0)
1268                 b->last_connect_error = errno;
1269         else if (error != 0)
1270                 b->last_connect_error = error;
1271         else if (p.revents & (POLLERR|POLLHUP))
1272                 b->last_connect_error = ECONNREFUSED;
1273         else
1274                 return bus_socket_start_auth(b);
1275
1276         return bus_next_address(b);
1277 }
1278
1279 int bus_socket_process_authenticating(sd_bus *b) {
1280         int r;
1281
1282         assert(b);
1283         assert(b->state == BUS_AUTHENTICATING);
1284
1285         if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1286                 return -ETIMEDOUT;
1287
1288         r = bus_socket_write_auth(b);
1289         if (r != 0)
1290                 return r;
1291
1292         return bus_socket_read_auth(b);
1293 }
1294
1295 int bus_socket_process_watch_bind(sd_bus *b) {
1296         int r, q;
1297
1298         assert(b);
1299         assert(b->state == BUS_WATCH_BIND);
1300         assert(b->inotify_fd >= 0);
1301
1302         r = flush_fd(b->inotify_fd);
1303         if (r <= 0)
1304                 return r;
1305
1306         log_debug("Got inotify event on bus %s.", strna(b->description));
1307
1308         /* We flushed events out of the inotify fd. In that case, maybe the socket is valid now? Let's try to connect
1309          * to it again */
1310
1311         r = bus_socket_connect(b);
1312         if (r < 0)
1313                 return r;
1314
1315         q = bus_attach_io_events(b);
1316         if (q < 0)
1317                 return q;
1318
1319         q = bus_attach_inotify_event(b);
1320         if (q < 0)
1321                 return q;
1322
1323         return r;
1324 }