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