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