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