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