chiark / gitweb /
pam_elogind compiling
[elogind.git] / src / libsystemd / sd-bus / bus-kernel.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #ifdef HAVE_VALGRIND_MEMCHECK_H
23 #include <valgrind/memcheck.h>
24 #endif
25
26 #include <fcntl.h>
27 #include <malloc.h>
28 #include <sys/mman.h>
29 #include <sys/prctl.h>
30
31 /* When we include libgen.h because we need dirname() we immediately
32  * undefine basename() since libgen.h defines it as a macro to the XDG
33  * version which is really broken. */
34 #include <libgen.h>
35 #undef basename
36
37 #include "util.h"
38 #include "strv.h"
39 #include "memfd-util.h"
40 #include "capability.h"
41 #include "fileio.h"
42
43 #include "bus-internal.h"
44 #include "bus-message.h"
45 #include "bus-kernel.h"
46 #include "bus-bloom.h"
47 #include "bus-util.h"
48 #include "bus-label.h"
49
50 #define UNIQUE_NAME_MAX (3+DECIMAL_STR_MAX(uint64_t))
51
52 int bus_kernel_parse_unique_name(const char *s, uint64_t *id) {
53         int r;
54
55         assert(s);
56         assert(id);
57
58         if (!startswith(s, ":1."))
59                 return 0;
60
61         r = safe_atou64(s + 3, id);
62         if (r < 0)
63                 return r;
64
65         return 1;
66 }
67
68 static void append_payload_vec(struct kdbus_item **d, const void *p, size_t sz) {
69         assert(d);
70         assert(sz > 0);
71
72         *d = ALIGN8_PTR(*d);
73
74         /* Note that p can be NULL, which encodes a region full of
75          * zeroes, which is useful to optimize certain padding
76          * conditions */
77
78         (*d)->size = offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec);
79         (*d)->type = KDBUS_ITEM_PAYLOAD_VEC;
80         (*d)->vec.address = PTR_TO_UINT64(p);
81         (*d)->vec.size = sz;
82
83         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
84 }
85
86 static void append_payload_memfd(struct kdbus_item **d, int memfd, size_t start, size_t sz) {
87         assert(d);
88         assert(memfd >= 0);
89         assert(sz > 0);
90
91         *d = ALIGN8_PTR(*d);
92         (*d)->size = offsetof(struct kdbus_item, memfd) + sizeof(struct kdbus_memfd);
93         (*d)->type = KDBUS_ITEM_PAYLOAD_MEMFD;
94         (*d)->memfd.fd = memfd;
95         (*d)->memfd.start = start;
96         (*d)->memfd.size = sz;
97
98         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
99 }
100
101 static void append_destination(struct kdbus_item **d, const char *s, size_t length) {
102         assert(d);
103         assert(s);
104
105         *d = ALIGN8_PTR(*d);
106
107         (*d)->size = offsetof(struct kdbus_item, str) + length + 1;
108         (*d)->type = KDBUS_ITEM_DST_NAME;
109         memcpy((*d)->str, s, length + 1);
110
111         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
112 }
113
114 static struct kdbus_bloom_filter *append_bloom(struct kdbus_item **d, size_t length) {
115         struct kdbus_item *i;
116
117         assert(d);
118
119         i = ALIGN8_PTR(*d);
120
121         i->size = offsetof(struct kdbus_item, bloom_filter) +
122                   offsetof(struct kdbus_bloom_filter, data) +
123                   length;
124         i->type = KDBUS_ITEM_BLOOM_FILTER;
125
126         *d = (struct kdbus_item *) ((uint8_t*) i + i->size);
127
128         return &i->bloom_filter;
129 }
130
131 static void append_fds(struct kdbus_item **d, const int fds[], unsigned n_fds) {
132         assert(d);
133         assert(fds);
134         assert(n_fds > 0);
135
136         *d = ALIGN8_PTR(*d);
137         (*d)->size = offsetof(struct kdbus_item, fds) + sizeof(int) * n_fds;
138         (*d)->type = KDBUS_ITEM_FDS;
139         memcpy((*d)->fds, fds, sizeof(int) * n_fds);
140
141         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
142 }
143
144 static void add_bloom_arg(void *data, size_t size, unsigned n_hash, unsigned i, const char *t) {
145         char buf[sizeof("arg")-1 + 2 + sizeof("-slash-prefix")];
146         char *e;
147
148         assert(data);
149         assert(size > 0);
150         assert(i < 64);
151         assert(t);
152
153         e = stpcpy(buf, "arg");
154         if (i < 10)
155                 *(e++) = '0' + (char) i;
156         else {
157                 *(e++) = '0' + (char) (i / 10);
158                 *(e++) = '0' + (char) (i % 10);
159         }
160
161         *e = 0;
162         bloom_add_pair(data, size, n_hash, buf, t);
163
164         strcpy(e, "-dot-prefix");
165         bloom_add_prefixes(data, size, n_hash, buf, t, '.');
166         strcpy(e, "-slash-prefix");
167         bloom_add_prefixes(data, size, n_hash, buf, t, '/');
168 }
169
170 static int bus_message_setup_bloom(sd_bus_message *m, struct kdbus_bloom_filter *bloom) {
171         void *data;
172         unsigned i;
173         int r;
174
175         assert(m);
176         assert(bloom);
177
178         data = bloom->data;
179         memzero(data, m->bus->bloom_size);
180         bloom->generation = 0;
181
182         bloom_add_pair(data, m->bus->bloom_size, m->bus->bloom_n_hash, "message-type", bus_message_type_to_string(m->header->type));
183
184         if (m->interface)
185                 bloom_add_pair(data, m->bus->bloom_size, m->bus->bloom_n_hash, "interface", m->interface);
186         if (m->member)
187                 bloom_add_pair(data, m->bus->bloom_size, m->bus->bloom_n_hash, "member", m->member);
188         if (m->path) {
189                 bloom_add_pair(data, m->bus->bloom_size, m->bus->bloom_n_hash, "path", m->path);
190                 bloom_add_pair(data, m->bus->bloom_size, m->bus->bloom_n_hash, "path-slash-prefix", m->path);
191                 bloom_add_prefixes(data, m->bus->bloom_size, m->bus->bloom_n_hash, "path-slash-prefix", m->path, '/');
192         }
193
194         r = sd_bus_message_rewind(m, true);
195         if (r < 0)
196                 return r;
197
198         for (i = 0; i < 64; i++) {
199                 const char *t, *contents;
200                 char type;
201
202                 r = sd_bus_message_peek_type(m, &type, &contents);
203                 if (r < 0)
204                         return r;
205
206                 if (IN_SET(type, SD_BUS_TYPE_STRING, SD_BUS_TYPE_OBJECT_PATH, SD_BUS_TYPE_SIGNATURE)) {
207
208                         /* The bloom filter includes simple strings of any kind */
209                         r = sd_bus_message_read_basic(m, type, &t);
210                         if (r < 0)
211                                 return r;
212
213                         add_bloom_arg(data, m->bus->bloom_size, m->bus->bloom_n_hash, i, t);
214                 } if (type == SD_BUS_TYPE_ARRAY && STR_IN_SET(contents, "s", "o", "g")) {
215
216                         /* As well as array of simple strings of any kinds */
217                         r = sd_bus_message_enter_container(m, type, contents);
218                         if (r < 0)
219                                 return r;
220
221                         while ((r = sd_bus_message_read_basic(m, contents[0], &t)) > 0)
222                                 add_bloom_arg(data, m->bus->bloom_size, m->bus->bloom_n_hash, i, t);
223                         if (r < 0)
224                                 return r;
225
226                         r = sd_bus_message_exit_container(m);
227                         if (r < 0)
228                                 return r;
229
230                 } else
231                         /* Stop adding to bloom filter as soon as we
232                          * run into the first argument we cannot add
233                          * to it. */
234                         break;
235         }
236
237         return 0;
238 }
239
240 static int bus_message_setup_kmsg(sd_bus *b, sd_bus_message *m) {
241         struct bus_body_part *part;
242         struct kdbus_item *d;
243         const char *destination;
244         bool well_known;
245         uint64_t unique;
246         size_t sz, dl;
247         unsigned i;
248         int r;
249
250         assert(b);
251         assert(m);
252         assert(m->sealed);
253
254         /* We put this together only once, if this message is reused
255          * we reuse the earlier-built version */
256         if (m->kdbus)
257                 return 0;
258
259         destination = m->destination ?: m->destination_ptr;
260
261         if (destination) {
262                 r = bus_kernel_parse_unique_name(destination, &unique);
263                 if (r < 0)
264                         return r;
265
266                 well_known = r == 0;
267         } else
268                 well_known = false;
269
270         sz = offsetof(struct kdbus_msg, items);
271
272         /* Add in fixed header, fields header and payload */
273         sz += (1 + m->n_body_parts) * ALIGN8(offsetof(struct kdbus_item, vec) +
274                                              MAX(sizeof(struct kdbus_vec),
275                                                  sizeof(struct kdbus_memfd)));
276
277         /* Add space for bloom filter */
278         sz += ALIGN8(offsetof(struct kdbus_item, bloom_filter) +
279                      offsetof(struct kdbus_bloom_filter, data) +
280                      m->bus->bloom_size);
281
282         /* Add in well-known destination header */
283         if (well_known) {
284                 dl = strlen(destination);
285                 sz += ALIGN8(offsetof(struct kdbus_item, str) + dl + 1);
286         }
287
288         /* Add space for unix fds */
289         if (m->n_fds > 0)
290                 sz += ALIGN8(offsetof(struct kdbus_item, fds) + sizeof(int)*m->n_fds);
291
292         m->kdbus = memalign(8, sz);
293         if (!m->kdbus) {
294                 r = -ENOMEM;
295                 goto fail;
296         }
297
298         m->free_kdbus = true;
299         memzero(m->kdbus, sz);
300
301         m->kdbus->flags =
302                 ((m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED) ? 0 : KDBUS_MSG_EXPECT_REPLY) |
303                 ((m->header->flags & BUS_MESSAGE_NO_AUTO_START) ? KDBUS_MSG_NO_AUTO_START : 0) |
304                 ((m->header->type == SD_BUS_MESSAGE_SIGNAL) ? KDBUS_MSG_SIGNAL : 0);
305
306         if (well_known)
307                 /* verify_destination_id will usually be 0, which makes the kernel driver only look
308                  * at the provided well-known name. Otherwise, the kernel will make sure the provided
309                  * destination id matches the owner of the provided weel-known-name, and fail if they
310                  * differ. Currently, this is only needed for bus-proxyd. */
311                 m->kdbus->dst_id = m->verify_destination_id;
312         else
313                 m->kdbus->dst_id = destination ? unique : KDBUS_DST_ID_BROADCAST;
314
315         m->kdbus->payload_type = KDBUS_PAYLOAD_DBUS;
316         m->kdbus->cookie = m->header->dbus2.cookie;
317         m->kdbus->priority = m->priority;
318
319         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
320                 m->kdbus->cookie_reply = m->reply_cookie;
321         else {
322                 struct timespec now;
323
324                 assert_se(clock_gettime(CLOCK_MONOTONIC_COARSE, &now) == 0);
325                 m->kdbus->timeout_ns = now.tv_sec * NSEC_PER_SEC + now.tv_nsec +
326                                        m->timeout * NSEC_PER_USEC;
327         }
328
329         d = m->kdbus->items;
330
331         if (well_known)
332                 append_destination(&d, destination, dl);
333
334         append_payload_vec(&d, m->header, BUS_MESSAGE_BODY_BEGIN(m));
335
336         MESSAGE_FOREACH_PART(part, i, m) {
337                 if (part->is_zero) {
338                         /* If this is padding then simply send a
339                          * vector with a NULL data pointer which the
340                          * kernel will just pass through. This is the
341                          * most efficient way to encode zeroes */
342
343                         append_payload_vec(&d, NULL, part->size);
344                         continue;
345                 }
346
347                 if (part->memfd >= 0 && part->sealed && destination) {
348                         /* Try to send a memfd, if the part is
349                          * sealed and this is not a broadcast. Since we can only  */
350
351                         append_payload_memfd(&d, part->memfd, part->memfd_offset, part->size);
352                         continue;
353                 }
354
355                 /* Otherwise, let's send a vector to the actual data.
356                  * For that, we need to map it first. */
357                 r = bus_body_part_map(part);
358                 if (r < 0)
359                         goto fail;
360
361                 append_payload_vec(&d, part->data, part->size);
362         }
363
364         if (m->header->type == SD_BUS_MESSAGE_SIGNAL) {
365                 struct kdbus_bloom_filter *bloom;
366
367                 bloom = append_bloom(&d, m->bus->bloom_size);
368                 r = bus_message_setup_bloom(m, bloom);
369                 if (r < 0)
370                         goto fail;
371         }
372
373         if (m->n_fds > 0)
374                 append_fds(&d, m->fds, m->n_fds);
375
376         m->kdbus->size = (uint8_t*) d - (uint8_t*) m->kdbus;
377         assert(m->kdbus->size <= sz);
378
379         return 0;
380
381 fail:
382         m->poisoned = true;
383         return r;
384 }
385
386 static void unset_memfds(struct sd_bus_message *m) {
387         struct bus_body_part *part;
388         unsigned i;
389
390         assert(m);
391
392         /* Make sure the memfds are not freed twice */
393         MESSAGE_FOREACH_PART(part, i, m)
394                 if (part->memfd >= 0)
395                         part->memfd = -1;
396 }
397
398 static void message_set_timestamp(sd_bus *bus, sd_bus_message *m, const struct kdbus_timestamp *ts) {
399         assert(bus);
400         assert(m);
401
402         if (!ts)
403                 return;
404
405         if (!(bus->attach_flags & KDBUS_ATTACH_TIMESTAMP))
406                 return;
407
408         m->realtime = ts->realtime_ns / NSEC_PER_USEC;
409         m->monotonic = ts->monotonic_ns / NSEC_PER_USEC;
410         m->seqnum = ts->seqnum;
411 }
412
413 static int bus_kernel_make_message(sd_bus *bus, struct kdbus_msg *k) {
414         sd_bus_message *m = NULL;
415         struct kdbus_item *d;
416         unsigned n_fds = 0;
417         _cleanup_free_ int *fds = NULL;
418         struct bus_header *header = NULL;
419         void *footer = NULL;
420         size_t header_size = 0, footer_size = 0;
421         size_t n_bytes = 0, idx = 0;
422         const char *destination = NULL, *seclabel = NULL;
423         bool last_was_memfd = false;
424         int r;
425
426         assert(bus);
427         assert(k);
428         assert(k->payload_type == KDBUS_PAYLOAD_DBUS);
429
430         KDBUS_ITEM_FOREACH(d, k, items) {
431                 size_t l;
432
433                 l = d->size - offsetof(struct kdbus_item, data);
434
435                 switch (d->type) {
436
437                 case KDBUS_ITEM_PAYLOAD_OFF:
438                         if (!header) {
439                                 header = (struct bus_header*)((uint8_t*) k + d->vec.offset);
440                                 header_size = d->vec.size;
441                         }
442
443                         footer = (uint8_t*) k + d->vec.offset;
444                         footer_size = d->vec.size;
445
446                         n_bytes += d->vec.size;
447                         last_was_memfd = false;
448                         break;
449
450                 case KDBUS_ITEM_PAYLOAD_MEMFD:
451                         if (!header) /* memfd cannot be first part */
452                                 return -EBADMSG;
453
454                         n_bytes += d->memfd.size;
455                         last_was_memfd = true;
456                         break;
457
458                 case KDBUS_ITEM_FDS: {
459                         int *f;
460                         unsigned j;
461
462                         j = l / sizeof(int);
463                         f = realloc(fds, sizeof(int) * (n_fds + j));
464                         if (!f)
465                                 return -ENOMEM;
466
467                         fds = f;
468                         memcpy(fds + n_fds, d->fds, sizeof(int) * j);
469                         n_fds += j;
470                         break;
471                 }
472
473                 case KDBUS_ITEM_SECLABEL:
474                         seclabel = d->str;
475                         break;
476                 }
477         }
478
479         if (last_was_memfd) /* memfd cannot be last part */
480                 return -EBADMSG;
481
482         if (!header)
483                 return -EBADMSG;
484
485         if (header_size < sizeof(struct bus_header))
486                 return -EBADMSG;
487
488         /* on kdbus we only speak native endian gvariant, never dbus1
489          * marshalling or reverse endian */
490         if (header->version != 2 ||
491             header->endian != BUS_NATIVE_ENDIAN)
492                 return -EPROTOTYPE;
493
494         r = bus_message_from_header(
495                         bus,
496                         header, header_size,
497                         footer, footer_size,
498                         n_bytes,
499                         fds, n_fds,
500                         NULL,
501                         seclabel, 0, &m);
502         if (r < 0)
503                 return r;
504
505         /* The well-known names list is different from the other
506         credentials. If we asked for it, but nothing is there, this
507         means that the list of well-known names is simply empty, not
508         that we lack any data */
509
510         m->creds.mask |= (SD_BUS_CREDS_UNIQUE_NAME|SD_BUS_CREDS_WELL_KNOWN_NAMES) & bus->creds_mask;
511
512         KDBUS_ITEM_FOREACH(d, k, items) {
513                 size_t l;
514
515                 l = d->size - offsetof(struct kdbus_item, data);
516
517                 switch (d->type) {
518
519                 case KDBUS_ITEM_PAYLOAD_OFF: {
520                         size_t begin_body;
521
522                         begin_body = BUS_MESSAGE_BODY_BEGIN(m);
523
524                         if (idx + d->vec.size > begin_body) {
525                                 struct bus_body_part *part;
526
527                                 /* Contains body material */
528
529                                 part = message_append_part(m);
530                                 if (!part) {
531                                         r = -ENOMEM;
532                                         goto fail;
533                                 }
534
535                                 /* A -1 offset is NUL padding. */
536                                 part->is_zero = d->vec.offset == ~0ULL;
537
538                                 if (idx >= begin_body) {
539                                         if (!part->is_zero)
540                                                 part->data = (uint8_t* )k + d->vec.offset;
541                                         part->size = d->vec.size;
542                                 } else {
543                                         if (!part->is_zero)
544                                                 part->data = (uint8_t*) k + d->vec.offset + (begin_body - idx);
545                                         part->size = d->vec.size - (begin_body - idx);
546                                 }
547
548                                 part->sealed = true;
549                         }
550
551                         idx += d->vec.size;
552                         break;
553                 }
554
555                 case KDBUS_ITEM_PAYLOAD_MEMFD: {
556                         struct bus_body_part *part;
557
558                         if (idx < BUS_MESSAGE_BODY_BEGIN(m)) {
559                                 r = -EBADMSG;
560                                 goto fail;
561                         }
562
563                         part = message_append_part(m);
564                         if (!part) {
565                                 r = -ENOMEM;
566                                 goto fail;
567                         }
568
569                         part->memfd = d->memfd.fd;
570                         part->memfd_offset = d->memfd.start;
571                         part->size = d->memfd.size;
572                         part->sealed = true;
573
574                         idx += d->memfd.size;
575                         break;
576                 }
577
578                 case KDBUS_ITEM_PIDS:
579
580                         /* The PID/TID might be missing, when the data
581                          * is faked by a bus proxy and it lacks that
582                          * information about the real client (since
583                          * SO_PEERCRED is used for that). Also kernel
584                          * namespacing might make some of this data
585                          * unavailable when untranslatable. */
586
587                         if (d->pids.pid > 0) {
588                                 m->creds.pid = (pid_t) d->pids.pid;
589                                 m->creds.mask |= SD_BUS_CREDS_PID & bus->creds_mask;
590                         }
591
592                         if (d->pids.tid > 0) {
593                                 m->creds.tid = (pid_t) d->pids.tid;
594                                 m->creds.mask |= SD_BUS_CREDS_TID & bus->creds_mask;
595                         }
596
597                         break;
598
599                 case KDBUS_ITEM_CREDS:
600
601                         /* EUID/SUID/FSUID/EGID/SGID/FSGID might be
602                          * missing too (see above). */
603
604                         if ((uid_t) d->creds.uid != UID_INVALID) {
605                                 m->creds.uid = (uid_t) d->creds.uid;
606                                 m->creds.mask |= SD_BUS_CREDS_UID & bus->creds_mask;
607                         }
608
609                         if ((uid_t) d->creds.euid != UID_INVALID) {
610                                 m->creds.euid = (uid_t) d->creds.euid;
611                                 m->creds.mask |= SD_BUS_CREDS_EUID & bus->creds_mask;
612                         }
613
614                         if ((uid_t) d->creds.suid != UID_INVALID) {
615                                 m->creds.suid = (uid_t) d->creds.suid;
616                                 m->creds.mask |= SD_BUS_CREDS_SUID & bus->creds_mask;
617                         }
618
619                         if ((uid_t) d->creds.fsuid != UID_INVALID) {
620                                 m->creds.fsuid = (uid_t) d->creds.fsuid;
621                                 m->creds.mask |= SD_BUS_CREDS_FSUID & bus->creds_mask;
622                         }
623
624                         if ((gid_t) d->creds.gid != GID_INVALID) {
625                                 m->creds.gid = (gid_t) d->creds.gid;
626                                 m->creds.mask |= SD_BUS_CREDS_GID & bus->creds_mask;
627                         }
628
629                         if ((gid_t) d->creds.egid != GID_INVALID) {
630                                 m->creds.egid = (gid_t) d->creds.egid;
631                                 m->creds.mask |= SD_BUS_CREDS_EGID & bus->creds_mask;
632                         }
633
634                         if ((gid_t) d->creds.sgid != GID_INVALID) {
635                                 m->creds.sgid = (gid_t) d->creds.sgid;
636                                 m->creds.mask |= SD_BUS_CREDS_SGID & bus->creds_mask;
637                         }
638
639                         if ((gid_t) d->creds.fsgid != GID_INVALID) {
640                                 m->creds.fsgid = (gid_t) d->creds.fsgid;
641                                 m->creds.mask |= SD_BUS_CREDS_FSGID & bus->creds_mask;
642                         }
643
644                         break;
645
646                 case KDBUS_ITEM_TIMESTAMP:
647                         message_set_timestamp(bus, m, &d->timestamp);
648                         break;
649
650                 case KDBUS_ITEM_PID_COMM:
651                         m->creds.comm = d->str;
652                         m->creds.mask |= SD_BUS_CREDS_COMM & bus->creds_mask;
653                         break;
654
655                 case KDBUS_ITEM_TID_COMM:
656                         m->creds.tid_comm = d->str;
657                         m->creds.mask |= SD_BUS_CREDS_TID_COMM & bus->creds_mask;
658                         break;
659
660                 case KDBUS_ITEM_EXE:
661                         m->creds.exe = d->str;
662                         m->creds.mask |= SD_BUS_CREDS_EXE & bus->creds_mask;
663                         break;
664
665                 case KDBUS_ITEM_CMDLINE:
666                         m->creds.cmdline = d->str;
667                         m->creds.cmdline_size = l;
668                         m->creds.mask |= SD_BUS_CREDS_CMDLINE & bus->creds_mask;
669                         break;
670
671                 case KDBUS_ITEM_CGROUP:
672                         m->creds.cgroup = d->str;
673                         m->creds.mask |= (SD_BUS_CREDS_CGROUP|SD_BUS_CREDS_UNIT|SD_BUS_CREDS_USER_UNIT|SD_BUS_CREDS_SLICE|SD_BUS_CREDS_SESSION|SD_BUS_CREDS_OWNER_UID) & bus->creds_mask;
674
675                         r = bus_get_root_path(bus);
676                         if (r < 0)
677                                 goto fail;
678
679                         m->creds.cgroup_root = bus->cgroup_root;
680                         break;
681
682                 case KDBUS_ITEM_AUDIT:
683                         if ((uint32_t) d->audit.sessionid != (uint32_t) -1) {
684                                 m->creds.audit_session_id = (uint32_t) d->audit.sessionid;
685                                 m->creds.mask |= SD_BUS_CREDS_AUDIT_SESSION_ID & bus->creds_mask;
686                         }
687
688                         if ((uid_t) d->audit.loginuid != UID_INVALID) {
689                                 m->creds.audit_login_uid = (uid_t) d->audit.loginuid;
690                                 m->creds.mask |= SD_BUS_CREDS_AUDIT_LOGIN_UID & bus->creds_mask;
691                         }
692                         break;
693
694                 case KDBUS_ITEM_CAPS:
695                         if (d->caps.last_cap != cap_last_cap() ||
696                             d->size - offsetof(struct kdbus_item, caps.caps) < DIV_ROUND_UP(d->caps.last_cap, 32U) * 4 * 4) {
697                                 r = -EBADMSG;
698                                 goto fail;
699                         }
700
701                         m->creds.capability = d->caps.caps;
702                         m->creds.mask |= (SD_BUS_CREDS_EFFECTIVE_CAPS|SD_BUS_CREDS_PERMITTED_CAPS|SD_BUS_CREDS_INHERITABLE_CAPS|SD_BUS_CREDS_BOUNDING_CAPS) & bus->creds_mask;
703                         break;
704
705                 case KDBUS_ITEM_DST_NAME:
706                         if (!service_name_is_valid(d->str)) {
707                                 r = -EBADMSG;
708                                 goto fail;
709                         }
710
711                         destination = d->str;
712                         break;
713
714                 case KDBUS_ITEM_OWNED_NAME:
715                         if (!service_name_is_valid(d->name.name)) {
716                                 r = -EBADMSG;
717                                 goto fail;
718                         }
719
720                         if (bus->creds_mask & SD_BUS_CREDS_WELL_KNOWN_NAMES) {
721                                 char **wkn;
722                                 size_t n;
723
724                                 /* We just extend the array here, but
725                                  * do not allocate the strings inside
726                                  * of it, instead we just point to our
727                                  * buffer directly. */
728                                 n = strv_length(m->creds.well_known_names);
729                                 wkn = realloc(m->creds.well_known_names, (n + 2) * sizeof(char*));
730                                 if (!wkn) {
731                                         r = -ENOMEM;
732                                         goto fail;
733                                 }
734
735                                 wkn[n] = d->name.name;
736                                 wkn[n+1] = NULL;
737                                 m->creds.well_known_names = wkn;
738
739                                 m->creds.mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES;
740                         }
741                         break;
742
743                 case KDBUS_ITEM_CONN_DESCRIPTION:
744                         m->creds.description = d->str;
745                         m->creds.mask |= SD_BUS_CREDS_DESCRIPTION & bus->creds_mask;
746                         break;
747
748                 case KDBUS_ITEM_AUXGROUPS:
749
750                         if (bus->creds_mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) {
751                                 size_t i, n;
752                                 gid_t *g;
753
754                                 n = (d->size - offsetof(struct kdbus_item, data64)) / sizeof(uint64_t);
755                                 g = new(gid_t, n);
756                                 if (!g) {
757                                         r = -ENOMEM;
758                                         goto fail;
759                                 }
760
761                                 for (i = 0; i < n; i++)
762                                         g[i] = d->data64[i];
763
764                                 m->creds.supplementary_gids = g;
765                                 m->creds.n_supplementary_gids = n;
766                                 m->creds.mask |= SD_BUS_CREDS_SUPPLEMENTARY_GIDS;
767                         }
768
769                         break;
770
771                 case KDBUS_ITEM_FDS:
772                 case KDBUS_ITEM_SECLABEL:
773                         break;
774
775                 default:
776                         log_debug("Got unknown field from kernel %llu", d->type);
777                 }
778         }
779
780         /* If we requested the list of well-known names to be appended
781          * and the sender had none no item for it will be
782          * attached. However, this does *not* mean that the kernel
783          * didn't want to provide this information to us. Hence, let's
784          * explicitly mark this information as available if it was
785          * requested. */
786         m->creds.mask |= bus->creds_mask & SD_BUS_CREDS_WELL_KNOWN_NAMES;
787
788         r = bus_message_parse_fields(m);
789         if (r < 0)
790                 goto fail;
791
792         /* Refuse messages if kdbus and dbus1 cookie doesn't match up */
793         if ((uint64_t) m->header->dbus2.cookie != k->cookie) {
794                 r = -EBADMSG;
795                 goto fail;
796         }
797
798         /* Refuse messages where the reply flag doesn't match up */
799         if (!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED) != !!(k->flags & KDBUS_MSG_EXPECT_REPLY)) {
800                 r = -EBADMSG;
801                 goto fail;
802         }
803
804         /* Refuse reply messages where the reply cookie doesn't match up */
805         if ((m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED) && m->reply_cookie != k->cookie_reply) {
806                 r = -EBADMSG;
807                 goto fail;
808         }
809
810         /* Refuse messages where the autostart flag doesn't match up */
811         if (!(m->header->flags & BUS_MESSAGE_NO_AUTO_START) != !(k->flags & KDBUS_MSG_NO_AUTO_START)) {
812                 r = -EBADMSG;
813                 goto fail;
814         }
815
816         /* Override information from the user header with data from the kernel */
817         if (k->src_id == KDBUS_SRC_ID_KERNEL)
818                 bus_message_set_sender_driver(bus, m);
819         else {
820                 snprintf(m->sender_buffer, sizeof(m->sender_buffer), ":1.%llu", (unsigned long long) k->src_id);
821                 m->sender = m->creds.unique_name = m->sender_buffer;
822         }
823
824         if (destination)
825                 m->destination = destination;
826         else if (k->dst_id == KDBUS_DST_ID_BROADCAST)
827                 m->destination = NULL;
828         else if (k->dst_id == KDBUS_DST_ID_NAME)
829                 m->destination = bus->unique_name; /* fill in unique name if the well-known name is missing */
830         else {
831                 snprintf(m->destination_buffer, sizeof(m->destination_buffer), ":1.%llu", (unsigned long long) k->dst_id);
832                 m->destination = m->destination_buffer;
833         }
834
835         /* We take possession of the kmsg struct now */
836         m->kdbus = k;
837         m->release_kdbus = true;
838         m->free_fds = true;
839         fds = NULL;
840
841         bus->rqueue[bus->rqueue_size++] = m;
842
843         return 1;
844
845 fail:
846         unset_memfds(m);
847         sd_bus_message_unref(m);
848
849         return r;
850 }
851
852 int bus_kernel_take_fd(sd_bus *b) {
853         struct kdbus_bloom_parameter *bloom = NULL;
854         struct kdbus_item *items, *item;
855         struct kdbus_cmd_hello *hello;
856         _cleanup_free_ char *g = NULL;
857         const char *name;
858         size_t l = 0, m = 0, sz;
859         int r;
860
861         assert(b);
862
863         if (b->is_server)
864                 return -EINVAL;
865
866         b->use_memfd = 1;
867
868         if (b->description) {
869                 g = bus_label_escape(b->description);
870                 if (!g)
871                         return -ENOMEM;
872
873                 name = g;
874         } else {
875                 char pr[17] = {};
876
877                 /* If no name is explicitly set, we'll include a hint
878                  * indicating the library implementation, a hint which
879                  * kind of bus this is and the thread name */
880
881                 assert_se(prctl(PR_GET_NAME, (unsigned long) pr) >= 0);
882
883                 if (isempty(pr)) {
884                         name = b->is_system ? "sd-system" :
885                                 b->is_user ? "sd-user" : "sd";
886                 } else {
887                         _cleanup_free_ char *e = NULL;
888
889                         e = bus_label_escape(pr);
890                         if (!e)
891                                 return -ENOMEM;
892
893                         g = strappend(b->is_system ? "sd-system-" :
894                                       b->is_user ? "sd-user-" : "sd-",
895                                       e);
896                         if (!g)
897                                 return -ENOMEM;
898
899                         name = g;
900                 }
901
902                 b->description = bus_label_unescape(name);
903                 if (!b->description)
904                         return -ENOMEM;
905         }
906
907         m = strlen(name);
908
909         sz = ALIGN8(offsetof(struct kdbus_cmd_hello, items)) +
910                 ALIGN8(offsetof(struct kdbus_item, str) + m + 1);
911
912         if (b->fake_creds_valid)
913                 sz += ALIGN8(offsetof(struct kdbus_item, creds) + sizeof(struct kdbus_creds));
914
915         if (b->fake_pids_valid)
916                 sz += ALIGN8(offsetof(struct kdbus_item, pids) + sizeof(struct kdbus_pids));
917
918         if (b->fake_label) {
919                 l = strlen(b->fake_label);
920                 sz += ALIGN8(offsetof(struct kdbus_item, str) + l + 1);
921         }
922
923         hello = alloca0_align(sz, 8);
924         hello->size = sz;
925         hello->flags = b->hello_flags;
926         hello->attach_flags_send = _KDBUS_ATTACH_ANY;
927         hello->attach_flags_recv = b->attach_flags;
928         hello->pool_size = KDBUS_POOL_SIZE;
929
930         item = hello->items;
931
932         item->size = offsetof(struct kdbus_item, str) + m + 1;
933         item->type = KDBUS_ITEM_CONN_DESCRIPTION;
934         memcpy(item->str, name, m + 1);
935         item = KDBUS_ITEM_NEXT(item);
936
937         if (b->fake_creds_valid) {
938                 item->size = offsetof(struct kdbus_item, creds) + sizeof(struct kdbus_creds);
939                 item->type = KDBUS_ITEM_CREDS;
940                 item->creds = b->fake_creds;
941
942                 item = KDBUS_ITEM_NEXT(item);
943         }
944
945         if (b->fake_pids_valid) {
946                 item->size = offsetof(struct kdbus_item, pids) + sizeof(struct kdbus_pids);
947                 item->type = KDBUS_ITEM_PIDS;
948                 item->pids = b->fake_pids;
949
950                 item = KDBUS_ITEM_NEXT(item);
951         }
952
953         if (b->fake_label) {
954                 item->size = offsetof(struct kdbus_item, str) + l + 1;
955                 item->type = KDBUS_ITEM_SECLABEL;
956                 memcpy(item->str, b->fake_label, l+1);
957         }
958
959         r = ioctl(b->input_fd, KDBUS_CMD_HELLO, hello);
960         if (r < 0)
961                 return -errno;
962
963         if (!b->kdbus_buffer) {
964                 b->kdbus_buffer = mmap(NULL, KDBUS_POOL_SIZE, PROT_READ, MAP_SHARED, b->input_fd, 0);
965                 if (b->kdbus_buffer == MAP_FAILED) {
966                         b->kdbus_buffer = NULL;
967                         r = -errno;
968                         goto fail;
969                 }
970         }
971
972         /* The higher 32bit of the bus_flags fields are considered
973          * 'incompatible flags'. Refuse them all for now. */
974         if (hello->bus_flags > 0xFFFFFFFFULL) {
975                 r = -EOPNOTSUPP;
976                 goto fail;
977         }
978
979         /* extract bloom parameters from items */
980         items = (void*)((uint8_t*)b->kdbus_buffer + hello->offset);
981         KDBUS_FOREACH(item, items, hello->items_size) {
982                 switch (item->type) {
983                 case KDBUS_ITEM_BLOOM_PARAMETER:
984                         bloom = &item->bloom_parameter;
985                         break;
986                 }
987         }
988
989         if (!bloom || !bloom_validate_parameters((size_t) bloom->size, (unsigned) bloom->n_hash)) {
990                 r = -EOPNOTSUPP;
991                 goto fail;
992         }
993
994         b->bloom_size = (size_t) bloom->size;
995         b->bloom_n_hash = (unsigned) bloom->n_hash;
996
997         if (asprintf(&b->unique_name, ":1.%llu", (unsigned long long) hello->id) < 0) {
998                 r = -ENOMEM;
999                 goto fail;
1000         }
1001
1002         b->unique_id = hello->id;
1003
1004         b->is_kernel = true;
1005         b->bus_client = true;
1006         b->can_fds = !!(hello->flags & KDBUS_HELLO_ACCEPT_FD);
1007         b->message_version = 2;
1008         b->message_endian = BUS_NATIVE_ENDIAN;
1009
1010         /* the kernel told us the UUID of the underlying bus */
1011         memcpy(b->server_id.bytes, hello->id128, sizeof(b->server_id.bytes));
1012
1013         /* free returned items */
1014         (void) bus_kernel_cmd_free(b, hello->offset);
1015         return bus_start_running(b);
1016
1017 fail:
1018         (void) bus_kernel_cmd_free(b, hello->offset);
1019         return r;
1020 }
1021
1022 int bus_kernel_connect(sd_bus *b) {
1023         assert(b);
1024         assert(b->input_fd < 0);
1025         assert(b->output_fd < 0);
1026         assert(b->kernel);
1027
1028         if (b->is_server)
1029                 return -EINVAL;
1030
1031         b->input_fd = open(b->kernel, O_RDWR|O_NOCTTY|O_CLOEXEC);
1032         if (b->input_fd < 0)
1033                 return -errno;
1034
1035         b->output_fd = b->input_fd;
1036
1037         return bus_kernel_take_fd(b);
1038 }
1039
1040 int bus_kernel_cmd_free(sd_bus *bus, uint64_t offset) {
1041         struct kdbus_cmd_free cmd = {
1042                 .size = sizeof(cmd),
1043                 .offset = offset,
1044         };
1045         int r;
1046
1047         assert(bus);
1048         assert(bus->is_kernel);
1049
1050         r = ioctl(bus->input_fd, KDBUS_CMD_FREE, &cmd);
1051         if (r < 0)
1052                 return -errno;
1053
1054         return 0;
1055 }
1056
1057 static void close_kdbus_msg(sd_bus *bus, struct kdbus_msg *k) {
1058         struct kdbus_item *d;
1059
1060         assert(bus);
1061         assert(k);
1062
1063         KDBUS_ITEM_FOREACH(d, k, items) {
1064                 if (d->type == KDBUS_ITEM_FDS)
1065                         close_many(d->fds, (d->size - offsetof(struct kdbus_item, fds)) / sizeof(int));
1066                 else if (d->type == KDBUS_ITEM_PAYLOAD_MEMFD)
1067                         safe_close(d->memfd.fd);
1068         }
1069
1070         bus_kernel_cmd_free(bus, (uint8_t*) k - (uint8_t*) bus->kdbus_buffer);
1071 }
1072
1073 int bus_kernel_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call) {
1074         struct kdbus_cmd_send cmd = { };
1075         int r;
1076
1077         assert(bus);
1078         assert(m);
1079         assert(bus->state == BUS_RUNNING);
1080
1081         /* If we can't deliver, we want room for the error message */
1082         r = bus_rqueue_make_room(bus);
1083         if (r < 0)
1084                 return r;
1085
1086         r = bus_message_setup_kmsg(bus, m);
1087         if (r < 0)
1088                 return r;
1089
1090         cmd.size = sizeof(cmd);
1091         cmd.msg_address = (uintptr_t)m->kdbus;
1092
1093         /* If this is a synchronous method call, then let's tell the
1094          * kernel, so that it can pass CPU time/scheduling to the
1095          * destination for the time, if it wants to. If we
1096          * synchronously wait for the result anyway, we won't need CPU
1097          * anyway. */
1098         if (hint_sync_call) {
1099                 m->kdbus->flags |= KDBUS_MSG_EXPECT_REPLY;
1100                 cmd.flags |= KDBUS_SEND_SYNC_REPLY;
1101         }
1102
1103         r = ioctl(bus->output_fd, KDBUS_CMD_SEND, &cmd);
1104         if (r < 0) {
1105                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1106                 sd_bus_message *reply;
1107
1108                 if (errno == EAGAIN || errno == EINTR)
1109                         return 0;
1110                 else if (errno == ENXIO || errno == ESRCH) {
1111
1112                         /* ENXIO: unique name not known
1113                          * ESRCH: well-known name not known */
1114
1115                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1116                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Destination %s not known", m->destination);
1117                         else {
1118                                 log_debug("Could not deliver message to %s as destination is not known. Ignoring.", m->destination);
1119                                 return 0;
1120                         }
1121
1122                 } else if (errno == EADDRNOTAVAIL) {
1123
1124                         /* EADDRNOTAVAIL: activation is possible, but turned off in request flags */
1125
1126                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1127                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Activation of %s not requested", m->destination);
1128                         else {
1129                                 log_debug("Could not deliver message to %s as destination is not activated. Ignoring.", m->destination);
1130                                 return 0;
1131                         }
1132                 } else
1133                         return -errno;
1134
1135                 r = bus_message_new_synthetic_error(
1136                                 bus,
1137                                 BUS_MESSAGE_COOKIE(m),
1138                                 &error,
1139                                 &reply);
1140
1141                 if (r < 0)
1142                         return r;
1143
1144                 r = bus_seal_synthetic_message(bus, reply);
1145                 if (r < 0)
1146                         return r;
1147
1148                 bus->rqueue[bus->rqueue_size++] = reply;
1149
1150         } else if (hint_sync_call) {
1151                 struct kdbus_msg *k;
1152
1153                 k = (struct kdbus_msg *)((uint8_t *)bus->kdbus_buffer + cmd.reply.offset);
1154                 assert(k);
1155
1156                 if (k->payload_type == KDBUS_PAYLOAD_DBUS) {
1157
1158                         r = bus_kernel_make_message(bus, k);
1159                         if (r < 0) {
1160                                 close_kdbus_msg(bus, k);
1161
1162                                 /* Anybody can send us invalid messages, let's just drop them. */
1163                                 if (r == -EBADMSG || r == -EPROTOTYPE)
1164                                         log_debug_errno(r, "Ignoring invalid synchronous reply: %m");
1165                                 else
1166                                         return r;
1167                         }
1168                 } else {
1169                         log_debug("Ignoring message with unknown payload type %llu.", (unsigned long long) k->payload_type);
1170                         close_kdbus_msg(bus, k);
1171                 }
1172         }
1173
1174         return 1;
1175 }
1176
1177 static int push_name_owner_changed(
1178                 sd_bus *bus,
1179                 const char *name,
1180                 const char *old_owner,
1181                 const char *new_owner,
1182                 const struct kdbus_timestamp *ts) {
1183
1184         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1185         int r;
1186
1187         assert(bus);
1188
1189         r = sd_bus_message_new_signal(
1190                         bus,
1191                         &m,
1192                         "/org/freedesktop/DBus",
1193                         "org.freedesktop.DBus",
1194                         "NameOwnerChanged");
1195         if (r < 0)
1196                 return r;
1197
1198         r = sd_bus_message_append(m, "sss", name, old_owner, new_owner);
1199         if (r < 0)
1200                 return r;
1201
1202         bus_message_set_sender_driver(bus, m);
1203         message_set_timestamp(bus, m, ts);
1204
1205         r = bus_seal_synthetic_message(bus, m);
1206         if (r < 0)
1207                 return r;
1208
1209         bus->rqueue[bus->rqueue_size++] = m;
1210         m = NULL;
1211
1212         return 1;
1213 }
1214
1215 static int translate_name_change(
1216                 sd_bus *bus,
1217                 const struct kdbus_msg *k,
1218                 const struct kdbus_item *d,
1219                 const struct kdbus_timestamp *ts) {
1220
1221         char new_owner[UNIQUE_NAME_MAX], old_owner[UNIQUE_NAME_MAX];
1222
1223         assert(bus);
1224         assert(k);
1225         assert(d);
1226
1227         if (d->type == KDBUS_ITEM_NAME_ADD || (d->name_change.old_id.flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_ACTIVATOR)))
1228                 old_owner[0] = 0;
1229         else
1230                 sprintf(old_owner, ":1.%llu", (unsigned long long) d->name_change.old_id.id);
1231
1232         if (d->type == KDBUS_ITEM_NAME_REMOVE || (d->name_change.new_id.flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_ACTIVATOR))) {
1233
1234                 if (isempty(old_owner))
1235                         return 0;
1236
1237                 new_owner[0] = 0;
1238         } else
1239                 sprintf(new_owner, ":1.%llu", (unsigned long long) d->name_change.new_id.id);
1240
1241         return push_name_owner_changed(bus, d->name_change.name, old_owner, new_owner, ts);
1242 }
1243
1244 static int translate_id_change(
1245                 sd_bus *bus,
1246                 const struct kdbus_msg *k,
1247                 const struct kdbus_item *d,
1248                 const struct kdbus_timestamp *ts) {
1249
1250         char owner[UNIQUE_NAME_MAX];
1251
1252         assert(bus);
1253         assert(k);
1254         assert(d);
1255
1256         sprintf(owner, ":1.%llu", d->id_change.id);
1257
1258         return push_name_owner_changed(
1259                         bus, owner,
1260                         d->type == KDBUS_ITEM_ID_ADD ? NULL : owner,
1261                         d->type == KDBUS_ITEM_ID_ADD ? owner : NULL,
1262                         ts);
1263 }
1264
1265 static int translate_reply(
1266                 sd_bus *bus,
1267                 const struct kdbus_msg *k,
1268                 const struct kdbus_item *d,
1269                 const struct kdbus_timestamp *ts) {
1270
1271         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1272         int r;
1273
1274         assert(bus);
1275         assert(k);
1276         assert(d);
1277
1278         r = bus_message_new_synthetic_error(
1279                         bus,
1280                         k->cookie_reply,
1281                         d->type == KDBUS_ITEM_REPLY_TIMEOUT ?
1282                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out") :
1283                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call peer died"),
1284                         &m);
1285         if (r < 0)
1286                 return r;
1287
1288         message_set_timestamp(bus, m, ts);
1289
1290         r = bus_seal_synthetic_message(bus, m);
1291         if (r < 0)
1292                 return r;
1293
1294         bus->rqueue[bus->rqueue_size++] = m;
1295         m = NULL;
1296
1297         return 1;
1298 }
1299
1300 static int bus_kernel_translate_message(sd_bus *bus, struct kdbus_msg *k) {
1301         static int (* const translate[])(sd_bus *bus, const struct kdbus_msg *k, const struct kdbus_item *d, const struct kdbus_timestamp *ts) = {
1302                 [KDBUS_ITEM_NAME_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
1303                 [KDBUS_ITEM_NAME_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
1304                 [KDBUS_ITEM_NAME_CHANGE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
1305
1306                 [KDBUS_ITEM_ID_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
1307                 [KDBUS_ITEM_ID_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
1308
1309                 [KDBUS_ITEM_REPLY_TIMEOUT - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
1310                 [KDBUS_ITEM_REPLY_DEAD - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
1311         };
1312
1313         struct kdbus_item *d, *found = NULL;
1314         struct kdbus_timestamp *ts = NULL;
1315
1316         assert(bus);
1317         assert(k);
1318         assert(k->payload_type == KDBUS_PAYLOAD_KERNEL);
1319
1320         KDBUS_ITEM_FOREACH(d, k, items) {
1321                 if (d->type == KDBUS_ITEM_TIMESTAMP)
1322                         ts = &d->timestamp;
1323
1324                 if (d->type >= _KDBUS_ITEM_KERNEL_BASE && d->type < _KDBUS_ITEM_KERNEL_BASE + ELEMENTSOF(translate)) {
1325                         if (found)
1326                                 return -EBADMSG;
1327                         found = d;
1328                 } else
1329                         log_debug("Got unknown field from kernel %llu", d->type);
1330         }
1331
1332         if (!found) {
1333                 log_debug("Didn't find a kernel message to translate.");
1334                 return 0;
1335         }
1336
1337         return translate[found->type - _KDBUS_ITEM_KERNEL_BASE](bus, k, found, ts);
1338 }
1339
1340 int bus_kernel_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1341         struct kdbus_cmd_recv recv = { .size = sizeof(recv) };
1342         struct kdbus_msg *k;
1343         int r;
1344
1345         assert(bus);
1346
1347         r = bus_rqueue_make_room(bus);
1348         if (r < 0)
1349                 return r;
1350
1351         if (hint_priority) {
1352                 recv.flags |= KDBUS_RECV_USE_PRIORITY;
1353                 recv.priority = priority;
1354         }
1355
1356         r = ioctl(bus->input_fd, KDBUS_CMD_RECV, &recv);
1357         if (recv.return_flags & KDBUS_RECV_RETURN_DROPPED_MSGS)
1358                 log_debug("%s: kdbus reports %" PRIu64 " dropped broadcast messages, ignoring.", strna(bus->description), (uint64_t) recv.dropped_msgs);
1359         if (r < 0) {
1360                 if (errno == EAGAIN)
1361                         return 0;
1362
1363                 return -errno;
1364         }
1365
1366         k = (struct kdbus_msg *)((uint8_t *)bus->kdbus_buffer + recv.msg.offset);
1367         if (k->payload_type == KDBUS_PAYLOAD_DBUS) {
1368                 r = bus_kernel_make_message(bus, k);
1369
1370                 /* Anybody can send us invalid messages, let's just drop them. */
1371                 if (r == -EBADMSG || r == -EPROTOTYPE) {
1372                         log_debug_errno(r, "Ignoring invalid message: %m");
1373                         r = 0;
1374                 }
1375
1376         } else if (k->payload_type == KDBUS_PAYLOAD_KERNEL)
1377                 r = bus_kernel_translate_message(bus, k);
1378         else {
1379                 log_debug("Ignoring message with unknown payload type %llu.", (unsigned long long) k->payload_type);
1380                 r = 0;
1381         }
1382
1383         if (r <= 0)
1384                 close_kdbus_msg(bus, k);
1385
1386         return r < 0 ? r : 1;
1387 }
1388
1389 int bus_kernel_pop_memfd(sd_bus *bus, void **address, size_t *mapped, size_t *allocated) {
1390         struct memfd_cache *c;
1391         int fd;
1392
1393         assert(address);
1394         assert(mapped);
1395         assert(allocated);
1396
1397         if (!bus || !bus->is_kernel)
1398                 return -EOPNOTSUPP;
1399
1400         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
1401
1402         if (bus->n_memfd_cache <= 0) {
1403                 int r;
1404
1405                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1406
1407                 r = memfd_new(bus->description);
1408                 if (r < 0)
1409                         return r;
1410
1411                 *address = NULL;
1412                 *mapped = 0;
1413                 *allocated = 0;
1414                 return r;
1415         }
1416
1417         c = &bus->memfd_cache[--bus->n_memfd_cache];
1418
1419         assert(c->fd >= 0);
1420         assert(c->mapped == 0 || c->address);
1421
1422         *address = c->address;
1423         *mapped = c->mapped;
1424         *allocated = c->allocated;
1425         fd = c->fd;
1426
1427         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1428
1429         return fd;
1430 }
1431
1432 static void close_and_munmap(int fd, void *address, size_t size) {
1433         if (size > 0)
1434                 assert_se(munmap(address, PAGE_ALIGN(size)) >= 0);
1435
1436         safe_close(fd);
1437 }
1438
1439 void bus_kernel_push_memfd(sd_bus *bus, int fd, void *address, size_t mapped, size_t allocated) {
1440         struct memfd_cache *c;
1441         uint64_t max_mapped = PAGE_ALIGN(MEMFD_CACHE_ITEM_SIZE_MAX);
1442
1443         assert(fd >= 0);
1444         assert(mapped == 0 || address);
1445
1446         if (!bus || !bus->is_kernel) {
1447                 close_and_munmap(fd, address, mapped);
1448                 return;
1449         }
1450
1451         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
1452
1453         if (bus->n_memfd_cache >= ELEMENTSOF(bus->memfd_cache)) {
1454                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1455
1456                 close_and_munmap(fd, address, mapped);
1457                 return;
1458         }
1459
1460         c = &bus->memfd_cache[bus->n_memfd_cache++];
1461         c->fd = fd;
1462         c->address = address;
1463
1464         /* If overly long, let's return a bit to the OS */
1465         if (mapped > max_mapped) {
1466                 assert_se(memfd_set_size(fd, max_mapped) >= 0);
1467                 assert_se(munmap((uint8_t*) address + max_mapped, PAGE_ALIGN(mapped - max_mapped)) >= 0);
1468                 c->mapped = c->allocated = max_mapped;
1469         } else {
1470                 c->mapped = mapped;
1471                 c->allocated = allocated;
1472         }
1473
1474         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1475 }
1476
1477 void bus_kernel_flush_memfd(sd_bus *b) {
1478         unsigned i;
1479
1480         assert(b);
1481
1482         for (i = 0; i < b->n_memfd_cache; i++)
1483                 close_and_munmap(b->memfd_cache[i].fd, b->memfd_cache[i].address, b->memfd_cache[i].mapped);
1484 }
1485
1486 uint64_t request_name_flags_to_kdbus(uint64_t flags) {
1487         uint64_t f = 0;
1488
1489         if (flags & SD_BUS_NAME_ALLOW_REPLACEMENT)
1490                 f |= KDBUS_NAME_ALLOW_REPLACEMENT;
1491
1492         if (flags & SD_BUS_NAME_REPLACE_EXISTING)
1493                 f |= KDBUS_NAME_REPLACE_EXISTING;
1494
1495         if (flags & SD_BUS_NAME_QUEUE)
1496                 f |= KDBUS_NAME_QUEUE;
1497
1498         return f;
1499 }
1500
1501 uint64_t attach_flags_to_kdbus(uint64_t mask) {
1502         uint64_t m = 0;
1503
1504         if (mask & (SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_SUID|SD_BUS_CREDS_FSUID|
1505                     SD_BUS_CREDS_GID|SD_BUS_CREDS_EGID|SD_BUS_CREDS_SGID|SD_BUS_CREDS_FSGID))
1506                 m |= KDBUS_ATTACH_CREDS;
1507
1508         if (mask & (SD_BUS_CREDS_PID|SD_BUS_CREDS_TID))
1509                 m |= KDBUS_ATTACH_PIDS;
1510
1511         if (mask & SD_BUS_CREDS_COMM)
1512                 m |= KDBUS_ATTACH_PID_COMM;
1513
1514         if (mask & SD_BUS_CREDS_TID_COMM)
1515                 m |= KDBUS_ATTACH_TID_COMM;
1516
1517         if (mask & SD_BUS_CREDS_EXE)
1518                 m |= KDBUS_ATTACH_EXE;
1519
1520         if (mask & SD_BUS_CREDS_CMDLINE)
1521                 m |= KDBUS_ATTACH_CMDLINE;
1522
1523         if (mask & (SD_BUS_CREDS_CGROUP|SD_BUS_CREDS_UNIT|SD_BUS_CREDS_USER_UNIT|SD_BUS_CREDS_SLICE|SD_BUS_CREDS_SESSION|SD_BUS_CREDS_OWNER_UID))
1524                 m |= KDBUS_ATTACH_CGROUP;
1525
1526         if (mask & (SD_BUS_CREDS_EFFECTIVE_CAPS|SD_BUS_CREDS_PERMITTED_CAPS|SD_BUS_CREDS_INHERITABLE_CAPS|SD_BUS_CREDS_BOUNDING_CAPS))
1527                 m |= KDBUS_ATTACH_CAPS;
1528
1529         if (mask & SD_BUS_CREDS_SELINUX_CONTEXT)
1530                 m |= KDBUS_ATTACH_SECLABEL;
1531
1532         if (mask & (SD_BUS_CREDS_AUDIT_SESSION_ID|SD_BUS_CREDS_AUDIT_LOGIN_UID))
1533                 m |= KDBUS_ATTACH_AUDIT;
1534
1535         if (mask & SD_BUS_CREDS_WELL_KNOWN_NAMES)
1536                 m |= KDBUS_ATTACH_NAMES;
1537
1538         if (mask & SD_BUS_CREDS_DESCRIPTION)
1539                 m |= KDBUS_ATTACH_CONN_DESCRIPTION;
1540
1541         if (mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS)
1542                 m |= KDBUS_ATTACH_AUXGROUPS;
1543
1544         return m;
1545 }
1546
1547 int bus_kernel_create_bus(const char *name, bool world, char **s) {
1548         struct kdbus_cmd *make;
1549         struct kdbus_item *n;
1550         size_t l;
1551         int fd;
1552
1553         assert(name);
1554         assert(s);
1555
1556         fd = open("/sys/fs/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
1557         if (fd < 0)
1558                 return -errno;
1559
1560         l = strlen(name);
1561         make = alloca0_align(offsetof(struct kdbus_cmd, items) +
1562                              ALIGN8(offsetof(struct kdbus_item, bloom_parameter) + sizeof(struct kdbus_bloom_parameter)) +
1563                              ALIGN8(offsetof(struct kdbus_item, data64) + sizeof(uint64_t)) +
1564                              ALIGN8(offsetof(struct kdbus_item, data64) + sizeof(uint64_t)) +
1565                              ALIGN8(offsetof(struct kdbus_item, str) + DECIMAL_STR_MAX(uid_t) + 1 + l + 1),
1566                              8);
1567
1568         make->size = offsetof(struct kdbus_cmd, items);
1569
1570         /* Set the bloom parameters */
1571         n = make->items;
1572         n->size = offsetof(struct kdbus_item, bloom_parameter) +
1573                   sizeof(struct kdbus_bloom_parameter);
1574         n->type = KDBUS_ITEM_BLOOM_PARAMETER;
1575         n->bloom_parameter.size = DEFAULT_BLOOM_SIZE;
1576         n->bloom_parameter.n_hash = DEFAULT_BLOOM_N_HASH;
1577
1578         assert_cc(DEFAULT_BLOOM_SIZE > 0);
1579         assert_cc(DEFAULT_BLOOM_N_HASH > 0);
1580
1581         make->size += ALIGN8(n->size);
1582
1583         /* The busses we create make no restrictions on what metadata
1584          * peers can read from incoming messages. */
1585         n = KDBUS_ITEM_NEXT(n);
1586         n->type = KDBUS_ITEM_ATTACH_FLAGS_RECV;
1587         n->size = offsetof(struct kdbus_item, data64) + sizeof(uint64_t);
1588         n->data64[0] = _KDBUS_ATTACH_ANY;
1589         make->size += ALIGN8(n->size);
1590
1591         /* Provide all metadata via bus-owner queries */
1592         n = KDBUS_ITEM_NEXT(n);
1593         n->type = KDBUS_ITEM_ATTACH_FLAGS_SEND;
1594         n->size = offsetof(struct kdbus_item, data64) + sizeof(uint64_t);
1595         n->data64[0] = _KDBUS_ATTACH_ANY;
1596         make->size += ALIGN8(n->size);
1597
1598         /* Set the a good name */
1599         n = KDBUS_ITEM_NEXT(n);
1600         sprintf(n->str, UID_FMT "-%s", getuid(), name);
1601         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1602         n->type = KDBUS_ITEM_MAKE_NAME;
1603         make->size += ALIGN8(n->size);
1604
1605         make->flags = world ? KDBUS_MAKE_ACCESS_WORLD : 0;
1606
1607         if (ioctl(fd, KDBUS_CMD_BUS_MAKE, make) < 0) {
1608                 safe_close(fd);
1609                 return -errno;
1610         }
1611
1612         if (s) {
1613                 char *p;
1614
1615                 p = strjoin("/sys/fs/kdbus/", n->str, "/bus", NULL);
1616                 if (!p) {
1617                         safe_close(fd);
1618                         return -ENOMEM;
1619                 }
1620
1621                 *s = p;
1622         }
1623
1624         return fd;
1625 }
1626
1627 int bus_kernel_open_bus_fd(const char *bus, char **path) {
1628         char *p;
1629         int fd;
1630         size_t len;
1631
1632         assert(bus);
1633
1634         len = strlen("/sys/fs/kdbus/") + DECIMAL_STR_MAX(uid_t) + 1 + strlen(bus) + strlen("/bus") + 1;
1635
1636         if (path) {
1637                 p = new(char, len);
1638                 if (!p)
1639                         return -ENOMEM;
1640         } else
1641                 p = newa(char, len);
1642
1643         sprintf(p, "/sys/fs/kdbus/" UID_FMT "-%s/bus", getuid(), bus);
1644
1645         fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
1646         if (fd < 0) {
1647                 if (path)
1648                         free(p);
1649
1650                 return -errno;
1651         }
1652
1653         if (path)
1654                 *path = p;
1655
1656         return fd;
1657 }
1658
1659 int bus_kernel_create_endpoint(const char *bus_name, const char *ep_name, char **ep_path) {
1660         _cleanup_free_ char *path = NULL;
1661         struct kdbus_cmd *make;
1662         struct kdbus_item *n;
1663         const char *name;
1664         int fd;
1665
1666         fd = bus_kernel_open_bus_fd(bus_name, &path);
1667         if (fd < 0)
1668                 return fd;
1669
1670         make = alloca0_align(ALIGN8(offsetof(struct kdbus_cmd, items)) +
1671                              ALIGN8(offsetof(struct kdbus_item, str) + DECIMAL_STR_MAX(uid_t) + 1 + strlen(ep_name) + 1),
1672                              8);
1673         make->size = ALIGN8(offsetof(struct kdbus_cmd, items));
1674         make->flags = KDBUS_MAKE_ACCESS_WORLD;
1675
1676         n = make->items;
1677         sprintf(n->str, UID_FMT "-%s", getuid(), ep_name);
1678         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1679         n->type = KDBUS_ITEM_MAKE_NAME;
1680         make->size += ALIGN8(n->size);
1681         name = n->str;
1682
1683         if (ioctl(fd, KDBUS_CMD_ENDPOINT_MAKE, make) < 0) {
1684                 safe_close(fd);
1685                 return -errno;
1686         }
1687
1688         if (ep_path) {
1689                 char *p;
1690
1691                 p = strjoin(dirname(path), "/", name, NULL);
1692                 if (!p) {
1693                         safe_close(fd);
1694                         return -ENOMEM;
1695                 }
1696
1697                 *ep_path = p;
1698         }
1699
1700         return fd;
1701 }
1702
1703 int bus_kernel_try_close(sd_bus *bus) {
1704         struct kdbus_cmd byebye = { .size = sizeof(byebye) };
1705
1706         assert(bus);
1707         assert(bus->is_kernel);
1708
1709         if (ioctl(bus->input_fd, KDBUS_CMD_BYEBYE, &byebye) < 0)
1710                 return -errno;
1711
1712         return 0;
1713 }
1714
1715 int bus_kernel_drop_one(int fd) {
1716         struct kdbus_cmd_recv recv = {
1717                 .size = sizeof(recv),
1718                 .flags = KDBUS_RECV_DROP,
1719         };
1720
1721         assert(fd >= 0);
1722
1723         if (ioctl(fd, KDBUS_CMD_RECV, &recv) < 0)
1724                 return -errno;
1725
1726         return 0;
1727 }
1728
1729 int bus_kernel_realize_attach_flags(sd_bus *bus) {
1730         struct kdbus_cmd *update;
1731         struct kdbus_item *n;
1732
1733         assert(bus);
1734         assert(bus->is_kernel);
1735
1736         update = alloca0_align(offsetof(struct kdbus_cmd, items) +
1737                                ALIGN8(offsetof(struct kdbus_item, data64) + sizeof(uint64_t)),
1738                                8);
1739
1740         n = update->items;
1741         n->type = KDBUS_ITEM_ATTACH_FLAGS_RECV;
1742         n->size = offsetof(struct kdbus_item, data64) + sizeof(uint64_t);
1743         n->data64[0] = bus->attach_flags;
1744
1745         update->size =
1746                 offsetof(struct kdbus_cmd, items) +
1747                 ALIGN8(n->size);
1748
1749         if (ioctl(bus->input_fd, KDBUS_CMD_UPDATE, update) < 0)
1750                 return -errno;
1751
1752         return 0;
1753 }
1754
1755 int bus_kernel_fix_attach_mask(void) {
1756         _cleanup_free_ char *mask = NULL;
1757         uint64_t m = (uint64_t) -1;
1758         char buf[2+16+2];
1759         int r;
1760
1761         /* By default we don't want any kdbus metadata fields to be
1762          * suppressed, hence we reset the kernel mask for it to
1763          * (uint64_t) -1. If the module argument was overwritten by
1764          * the kernel cmdline, we leave it as is. */
1765
1766         r = get_proc_cmdline_key("kdbus.attach_flags_mask=", &mask);
1767         if (r < 0)
1768                 return log_warning_errno(r, "Failed to read kernel command line: %m");
1769
1770         if (r == 0) {
1771                 sprintf(buf, "0x%" PRIx64 "\n", m);
1772                 r = write_string_file("/sys/module/kdbus/parameters/attach_flags_mask", buf);
1773                 if (r < 0)
1774                         return log_full_errno(IN_SET(r, -ENOENT, -EROFS) ? LOG_DEBUG : LOG_WARNING, r,
1775                                               "Failed to write kdbus attach mask: %m");
1776         }
1777
1778         return 0;
1779 }
1780
1781 int bus_kernel_get_bus_name(sd_bus *bus, char **name) {
1782         struct kdbus_cmd_info cmd = {
1783                 .size = sizeof(struct kdbus_cmd_info),
1784         };
1785         struct kdbus_info *info;
1786         struct kdbus_item *item;
1787         char *n = NULL;
1788         int r;
1789
1790         assert(bus);
1791         assert(name);
1792         assert(bus->is_kernel);
1793
1794         r = ioctl(bus->input_fd, KDBUS_CMD_BUS_CREATOR_INFO, &cmd);
1795         if (r < 0)
1796                 return -errno;
1797
1798         info = (struct kdbus_info*) ((uint8_t*) bus->kdbus_buffer + cmd.offset);
1799
1800         KDBUS_ITEM_FOREACH(item, info, items)
1801                 if (item->type == KDBUS_ITEM_MAKE_NAME) {
1802                         r = free_and_strdup(&n, item->str);
1803                         break;
1804                 }
1805
1806         bus_kernel_cmd_free(bus, cmd.offset);
1807
1808         if (r < 0)
1809                 return r;
1810         if (!n)
1811                 return -EIO;
1812
1813         *name = n;
1814         return 0;
1815 }