chiark / gitweb /
bus: always override message destination field with data from kdbus
[elogind.git] / src / libsystemd-bus / bus-kernel.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #ifdef HAVE_VALGRIND_MEMCHECK_H
23 #include <valgrind/memcheck.h>
24 #endif
25
26 #include <fcntl.h>
27 #include <malloc.h>
28 #include <sys/mman.h>
29
30 #include "util.h"
31 #include "strv.h"
32
33 #include "bus-internal.h"
34 #include "bus-message.h"
35 #include "bus-kernel.h"
36 #include "bus-bloom.h"
37 #include "bus-util.h"
38
39 #define UNIQUE_NAME_MAX (3+DECIMAL_STR_MAX(uint64_t))
40
41 int bus_kernel_parse_unique_name(const char *s, uint64_t *id) {
42         int r;
43
44         assert(s);
45         assert(id);
46
47         if (!startswith(s, ":1."))
48                 return 0;
49
50         r = safe_atou64(s + 3, id);
51         if (r < 0)
52                 return r;
53
54         return 1;
55 }
56
57 static void append_payload_vec(struct kdbus_item **d, const void *p, size_t sz) {
58         assert(d);
59         assert(sz > 0);
60
61         *d = ALIGN8_PTR(*d);
62
63         /* Note that p can be NULL, which encodes a region full of
64          * zeroes, which is useful to optimize certain padding
65          * conditions */
66
67         (*d)->size = offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec);
68         (*d)->type = KDBUS_ITEM_PAYLOAD_VEC;
69         (*d)->vec.address = PTR_TO_UINT64(p);
70         (*d)->vec.size = sz;
71
72         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
73 }
74
75 static void append_payload_memfd(struct kdbus_item **d, int memfd, size_t sz) {
76         assert(d);
77         assert(memfd >= 0);
78         assert(sz > 0);
79
80         *d = ALIGN8_PTR(*d);
81         (*d)->size = offsetof(struct kdbus_item, memfd) + sizeof(struct kdbus_memfd);
82         (*d)->type = KDBUS_ITEM_PAYLOAD_MEMFD;
83         (*d)->memfd.fd = memfd;
84         (*d)->memfd.size = sz;
85
86         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
87 }
88
89 static void append_destination(struct kdbus_item **d, const char *s, size_t length) {
90         assert(d);
91         assert(s);
92
93         *d = ALIGN8_PTR(*d);
94
95         (*d)->size = offsetof(struct kdbus_item, str) + length + 1;
96         (*d)->type = KDBUS_ITEM_DST_NAME;
97         memcpy((*d)->str, s, length + 1);
98
99         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
100 }
101
102 static void* append_bloom(struct kdbus_item **d, size_t length) {
103         void *r;
104
105         assert(d);
106
107         *d = ALIGN8_PTR(*d);
108
109         (*d)->size = offsetof(struct kdbus_item, data) + length;
110         (*d)->type = KDBUS_ITEM_BLOOM;
111         r = (*d)->data;
112
113         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
114
115         return r;
116 }
117
118 static void append_fds(struct kdbus_item **d, const int fds[], unsigned n_fds) {
119         assert(d);
120         assert(fds);
121         assert(n_fds > 0);
122
123         *d = ALIGN8_PTR(*d);
124         (*d)->size = offsetof(struct kdbus_item, fds) + sizeof(int) * n_fds;
125         (*d)->type = KDBUS_ITEM_FDS;
126         memcpy((*d)->fds, fds, sizeof(int) * n_fds);
127
128         *d = (struct kdbus_item *) ((uint8_t*) *d + (*d)->size);
129 }
130
131 static int bus_message_setup_bloom(sd_bus_message *m, void *bloom) {
132         unsigned i;
133         int r;
134
135         assert(m);
136         assert(bloom);
137
138         memset(bloom, 0, BLOOM_SIZE);
139
140         bloom_add_pair(bloom, "message-type", bus_message_type_to_string(m->header->type));
141
142         if (m->interface)
143                 bloom_add_pair(bloom, "interface", m->interface);
144         if (m->member)
145                 bloom_add_pair(bloom, "member", m->member);
146         if (m->path) {
147                 bloom_add_pair(bloom, "path", m->path);
148                 bloom_add_pair(bloom, "path-slash-prefix", m->path);
149                 bloom_add_prefixes(bloom, "path-slash-prefix", m->path, '/');
150         }
151
152         r = sd_bus_message_rewind(m, true);
153         if (r < 0)
154                 return r;
155
156         for (i = 0; i < 64; i++) {
157                 char type;
158                 const char *t;
159                 char buf[sizeof("arg")-1 + 2 + sizeof("-slash-prefix")];
160                 char *e;
161
162                 r = sd_bus_message_peek_type(m, &type, NULL);
163                 if (r < 0)
164                         return r;
165
166                 if (type != SD_BUS_TYPE_STRING &&
167                     type != SD_BUS_TYPE_OBJECT_PATH &&
168                     type != SD_BUS_TYPE_SIGNATURE)
169                         break;
170
171                 r = sd_bus_message_read_basic(m, type, &t);
172                 if (r < 0)
173                         return r;
174
175                 e = stpcpy(buf, "arg");
176                 if (i < 10)
177                         *(e++) = '0' + i;
178                 else {
179                         *(e++) = '0' + (i / 10);
180                         *(e++) = '0' + (i % 10);
181                 }
182
183                 *e = 0;
184                 bloom_add_pair(bloom, buf, t);
185
186                 strcpy(e, "-dot-prefix");
187                 bloom_add_prefixes(bloom, buf, t, '.');
188                 strcpy(e, "-slash-prefix");
189                 bloom_add_prefixes(bloom, buf, t, '/');
190         }
191
192         return 0;
193 }
194
195 static int bus_message_setup_kmsg(sd_bus *b, sd_bus_message *m) {
196         struct bus_body_part *part;
197         struct kdbus_item *d;
198         bool well_known;
199         uint64_t unique;
200         size_t sz, dl;
201         unsigned i;
202         int r;
203
204         assert(b);
205         assert(m);
206         assert(m->sealed);
207
208         if (m->kdbus)
209                 return 0;
210
211         if (m->destination) {
212                 r = bus_kernel_parse_unique_name(m->destination, &unique);
213                 if (r < 0)
214                         return r;
215
216                 well_known = r == 0;
217         } else
218                 well_known = false;
219
220         sz = offsetof(struct kdbus_msg, items);
221
222         assert_cc(ALIGN8(offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec)) ==
223                   ALIGN8(offsetof(struct kdbus_item, memfd) + sizeof(struct kdbus_memfd)));
224
225         /* Add in fixed header, fields header and payload */
226         sz += (1 + m->n_body_parts) *
227                 ALIGN8(offsetof(struct kdbus_item, vec) + sizeof(struct kdbus_vec));
228
229         /* Add space for bloom filter */
230         sz += ALIGN8(offsetof(struct kdbus_item, data) + BLOOM_SIZE);
231
232         /* Add in well-known destination header */
233         if (well_known) {
234                 dl = strlen(m->destination);
235                 sz += ALIGN8(offsetof(struct kdbus_item, str) + dl + 1);
236         }
237
238         /* Add space for unix fds */
239         if (m->n_fds > 0)
240                 sz += ALIGN8(offsetof(struct kdbus_item, fds) + sizeof(int)*m->n_fds);
241
242         m->kdbus = memalign(8, sz);
243         if (!m->kdbus) {
244                 r = -ENOMEM;
245                 goto fail;
246         }
247
248         m->free_kdbus = true;
249         memset(m->kdbus, 0, sz);
250
251         m->kdbus->flags =
252                 ((m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED) ? 0 : KDBUS_MSG_FLAGS_EXPECT_REPLY) |
253                 ((m->header->flags & BUS_MESSAGE_NO_AUTO_START) ? KDBUS_MSG_FLAGS_NO_AUTO_START : 0);
254         m->kdbus->dst_id =
255                 well_known ? 0 :
256                 m->destination ? unique : KDBUS_DST_ID_BROADCAST;
257         m->kdbus->payload_type = KDBUS_PAYLOAD_DBUS;
258         m->kdbus->cookie = m->header->serial;
259
260         m->kdbus->timeout_ns = m->timeout * NSEC_PER_USEC;
261
262         d = m->kdbus->items;
263
264         if (well_known)
265                 append_destination(&d, m->destination, dl);
266
267         append_payload_vec(&d, m->header, BUS_MESSAGE_BODY_BEGIN(m));
268
269         MESSAGE_FOREACH_PART(part, i, m) {
270                 if (part->is_zero) {
271                         /* If this is padding then simply send a
272                          * vector with a NULL data pointer which the
273                          * kernel will just pass through. This is the
274                          * most efficient way to encode zeroes */
275
276                         append_payload_vec(&d, NULL, part->size);
277                         continue;
278                 }
279
280                 if (part->memfd >= 0 && part->sealed && m->destination) {
281                         /* Try to send a memfd, if the part is
282                          * sealed and this is not a broadcast. Since we can only  */
283
284                         append_payload_memfd(&d, part->memfd, part->size);
285                         continue;
286                 }
287
288                 /* Otherwise let's send a vector to the actual data,
289                  * for that we need to map it first. */
290                 r = bus_body_part_map(part);
291                 if (r < 0)
292                         goto fail;
293
294                 append_payload_vec(&d, part->data, part->size);
295         }
296
297         if (m->kdbus->dst_id == KDBUS_DST_ID_BROADCAST) {
298                 void *p;
299
300                 p = append_bloom(&d, BLOOM_SIZE);
301                 r = bus_message_setup_bloom(m, p);
302                 if (r < 0)
303                         goto fail;
304         }
305
306         if (m->n_fds > 0)
307                 append_fds(&d, m->fds, m->n_fds);
308
309         m->kdbus->size = (uint8_t*) d - (uint8_t*) m->kdbus;
310         assert(m->kdbus->size <= sz);
311
312         return 0;
313
314 fail:
315         m->poisoned = true;
316         return r;
317 }
318
319 int bus_kernel_take_fd(sd_bus *b) {
320         struct kdbus_cmd_hello hello;
321         int r;
322
323         assert(b);
324
325         if (b->is_server)
326                 return -EINVAL;
327
328         b->use_memfd = 1;
329
330         zero(hello);
331         hello.size = sizeof(hello);
332         hello.conn_flags = b->hello_flags;
333         hello.attach_flags = b->attach_flags;
334         hello.pool_size = KDBUS_POOL_SIZE;
335
336         r = ioctl(b->input_fd, KDBUS_CMD_HELLO, &hello);
337         if (r < 0)
338                 return -errno;
339
340         if (!b->kdbus_buffer) {
341                 b->kdbus_buffer = mmap(NULL, KDBUS_POOL_SIZE, PROT_READ, MAP_SHARED, b->input_fd, 0);
342                 if (b->kdbus_buffer == MAP_FAILED) {
343                         b->kdbus_buffer = NULL;
344                         return -errno;
345                 }
346         }
347
348         /* The higher 32bit of both flags fields are considered
349          * 'incompatible flags'. Refuse them all for now. */
350         if (hello.bus_flags > 0xFFFFFFFFULL ||
351             hello.conn_flags > 0xFFFFFFFFULL)
352                 return -ENOTSUP;
353
354         if (hello.bloom_size != BLOOM_SIZE)
355                 return -ENOTSUP;
356
357         if (asprintf(&b->unique_name, ":1.%llu", (unsigned long long) hello.id) < 0)
358                 return -ENOMEM;
359
360         b->unique_id = hello.id;
361
362         b->is_kernel = true;
363         b->bus_client = true;
364         b->can_fds = !!(hello.conn_flags & KDBUS_HELLO_ACCEPT_FD);
365         b->message_version = 2;
366         b->message_endian = BUS_NATIVE_ENDIAN;
367
368         /* the kernel told us the UUID of the underlying bus */
369         memcpy(b->server_id.bytes, hello.id128, sizeof(b->server_id.bytes));
370
371         return bus_start_running(b);
372 }
373
374 int bus_kernel_connect(sd_bus *b) {
375         assert(b);
376         assert(b->input_fd < 0);
377         assert(b->output_fd < 0);
378         assert(b->kernel);
379
380         if (b->is_server)
381                 return -EINVAL;
382
383         b->input_fd = open(b->kernel, O_RDWR|O_NOCTTY|O_CLOEXEC);
384         if (b->input_fd < 0)
385                 return -errno;
386
387         b->output_fd = b->input_fd;
388
389         return bus_kernel_take_fd(b);
390 }
391
392 int bus_kernel_write_message(sd_bus *bus, sd_bus_message *m) {
393         int r;
394
395         assert(bus);
396         assert(m);
397         assert(bus->state == BUS_RUNNING);
398
399         /* If we can't deliver, we want room for the error message */
400         r = bus_rqueue_make_room(bus);
401         if (r < 0)
402                 return r;
403
404         r = bus_message_setup_kmsg(bus, m);
405         if (r < 0)
406                 return r;
407
408         r = ioctl(bus->output_fd, KDBUS_CMD_MSG_SEND, m->kdbus);
409         if (r < 0) {
410                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
411                 sd_bus_message *reply;
412
413                 if (errno == EAGAIN || errno == EINTR)
414                         return 0;
415                 else if (errno == ENXIO || errno == ESRCH) {
416
417                         /* ENXIO: unique name not known
418                          * ESRCH: well-known name not known */
419
420                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
421                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Destination %s not known", m->destination);
422                         else {
423                                 log_debug("Could not deliver message to %s as destination is not known. Ignoring.", m->destination);
424                                 return 0;
425                         }
426
427                 } else if (errno == EADDRNOTAVAIL) {
428
429                         /* EADDRNOTAVAIL: activation is possible, but turned off in request flags */
430
431                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
432                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Activation of %s not requested", m->destination);
433                         else {
434                                 log_debug("Could not deliver message to %s as destination is not activated. Ignoring.", m->destination);
435                                 return 0;
436                         }
437                 } else
438                         return -errno;
439
440                 r = bus_message_new_synthetic_error(
441                                 bus,
442                                 BUS_MESSAGE_SERIAL(m),
443                                 &error,
444                                 &reply);
445
446                 if (r < 0)
447                         return r;
448
449                 r = bus_seal_synthetic_message(bus, reply);
450                 if (r < 0)
451                         return r;
452
453                 bus->rqueue[bus->rqueue_size++] = reply;
454
455                 return 0;
456         }
457
458         return 1;
459 }
460
461 static void close_kdbus_msg(sd_bus *bus, struct kdbus_msg *k) {
462         uint64_t off;
463         struct kdbus_item *d;
464
465         assert(bus);
466         assert(k);
467
468         off = (uint8_t *)k - (uint8_t *)bus->kdbus_buffer;
469         ioctl(bus->input_fd, KDBUS_CMD_FREE, &off);
470
471         KDBUS_ITEM_FOREACH(d, k, items) {
472
473                 if (d->type == KDBUS_ITEM_FDS)
474                         close_many(d->fds, (d->size - offsetof(struct kdbus_item, fds)) / sizeof(int));
475                 else if (d->type == KDBUS_ITEM_PAYLOAD_MEMFD)
476                         close_nointr_nofail(d->memfd.fd);
477         }
478 }
479
480 static int push_name_owner_changed(sd_bus *bus, const char *name, const char *old_owner, const char *new_owner) {
481         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
482         int r;
483
484         assert(bus);
485
486         r = sd_bus_message_new_signal(
487                         bus,
488                         "/org/freedesktop/DBus",
489                         "org.freedesktop.DBus",
490                         "NameOwnerChanged",
491                         &m);
492         if (r < 0)
493                 return r;
494
495         r = sd_bus_message_append(m, "sss", name, old_owner, new_owner);
496         if (r < 0)
497                 return r;
498
499         m->sender = "org.freedesktop.DBus";
500
501         r = bus_seal_synthetic_message(bus, m);
502         if (r < 0)
503                 return r;
504
505         bus->rqueue[bus->rqueue_size++] = m;
506         m = NULL;
507
508         return 1;
509 }
510
511 static int translate_name_change(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
512         char new_owner[UNIQUE_NAME_MAX], old_owner[UNIQUE_NAME_MAX];
513
514         assert(bus);
515         assert(k);
516         assert(d);
517
518         if (d->type == KDBUS_ITEM_NAME_ADD || (d->name_change.old.flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_ACTIVATOR)))
519                 old_owner[0] = 0;
520         else
521                 sprintf(old_owner, ":1.%llu", (unsigned long long) d->name_change.old.id);
522
523         if (d->type == KDBUS_ITEM_NAME_REMOVE || (d->name_change.new.flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_ACTIVATOR))) {
524
525                 if (isempty(old_owner))
526                         return 0;
527
528                 new_owner[0] = 0;
529         } else
530                 sprintf(new_owner, ":1.%llu", (unsigned long long) d->name_change.new.id);
531
532         return push_name_owner_changed(bus, d->name_change.name, old_owner, new_owner);
533 }
534
535 static int translate_id_change(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
536         char owner[UNIQUE_NAME_MAX];
537
538         assert(bus);
539         assert(k);
540         assert(d);
541
542         sprintf(owner, ":1.%llu", d->id_change.id);
543
544         return push_name_owner_changed(
545                         bus, owner,
546                         d->type == KDBUS_ITEM_ID_ADD ? NULL : owner,
547                         d->type == KDBUS_ITEM_ID_ADD ? owner : NULL);
548 }
549
550 static int translate_reply(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
551         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
552         int r;
553
554         assert(bus);
555         assert(k);
556         assert(d);
557
558         r = bus_message_new_synthetic_error(
559                         bus,
560                         k->cookie_reply,
561                         d->type == KDBUS_ITEM_REPLY_TIMEOUT ?
562                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out") :
563                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call peer died"),
564                         &m);
565         if (r < 0)
566                 return r;
567
568         m->sender = "org.freedesktop.DBus";
569
570         r = bus_seal_synthetic_message(bus, m);
571         if (r < 0)
572                 return r;
573
574         bus->rqueue[bus->rqueue_size++] = m;
575         m = NULL;
576
577         return 1;
578 }
579
580 static int bus_kernel_translate_message(sd_bus *bus, struct kdbus_msg *k) {
581         struct kdbus_item *d, *found = NULL;
582
583         static int (* const translate[])(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) = {
584                 [KDBUS_ITEM_NAME_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
585                 [KDBUS_ITEM_NAME_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
586                 [KDBUS_ITEM_NAME_CHANGE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
587
588                 [KDBUS_ITEM_ID_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
589                 [KDBUS_ITEM_ID_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
590
591                 [KDBUS_ITEM_REPLY_TIMEOUT - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
592                 [KDBUS_ITEM_REPLY_DEAD - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
593         };
594
595         assert(bus);
596         assert(k);
597         assert(k->payload_type == KDBUS_PAYLOAD_KERNEL);
598
599         KDBUS_ITEM_FOREACH(d, k, items) {
600                 if (d->type >= _KDBUS_ITEM_KERNEL_BASE && d->type < _KDBUS_ITEM_KERNEL_BASE + ELEMENTSOF(translate)) {
601                         if (found)
602                                 return -EBADMSG;
603                         found = d;
604                 } else
605                         log_debug("Got unknown field from kernel %llu", d->type);
606         }
607
608         if (!found) {
609                 log_debug("Didn't find a kernel message to translate.");
610                 return 0;
611         }
612
613         return translate[found->type - _KDBUS_ITEM_KERNEL_BASE](bus, k, found);
614 }
615
616 static int bus_kernel_make_message(sd_bus *bus, struct kdbus_msg *k) {
617         sd_bus_message *m = NULL;
618         struct kdbus_item *d;
619         unsigned n_fds = 0;
620         _cleanup_free_ int *fds = NULL;
621         struct bus_header *h = NULL;
622         size_t total, n_bytes = 0, idx = 0;
623         const char *destination = NULL, *seclabel = NULL;
624         int r;
625
626         assert(bus);
627         assert(k);
628         assert(k->payload_type == KDBUS_PAYLOAD_DBUS);
629
630         KDBUS_ITEM_FOREACH(d, k, items) {
631                 size_t l;
632
633                 l = d->size - offsetof(struct kdbus_item, data);
634
635                 switch (d->type) {
636
637                 case KDBUS_ITEM_PAYLOAD_OFF:
638                         if (!h) {
639                                 h = (struct bus_header *)((uint8_t *)k + d->vec.offset);
640
641                                 if (!bus_header_is_complete(h, d->vec.size))
642                                         return -EBADMSG;
643                         }
644
645                         n_bytes += d->vec.size;
646                         break;
647
648                 case KDBUS_ITEM_PAYLOAD_MEMFD:
649                         if (!h)
650                                 return -EBADMSG;
651
652                         n_bytes += d->memfd.size;
653                         break;
654
655                 case KDBUS_ITEM_FDS: {
656                         int *f;
657                         unsigned j;
658
659                         j = l / sizeof(int);
660                         f = realloc(fds, sizeof(int) * (n_fds + j));
661                         if (!f)
662                                 return -ENOMEM;
663
664                         fds = f;
665                         memcpy(fds + n_fds, d->fds, sizeof(int) * j);
666                         n_fds += j;
667                         break;
668                 }
669
670                 case KDBUS_ITEM_SECLABEL:
671                         seclabel = d->str;
672                         break;
673                 }
674         }
675
676         if (!h)
677                 return -EBADMSG;
678
679         r = bus_header_message_size(h, &total);
680         if (r < 0)
681                 return r;
682
683         if (n_bytes != total)
684                 return -EBADMSG;
685
686         /* on kdbus we only speak native endian gvariant, never dbus1
687          * marshalling or reverse endian */
688         if (h->version != 2 ||
689             h->endian != BUS_NATIVE_ENDIAN)
690                 return -EPROTOTYPE;
691
692         r = bus_message_from_header(bus, h, sizeof(struct bus_header), fds, n_fds, NULL, seclabel, 0, &m);
693         if (r < 0)
694                 return r;
695
696         /* The well-known names list is different from the other
697         credentials. If we asked for it, but nothing is there, this
698         means that the list of well-known names is simply empty, not
699         that we lack any data */
700
701         m->creds.mask |= (SD_BUS_CREDS_UNIQUE_NAME|SD_BUS_CREDS_WELL_KNOWN_NAMES) & bus->creds_mask;
702
703         KDBUS_ITEM_FOREACH(d, k, items) {
704                 size_t l;
705
706                 l = d->size - offsetof(struct kdbus_item, data);
707
708                 switch (d->type) {
709
710                 case KDBUS_ITEM_PAYLOAD_OFF: {
711                         size_t begin_body;
712
713                         begin_body = BUS_MESSAGE_BODY_BEGIN(m);
714
715                         if (idx + d->vec.size > begin_body) {
716                                 struct bus_body_part *part;
717
718                                 /* Contains body material */
719
720                                 part = message_append_part(m);
721                                 if (!part) {
722                                         r = -ENOMEM;
723                                         goto fail;
724                                 }
725
726                                 /* A -1 offset is NUL padding. */
727                                 part->is_zero = d->vec.offset == ~0ULL;
728
729                                 if (idx >= begin_body) {
730                                         if (!part->is_zero)
731                                                 part->data = (uint8_t *)k + d->vec.offset;
732                                         part->size = d->vec.size;
733                                 } else {
734                                         if (!part->is_zero)
735                                                 part->data = (uint8_t *)k + d->vec.offset + (begin_body - idx);
736                                         part->size = d->vec.size - (begin_body - idx);
737                                 }
738
739                                 part->sealed = true;
740                         }
741
742                         idx += d->vec.size;
743                         break;
744                 }
745
746                 case KDBUS_ITEM_PAYLOAD_MEMFD: {
747                         struct bus_body_part *part;
748
749                         if (idx < BUS_MESSAGE_BODY_BEGIN(m)) {
750                                 r = -EBADMSG;
751                                 goto fail;
752                         }
753
754                         part = message_append_part(m);
755                         if (!part) {
756                                 r = -ENOMEM;
757                                 goto fail;
758                         }
759
760                         part->memfd = d->memfd.fd;
761                         part->size = d->memfd.size;
762                         part->sealed = true;
763
764                         idx += d->memfd.size;
765                         break;
766                 }
767
768                 case KDBUS_ITEM_CREDS:
769                         m->creds.pid_starttime = d->creds.starttime / NSEC_PER_USEC;
770                         m->creds.uid = d->creds.uid;
771                         m->creds.gid = d->creds.gid;
772                         m->creds.pid = d->creds.pid;
773                         m->creds.tid = d->creds.tid;
774                         m->creds.mask |= (SD_BUS_CREDS_UID|SD_BUS_CREDS_GID|SD_BUS_CREDS_PID|SD_BUS_CREDS_PID_STARTTIME|SD_BUS_CREDS_TID) & bus->creds_mask;
775                         break;
776
777                 case KDBUS_ITEM_TIMESTAMP:
778                         m->realtime = d->timestamp.realtime_ns / NSEC_PER_USEC;
779                         m->monotonic = d->timestamp.monotonic_ns / NSEC_PER_USEC;
780                         break;
781
782                 case KDBUS_ITEM_PID_COMM:
783                         m->creds.comm = d->str;
784                         m->creds.mask |= SD_BUS_CREDS_COMM & bus->creds_mask;
785                         break;
786
787                 case KDBUS_ITEM_TID_COMM:
788                         m->creds.tid_comm = d->str;
789                         m->creds.mask |= SD_BUS_CREDS_TID_COMM & bus->creds_mask;
790                         break;
791
792                 case KDBUS_ITEM_EXE:
793                         m->creds.exe = d->str;
794                         m->creds.mask |= SD_BUS_CREDS_EXE & bus->creds_mask;
795                         break;
796
797                 case KDBUS_ITEM_CMDLINE:
798                         m->creds.cmdline = d->str;
799                         m->creds.cmdline_size = l;
800                         m->creds.mask |= SD_BUS_CREDS_CMDLINE & bus->creds_mask;
801                         break;
802
803                 case KDBUS_ITEM_CGROUP:
804                         m->creds.cgroup = d->str;
805                         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;
806                         break;
807
808                 case KDBUS_ITEM_AUDIT:
809                         m->creds.audit_session_id = d->audit.sessionid;
810                         m->creds.audit_login_uid = d->audit.loginuid;
811                         m->creds.mask |= (SD_BUS_CREDS_AUDIT_SESSION_ID|SD_BUS_CREDS_AUDIT_LOGIN_UID) & bus->creds_mask;
812                         break;
813
814                 case KDBUS_ITEM_CAPS:
815                         m->creds.capability = d->data;
816                         m->creds.capability_size = l;
817                         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;
818                         break;
819
820                 case KDBUS_ITEM_DST_NAME:
821                         destination = d->str;
822                         break;
823
824                 case KDBUS_ITEM_NAME:
825                         r = strv_extend(&m->creds.well_known_names, d->name.name);
826                         if (r < 0)
827                                 goto fail;
828                         break;
829
830                 case KDBUS_ITEM_FDS:
831                 case KDBUS_ITEM_SECLABEL:
832                         break;
833
834                 default:
835                         log_debug("Got unknown field from kernel %llu", d->type);
836                 }
837         }
838
839         r = bus_message_parse_fields(m);
840         if (r < 0)
841                 goto fail;
842
843         /* Override information from the user header with data from the kernel */
844         if (k->src_id == KDBUS_SRC_ID_KERNEL)
845                 m->sender = m->creds.unique_name = (char*) "org.freedesktop.DBus";
846         else {
847                 snprintf(m->sender_buffer, sizeof(m->sender_buffer), ":1.%llu", (unsigned long long) k->src_id);
848                 m->sender = m->creds.unique_name = m->sender_buffer;
849         }
850
851         if (destination)
852                 m->destination = destination;
853         else if (k->dst_id == KDBUS_DST_ID_BROADCAST)
854                 m->destination = NULL;
855         else if (k->dst_id == KDBUS_DST_ID_NAME)
856                 m->destination = bus->unique_name; /* fill in unique name if the well-known name is missing */
857         else {
858                 snprintf(m->destination_buffer, sizeof(m->destination_buffer), ":1.%llu", (unsigned long long) k->dst_id);
859                 m->destination = m->destination_buffer;
860         }
861
862         /* We take possession of the kmsg struct now */
863         m->kdbus = k;
864         m->release_kdbus = true;
865         m->free_fds = true;
866         fds = NULL;
867
868         bus->rqueue[bus->rqueue_size++] = m;
869
870         return 1;
871
872 fail:
873         if (m) {
874                 struct bus_body_part *part;
875                 unsigned i;
876
877                 /* Make sure the memfds are not freed twice */
878                 MESSAGE_FOREACH_PART(part, i, m)
879                         if (part->memfd >= 0)
880                                 part->memfd = -1;
881
882                 sd_bus_message_unref(m);
883         }
884
885         return r;
886 }
887
888 int bus_kernel_read_message(sd_bus *bus) {
889         struct kdbus_msg *k;
890         uint64_t off;
891         int r;
892
893         assert(bus);
894
895         r = bus_rqueue_make_room(bus);
896         if (r < 0)
897                 return r;
898
899         r = ioctl(bus->input_fd, KDBUS_CMD_MSG_RECV, &off);
900         if (r < 0) {
901                 if (errno == EAGAIN)
902                         return 0;
903
904                 return -errno;
905         }
906         k = (struct kdbus_msg *)((uint8_t *)bus->kdbus_buffer + off);
907
908         if (k->payload_type == KDBUS_PAYLOAD_DBUS) {
909                 r = bus_kernel_make_message(bus, k);
910
911                 /* Anybody can send us invalid messages, let's just drop them. */
912                 if (r == -EBADMSG || r == -EPROTOTYPE) {
913                         log_debug("Ignoring invalid message: %s", strerror(-r));
914                         r = 0;
915                 }
916
917         } else if (k->payload_type == KDBUS_PAYLOAD_KERNEL)
918                 r = bus_kernel_translate_message(bus, k);
919         else
920                 r = 0;
921
922         if (r <= 0)
923                 close_kdbus_msg(bus, k);
924
925         return r < 0 ? r : 1;
926 }
927
928 int bus_kernel_pop_memfd(sd_bus *bus, void **address, size_t *mapped, size_t *allocated) {
929         struct memfd_cache *c;
930         int fd;
931
932         assert(address);
933         assert(mapped);
934         assert(allocated);
935
936         if (!bus || !bus->is_kernel)
937                 return -ENOTSUP;
938
939         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
940
941         if (bus->n_memfd_cache <= 0) {
942                 int r;
943
944                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
945
946                 r = ioctl(bus->input_fd, KDBUS_CMD_MEMFD_NEW, &fd);
947                 if (r < 0)
948                         return -errno;
949
950                 *address = NULL;
951                 *mapped = 0;
952                 *allocated = 0;
953                 return fd;
954         }
955
956         c = &bus->memfd_cache[--bus->n_memfd_cache];
957
958         assert(c->fd >= 0);
959         assert(c->mapped == 0 || c->address);
960
961         *address = c->address;
962         *mapped = c->mapped;
963         *allocated = c->allocated;
964         fd = c->fd;
965
966         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
967
968         return fd;
969 }
970
971 static void close_and_munmap(int fd, void *address, size_t size) {
972         if (size > 0)
973                 assert_se(munmap(address, PAGE_ALIGN(size)) >= 0);
974
975         close_nointr_nofail(fd);
976 }
977
978 void bus_kernel_push_memfd(sd_bus *bus, int fd, void *address, size_t mapped, size_t allocated) {
979         struct memfd_cache *c;
980         uint64_t max_mapped = PAGE_ALIGN(MEMFD_CACHE_ITEM_SIZE_MAX);
981
982         assert(fd >= 0);
983         assert(mapped == 0 || address);
984
985         if (!bus || !bus->is_kernel) {
986                 close_and_munmap(fd, address, mapped);
987                 return;
988         }
989
990         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
991
992         if (bus->n_memfd_cache >= ELEMENTSOF(bus->memfd_cache)) {
993                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
994
995                 close_and_munmap(fd, address, mapped);
996                 return;
997         }
998
999         c = &bus->memfd_cache[bus->n_memfd_cache++];
1000         c->fd = fd;
1001         c->address = address;
1002
1003         /* If overly long, let's return a bit to the OS */
1004         if (mapped > max_mapped) {
1005                 assert_se(ioctl(fd, KDBUS_CMD_MEMFD_SIZE_SET, &max_mapped) >= 0);
1006                 assert_se(munmap((uint8_t*) address + max_mapped, PAGE_ALIGN(mapped - max_mapped)) >= 0);
1007                 c->mapped = c->allocated = max_mapped;
1008         } else {
1009                 c->mapped = mapped;
1010                 c->allocated = allocated;
1011         }
1012
1013         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1014 }
1015
1016 void bus_kernel_flush_memfd(sd_bus *b) {
1017         unsigned i;
1018
1019         assert(b);
1020
1021         for (i = 0; i < b->n_memfd_cache; i++)
1022                 close_and_munmap(b->memfd_cache[i].fd, b->memfd_cache[i].address, b->memfd_cache[i].mapped);
1023 }
1024
1025 int kdbus_translate_request_name_flags(uint64_t flags, uint64_t *kdbus_flags) {
1026         uint64_t f = 0;
1027
1028         assert(kdbus_flags);
1029
1030         if (flags & SD_BUS_NAME_ALLOW_REPLACEMENT)
1031                 f |= KDBUS_NAME_ALLOW_REPLACEMENT;
1032
1033         if (flags & SD_BUS_NAME_REPLACE_EXISTING)
1034                 f |= KDBUS_NAME_REPLACE_EXISTING;
1035
1036         if (flags & SD_BUS_NAME_QUEUE)
1037                 f |= KDBUS_NAME_QUEUE;
1038
1039         *kdbus_flags = f;
1040         return 0;
1041 }
1042
1043 int kdbus_translate_attach_flags(uint64_t mask, uint64_t *kdbus_mask) {
1044         uint64_t m = 0;
1045
1046         assert(kdbus_mask);
1047
1048         if (mask & (SD_BUS_CREDS_UID|SD_BUS_CREDS_GID|SD_BUS_CREDS_PID|SD_BUS_CREDS_PID_STARTTIME|SD_BUS_CREDS_TID))
1049                 m |= KDBUS_ATTACH_CREDS;
1050
1051         if (mask & (SD_BUS_CREDS_COMM|SD_BUS_CREDS_TID_COMM))
1052                 m |= KDBUS_ATTACH_COMM;
1053
1054         if (mask & SD_BUS_CREDS_EXE)
1055                 m |= KDBUS_ATTACH_EXE;
1056
1057         if (mask & SD_BUS_CREDS_CMDLINE)
1058                 m |= KDBUS_ATTACH_CMDLINE;
1059
1060         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))
1061                 m |= KDBUS_ATTACH_CGROUP;
1062
1063         if (mask & (SD_BUS_CREDS_EFFECTIVE_CAPS|SD_BUS_CREDS_PERMITTED_CAPS|SD_BUS_CREDS_INHERITABLE_CAPS|SD_BUS_CREDS_BOUNDING_CAPS))
1064                 m |= KDBUS_ATTACH_CAPS;
1065
1066         if (mask & SD_BUS_CREDS_SELINUX_CONTEXT)
1067                 m |= KDBUS_ATTACH_SECLABEL;
1068
1069         if (mask & (SD_BUS_CREDS_AUDIT_SESSION_ID|SD_BUS_CREDS_AUDIT_LOGIN_UID))
1070                 m |= KDBUS_ATTACH_AUDIT;
1071
1072         if (mask & SD_BUS_CREDS_WELL_KNOWN_NAMES)
1073                 m |= KDBUS_ATTACH_NAMES;
1074
1075         *kdbus_mask = m;
1076         return 0;
1077 }
1078
1079 int bus_kernel_create_bus(const char *name, char **s) {
1080         struct kdbus_cmd_make *make;
1081         struct kdbus_item *n;
1082         int fd;
1083
1084         assert(name);
1085         assert(s);
1086
1087         fd = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
1088         if (fd < 0)
1089                 return -errno;
1090
1091         make = alloca0(ALIGN8(offsetof(struct kdbus_cmd_make, items) +
1092                               offsetof(struct kdbus_item, data64) + sizeof(uint64_t) +
1093                               offsetof(struct kdbus_item, str) +
1094                               DECIMAL_STR_MAX(uid_t) + 1 + strlen(name) + 1));
1095
1096         make->size = offsetof(struct kdbus_cmd_make, items);
1097
1098         n = make->items;
1099         n->size = offsetof(struct kdbus_item, data64) + sizeof(uint64_t);
1100         n->type = KDBUS_ITEM_BLOOM_SIZE;
1101         n->data64[0] = BLOOM_SIZE;
1102         assert_cc(BLOOM_SIZE % 8 == 0);
1103         make->size += ALIGN8(n->size);
1104
1105         n = KDBUS_ITEM_NEXT(n);
1106         sprintf(n->str, "%lu-%s", (unsigned long) getuid(), name);
1107         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1108         n->type = KDBUS_ITEM_MAKE_NAME;
1109         make->size += ALIGN8(n->size);
1110
1111         make->flags = KDBUS_MAKE_POLICY_OPEN;
1112
1113         if (ioctl(fd, KDBUS_CMD_BUS_MAKE, make) < 0) {
1114                 close_nointr_nofail(fd);
1115                 return -errno;
1116         }
1117
1118         /* The higher 32bit of the flags field are considered
1119          * 'incompatible flags'. Refuse them all for now. */
1120         if (make->flags > 0xFFFFFFFFULL) {
1121                 close_nointr_nofail(fd);
1122                 return -ENOTSUP;
1123         }
1124
1125         if (s) {
1126                 char *p;
1127
1128                 p = strjoin("/dev/kdbus/", n->str, "/bus", NULL);
1129                 if (!p) {
1130                         close_nointr_nofail(fd);
1131                         return -ENOMEM;
1132                 }
1133
1134                 *s = p;
1135         }
1136
1137         return fd;
1138 }
1139
1140 int bus_kernel_create_starter(const char *bus, const char *name) {
1141         struct kdbus_cmd_hello *hello;
1142         struct kdbus_item *n;
1143         char *p;
1144         int fd;
1145
1146         assert(bus);
1147         assert(name);
1148
1149         p = alloca(sizeof("/dev/kdbus/") - 1 + DECIMAL_STR_MAX(uid_t) + 1 + strlen(bus) + sizeof("/bus"));
1150         sprintf(p, "/dev/kdbus/%lu-%s/bus", (unsigned long) getuid(), bus);
1151
1152         fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
1153         if (fd < 0)
1154                 return -errno;
1155
1156         hello = alloca0(ALIGN8(offsetof(struct kdbus_cmd_hello, items) +
1157                                offsetof(struct kdbus_item, str) +
1158                                strlen(name) + 1));
1159
1160         n = hello->items;
1161         strcpy(n->str, name);
1162         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1163         n->type = KDBUS_ITEM_NAME;
1164
1165         hello->size = ALIGN8(offsetof(struct kdbus_cmd_hello, items) + n->size);
1166         hello->conn_flags = KDBUS_HELLO_ACTIVATOR;
1167         hello->pool_size = KDBUS_POOL_SIZE;
1168
1169         if (ioctl(fd, KDBUS_CMD_HELLO, hello) < 0) {
1170                 close_nointr_nofail(fd);
1171                 return -errno;
1172         }
1173
1174         /* The higher 32bit of both flags fields are considered
1175          * 'incompatible flags'. Refuse them all for now. */
1176         if (hello->bus_flags > 0xFFFFFFFFULL ||
1177             hello->conn_flags > 0xFFFFFFFFULL) {
1178                 close_nointr_nofail(fd);
1179                 return -ENOTSUP;
1180         }
1181
1182         if (hello->bloom_size != BLOOM_SIZE) {
1183                 close_nointr_nofail(fd);
1184                 return -ENOTSUP;
1185         }
1186
1187         return fd;
1188 }
1189
1190 int bus_kernel_create_namespace(const char *name, char **s) {
1191         struct kdbus_cmd_make *make;
1192         struct kdbus_item *n;
1193         int fd;
1194
1195         assert(name);
1196         assert(s);
1197
1198         fd = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
1199         if (fd < 0)
1200                 return -errno;
1201
1202         make = alloca0(ALIGN8(offsetof(struct kdbus_cmd_make, items) +
1203                               offsetof(struct kdbus_item, str) +
1204                               strlen(name) + 1));
1205
1206         n = make->items;
1207         strcpy(n->str, name);
1208         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1209         n->type = KDBUS_ITEM_MAKE_NAME;
1210
1211         make->size = ALIGN8(offsetof(struct kdbus_cmd_make, items) + n->size);
1212         make->flags = KDBUS_MAKE_POLICY_OPEN | KDBUS_MAKE_ACCESS_WORLD;
1213
1214         if (ioctl(fd, KDBUS_CMD_NS_MAKE, make) < 0) {
1215                 close_nointr_nofail(fd);
1216                 return -errno;
1217         }
1218
1219         /* The higher 32bit of the flags field are considered
1220          * 'incompatible flags'. Refuse them all for now. */
1221         if (make->flags > 0xFFFFFFFFULL) {
1222                 close_nointr_nofail(fd);
1223                 return -ENOTSUP;
1224         }
1225
1226         if (s) {
1227                 char *p;
1228
1229                 p = strappend("/dev/kdbus/ns/", name);
1230                 if (!p) {
1231                         close_nointr_nofail(fd);
1232                         return -ENOMEM;
1233                 }
1234
1235                 *s = p;
1236         }
1237
1238         return fd;
1239 }
1240
1241 int bus_kernel_create_monitor(const char *bus) {
1242         struct kdbus_cmd_hello *hello;
1243         char *p;
1244         int fd;
1245
1246         assert(bus);
1247
1248         p = alloca(sizeof("/dev/kdbus/") - 1 + DECIMAL_STR_MAX(uid_t) + 1 + strlen(bus) + sizeof("/bus"));
1249         sprintf(p, "/dev/kdbus/%lu-%s/bus", (unsigned long) getuid(), bus);
1250
1251         fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
1252         if (fd < 0)
1253                 return -errno;
1254
1255         hello = alloca0(sizeof(struct kdbus_cmd_hello));
1256         hello->size = sizeof(struct kdbus_cmd_hello);
1257         hello->conn_flags = KDBUS_HELLO_ACTIVATOR;
1258         hello->pool_size = KDBUS_POOL_SIZE;
1259
1260         if (ioctl(fd, KDBUS_CMD_HELLO, hello) < 0) {
1261                 close_nointr_nofail(fd);
1262                 return -errno;
1263         }
1264
1265         /* The higher 32bit of both flags fields are considered
1266          * 'incompatible flags'. Refuse them all for now. */
1267         if (hello->bus_flags > 0xFFFFFFFFULL ||
1268             hello->conn_flags > 0xFFFFFFFFULL) {
1269                 close_nointr_nofail(fd);
1270                 return -ENOTSUP;
1271         }
1272
1273         return fd;
1274 }
1275
1276 int bus_kernel_try_close(sd_bus *bus) {
1277         assert(bus);
1278         assert(bus->is_kernel);
1279
1280         if (ioctl(bus->input_fd, KDBUS_CMD_BYEBYE) < 0)
1281                 return -errno;
1282
1283         return 0;
1284 }