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