chiark / gitweb /
bus: properly generate NameOwnerChanged messages when we take from/give back to queue...
[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
367         /* the kernel told us the UUID of the underlying bus */
368         memcpy(b->server_id.bytes, hello.id128, sizeof(b->server_id.bytes));
369
370         return bus_start_running(b);
371 }
372
373 int bus_kernel_connect(sd_bus *b) {
374         assert(b);
375         assert(b->input_fd < 0);
376         assert(b->output_fd < 0);
377         assert(b->kernel);
378
379         if (b->is_server)
380                 return -EINVAL;
381
382         b->input_fd = open(b->kernel, O_RDWR|O_NOCTTY|O_CLOEXEC);
383         if (b->input_fd < 0)
384                 return -errno;
385
386         b->output_fd = b->input_fd;
387
388         return bus_kernel_take_fd(b);
389 }
390
391 int bus_kernel_write_message(sd_bus *bus, sd_bus_message *m) {
392         int r;
393
394         assert(bus);
395         assert(m);
396         assert(bus->state == BUS_RUNNING);
397
398         /* If we can't deliver, we want room for the error message */
399         r = bus_rqueue_make_room(bus);
400         if (r < 0)
401                 return r;
402
403         r = bus_message_setup_kmsg(bus, m);
404         if (r < 0)
405                 return r;
406
407         r = ioctl(bus->output_fd, KDBUS_CMD_MSG_SEND, m->kdbus);
408         if (r < 0) {
409                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
410                 sd_bus_message *reply;
411
412                 if (errno == EAGAIN || errno == EINTR)
413                         return 0;
414                 else if (errno == ENXIO || errno == ESRCH) {
415
416                         /* ENXIO: unique name not known
417                          * ESRCH: well-known name not known */
418
419                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
420                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Destination %s not known", m->destination);
421                         else {
422                                 log_debug("Could not deliver message to %s as destination is not known. Ignoring.", m->destination);
423                                 return 0;
424                         }
425
426                 } else if (errno == EADDRNOTAVAIL) {
427
428                         /* EADDRNOTAVAIL: activation is possible, but turned off in request flags */
429
430                         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
431                                 sd_bus_error_setf(&error, SD_BUS_ERROR_SERVICE_UNKNOWN, "Activation of %s not requested", m->destination);
432                         else {
433                                 log_debug("Could not deliver message to %s as destination is not activated. Ignoring.", m->destination);
434                                 return 0;
435                         }
436                 } else
437                         return -errno;
438
439                 r = bus_message_new_synthetic_error(
440                                 bus,
441                                 BUS_MESSAGE_SERIAL(m),
442                                 &error,
443                                 &reply);
444
445                 if (r < 0)
446                         return r;
447
448                 r = bus_seal_synthetic_message(bus, reply);
449                 if (r < 0)
450                         return r;
451
452                 bus->rqueue[bus->rqueue_size++] = reply;
453
454                 return 0;
455         }
456
457         return 1;
458 }
459
460 static void close_kdbus_msg(sd_bus *bus, struct kdbus_msg *k) {
461         uint64_t off;
462         struct kdbus_item *d;
463
464         assert(bus);
465         assert(k);
466
467         off = (uint8_t *)k - (uint8_t *)bus->kdbus_buffer;
468         ioctl(bus->input_fd, KDBUS_CMD_FREE, &off);
469
470         KDBUS_ITEM_FOREACH(d, k, items) {
471
472                 if (d->type == KDBUS_ITEM_FDS)
473                         close_many(d->fds, (d->size - offsetof(struct kdbus_item, fds)) / sizeof(int));
474                 else if (d->type == KDBUS_ITEM_PAYLOAD_MEMFD)
475                         close_nointr_nofail(d->memfd.fd);
476         }
477 }
478
479 static int push_name_owner_changed(sd_bus *bus, const char *name, const char *old_owner, const char *new_owner) {
480         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
481         int r;
482
483         assert(bus);
484
485         r = sd_bus_message_new_signal(
486                         bus,
487                         "/org/freedesktop/DBus",
488                         "org.freedesktop.DBus",
489                         "NameOwnerChanged",
490                         &m);
491         if (r < 0)
492                 return r;
493
494         r = sd_bus_message_append(m, "sss", name, old_owner, new_owner);
495         if (r < 0)
496                 return r;
497
498         m->sender = "org.freedesktop.DBus";
499
500         r = bus_seal_synthetic_message(bus, m);
501         if (r < 0)
502                 return r;
503
504         bus->rqueue[bus->rqueue_size++] = m;
505         m = NULL;
506
507         return 1;
508 }
509
510 static int translate_name_change(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
511         char new_owner[UNIQUE_NAME_MAX], old_owner[UNIQUE_NAME_MAX];
512
513         assert(bus);
514         assert(k);
515         assert(d);
516
517         if (d->type == KDBUS_ITEM_NAME_ADD || (d->name_change.old_flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_STARTER)))
518                 old_owner[0] = 0;
519         else
520                 sprintf(old_owner, ":1.%llu", (unsigned long long) d->name_change.old_id);
521
522         if (d->type == KDBUS_ITEM_NAME_REMOVE || (d->name_change.new_flags & (KDBUS_NAME_IN_QUEUE|KDBUS_NAME_STARTER))) {
523
524                 if (isempty(old_owner))
525                         return 0;
526
527                 new_owner[0] = 0;
528         } else
529                 sprintf(new_owner, ":1.%llu", (unsigned long long) d->name_change.new_id);
530
531         return push_name_owner_changed(bus, d->name_change.name, old_owner, new_owner);
532 }
533
534 static int translate_id_change(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
535         char owner[UNIQUE_NAME_MAX];
536
537         assert(bus);
538         assert(k);
539         assert(d);
540
541         sprintf(owner, ":1.%llu", d->id_change.id);
542
543         return push_name_owner_changed(
544                         bus, owner,
545                         d->type == KDBUS_ITEM_ID_ADD ? NULL : owner,
546                         d->type == KDBUS_ITEM_ID_ADD ? owner : NULL);
547 }
548
549 static int translate_reply(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) {
550         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
551         int r;
552
553         assert(bus);
554         assert(k);
555         assert(d);
556
557         r = bus_message_new_synthetic_error(
558                         bus,
559                         k->cookie_reply,
560                         d->type == KDBUS_ITEM_REPLY_TIMEOUT ?
561                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out") :
562                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call peer died"),
563                         &m);
564         if (r < 0)
565                 return r;
566
567         m->sender = "org.freedesktop.DBus";
568
569         r = bus_seal_synthetic_message(bus, m);
570         if (r < 0)
571                 return r;
572
573         bus->rqueue[bus->rqueue_size++] = m;
574         m = NULL;
575
576         return 1;
577 }
578
579 static int bus_kernel_translate_message(sd_bus *bus, struct kdbus_msg *k) {
580         struct kdbus_item *d, *found = NULL;
581
582         static int (* const translate[])(sd_bus *bus, struct kdbus_msg *k, struct kdbus_item *d) = {
583                 [KDBUS_ITEM_NAME_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
584                 [KDBUS_ITEM_NAME_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
585                 [KDBUS_ITEM_NAME_CHANGE - _KDBUS_ITEM_KERNEL_BASE] = translate_name_change,
586
587                 [KDBUS_ITEM_ID_ADD - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
588                 [KDBUS_ITEM_ID_REMOVE - _KDBUS_ITEM_KERNEL_BASE] = translate_id_change,
589
590                 [KDBUS_ITEM_REPLY_TIMEOUT - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
591                 [KDBUS_ITEM_REPLY_DEAD - _KDBUS_ITEM_KERNEL_BASE] = translate_reply,
592         };
593
594         assert(bus);
595         assert(k);
596         assert(k->payload_type == KDBUS_PAYLOAD_KERNEL);
597
598         KDBUS_ITEM_FOREACH(d, k, items) {
599                 if (d->type >= _KDBUS_ITEM_KERNEL_BASE && d->type < _KDBUS_ITEM_KERNEL_BASE + ELEMENTSOF(translate)) {
600                         if (found)
601                                 return -EBADMSG;
602                         found = d;
603                 } else
604                         log_debug("Got unknown field from kernel %llu", d->type);
605         }
606
607         if (!found) {
608                 log_debug("Didn't find a kernel message to translate.");
609                 return 0;
610         }
611
612         return translate[found->type - _KDBUS_ITEM_KERNEL_BASE](bus, k, found);
613 }
614
615 static int bus_kernel_make_message(sd_bus *bus, struct kdbus_msg *k) {
616         sd_bus_message *m = NULL;
617         struct kdbus_item *d;
618         unsigned n_fds = 0;
619         _cleanup_free_ int *fds = NULL;
620         struct bus_header *h = NULL;
621         size_t total, n_bytes = 0, idx = 0;
622         const char *destination = NULL, *seclabel = NULL;
623         int r;
624
625         assert(bus);
626         assert(k);
627         assert(k->payload_type == KDBUS_PAYLOAD_DBUS);
628
629         KDBUS_ITEM_FOREACH(d, k, items) {
630                 size_t l;
631
632                 l = d->size - offsetof(struct kdbus_item, data);
633
634                 switch (d->type) {
635
636                 case KDBUS_ITEM_PAYLOAD_OFF:
637                         if (!h) {
638                                 h = (struct bus_header *)((uint8_t *)bus->kdbus_buffer + d->vec.offset);
639
640                                 if (!bus_header_is_complete(h, d->vec.size))
641                                         return -EBADMSG;
642                         }
643
644                         n_bytes += d->vec.size;
645                         break;
646
647                 case KDBUS_ITEM_PAYLOAD_MEMFD:
648                         if (!h)
649                                 return -EBADMSG;
650
651                         n_bytes += d->memfd.size;
652                         break;
653
654                 case KDBUS_ITEM_FDS: {
655                         int *f;
656                         unsigned j;
657
658                         j = l / sizeof(int);
659                         f = realloc(fds, sizeof(int) * (n_fds + j));
660                         if (!f)
661                                 return -ENOMEM;
662
663                         fds = f;
664                         memcpy(fds + n_fds, d->fds, sizeof(int) * j);
665                         n_fds += j;
666                         break;
667                 }
668
669                 case KDBUS_ITEM_SECLABEL:
670                         seclabel = d->str;
671                         break;
672                 }
673         }
674
675         if (!h)
676                 return -EBADMSG;
677
678         r = bus_header_message_size(h, &total);
679         if (r < 0)
680                 return r;
681
682         if (n_bytes != total)
683                 return -EBADMSG;
684
685         /* on kdbus we only speak native endian gvariant, never dbus1
686          * marshalling or reverse endian */
687         if (h->version != 2 ||
688             h->endian != BUS_NATIVE_ENDIAN)
689                 return -EPROTOTYPE;
690
691         r = bus_message_from_header(bus, h, sizeof(struct bus_header), fds, n_fds, NULL, seclabel, 0, &m);
692         if (r < 0)
693                 return r;
694
695         KDBUS_ITEM_FOREACH(d, k, items) {
696                 size_t l;
697
698                 l = d->size - offsetof(struct kdbus_item, data);
699
700                 switch (d->type) {
701
702                 case KDBUS_ITEM_PAYLOAD_OFF: {
703                         size_t begin_body;
704
705                         begin_body = BUS_MESSAGE_BODY_BEGIN(m);
706
707                         if (idx + d->vec.size > begin_body) {
708                                 struct bus_body_part *part;
709
710                                 /* Contains body material */
711
712                                 part = message_append_part(m);
713                                 if (!part) {
714                                         r = -ENOMEM;
715                                         goto fail;
716                                 }
717
718                                 /* A -1 offset is NUL padding. */
719                                 part->is_zero = d->vec.offset == ~0ULL;
720
721                                 if (idx >= begin_body) {
722                                         if (!part->is_zero)
723                                                 part->data = (uint8_t *)bus->kdbus_buffer + d->vec.offset;
724                                         part->size = d->vec.size;
725                                 } else {
726                                         if (!part->is_zero)
727                                                 part->data = (uint8_t *)bus->kdbus_buffer + d->vec.offset + (begin_body - idx);
728                                         part->size = d->vec.size - (begin_body - idx);
729                                 }
730
731                                 part->sealed = true;
732                         }
733
734                         idx += d->vec.size;
735                         break;
736                 }
737
738                 case KDBUS_ITEM_PAYLOAD_MEMFD: {
739                         struct bus_body_part *part;
740
741                         if (idx < BUS_MESSAGE_BODY_BEGIN(m)) {
742                                 r = -EBADMSG;
743                                 goto fail;
744                         }
745
746                         part = message_append_part(m);
747                         if (!part) {
748                                 r = -ENOMEM;
749                                 goto fail;
750                         }
751
752                         part->memfd = d->memfd.fd;
753                         part->size = d->memfd.size;
754                         part->sealed = true;
755
756                         idx += d->memfd.size;
757                         break;
758                 }
759
760                 case KDBUS_ITEM_CREDS:
761                         m->creds.pid_starttime = d->creds.starttime / NSEC_PER_USEC;
762                         m->creds.uid = d->creds.uid;
763                         m->creds.gid = d->creds.gid;
764                         m->creds.pid = d->creds.pid;
765                         m->creds.tid = d->creds.tid;
766                         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;
767                         break;
768
769                 case KDBUS_ITEM_TIMESTAMP:
770                         m->realtime = d->timestamp.realtime_ns / NSEC_PER_USEC;
771                         m->monotonic = d->timestamp.monotonic_ns / NSEC_PER_USEC;
772                         break;
773
774                 case KDBUS_ITEM_PID_COMM:
775                         m->creds.comm = d->str;
776                         m->creds.mask |= SD_BUS_CREDS_COMM & bus->creds_mask;
777                         break;
778
779                 case KDBUS_ITEM_TID_COMM:
780                         m->creds.tid_comm = d->str;
781                         m->creds.mask |= SD_BUS_CREDS_TID_COMM & bus->creds_mask;
782                         break;
783
784                 case KDBUS_ITEM_EXE:
785                         m->creds.exe = d->str;
786                         m->creds.mask |= SD_BUS_CREDS_EXE & bus->creds_mask;
787                         break;
788
789                 case KDBUS_ITEM_CMDLINE:
790                         m->creds.cmdline = d->str;
791                         m->creds.cmdline_size = l;
792                         m->creds.mask |= SD_BUS_CREDS_CMDLINE & bus->creds_mask;
793                         break;
794
795                 case KDBUS_ITEM_CGROUP:
796                         m->creds.cgroup = d->str;
797                         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;
798                         break;
799
800                 case KDBUS_ITEM_AUDIT:
801                         m->creds.audit_session_id = d->audit.sessionid;
802                         m->creds.audit_login_uid = d->audit.loginuid;
803                         m->creds.mask |= (SD_BUS_CREDS_AUDIT_SESSION_ID|SD_BUS_CREDS_AUDIT_LOGIN_UID) & bus->creds_mask;
804                         break;
805
806                 case KDBUS_ITEM_CAPS:
807                         m->creds.capability = d->data;
808                         m->creds.capability_size = l;
809                         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;
810                         break;
811
812                 case KDBUS_ITEM_DST_NAME:
813                         destination = d->str;
814                         break;
815
816                 case KDBUS_ITEM_NAME:
817                         r = strv_extend(&m->creds.well_known_names, d->name.name);
818                         if (r < 0)
819                                 goto fail;
820                         m->creds.mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES & bus->creds_mask;
821                         break;
822
823                 case KDBUS_ITEM_FDS:
824                 case KDBUS_ITEM_SECLABEL:
825                         break;
826
827                 default:
828                         log_debug("Got unknown field from kernel %llu", d->type);
829                 }
830         }
831
832         r = bus_message_parse_fields(m);
833         if (r < 0)
834                 goto fail;
835
836         if (k->src_id == KDBUS_SRC_ID_KERNEL)
837                 m->sender = "org.freedesktop.DBus";
838         else {
839                 snprintf(m->sender_buffer, sizeof(m->sender_buffer), ":1.%llu", (unsigned long long) k->src_id);
840                 m->sender = m->creds.unique_name = m->sender_buffer;
841                 m->creds.mask |= SD_BUS_CREDS_UNIQUE_NAME & bus->creds_mask;
842         }
843
844         if (!m->destination) {
845                 if (destination)
846                         m->destination = destination;
847                 else if (k->dst_id != KDBUS_DST_ID_NAME &&
848                          k->dst_id != KDBUS_DST_ID_BROADCAST) {
849                         snprintf(m->destination_buffer, sizeof(m->destination_buffer), ":1.%llu", (unsigned long long) k->dst_id);
850                         m->destination = m->destination_buffer;
851                 }
852         }
853
854         /* We take possession of the kmsg struct now */
855         m->kdbus = k;
856         m->release_kdbus = true;
857         m->free_fds = true;
858         fds = NULL;
859
860         bus->rqueue[bus->rqueue_size++] = m;
861
862         return 1;
863
864 fail:
865         if (m) {
866                 struct bus_body_part *part;
867                 unsigned i;
868
869                 /* Make sure the memfds are not freed twice */
870                 MESSAGE_FOREACH_PART(part, i, m)
871                         if (part->memfd >= 0)
872                                 part->memfd = -1;
873
874                 sd_bus_message_unref(m);
875         }
876
877         return r;
878 }
879
880 int bus_kernel_read_message(sd_bus *bus) {
881         struct kdbus_msg *k;
882         uint64_t off;
883         int r;
884
885         assert(bus);
886
887         r = bus_rqueue_make_room(bus);
888         if (r < 0)
889                 return r;
890
891         r = ioctl(bus->input_fd, KDBUS_CMD_MSG_RECV, &off);
892         if (r < 0) {
893                 if (errno == EAGAIN)
894                         return 0;
895
896                 return -errno;
897         }
898         k = (struct kdbus_msg *)((uint8_t *)bus->kdbus_buffer + off);
899
900         if (k->payload_type == KDBUS_PAYLOAD_DBUS) {
901                 r = bus_kernel_make_message(bus, k);
902
903                 /* Anybody can send us invalid messages, let's just drop them. */
904                 if (r == -EBADMSG || r == -EPROTOTYPE) {
905                         log_debug("Ignoring invalid message: %s", strerror(-r));
906                         r = 0;
907                 }
908
909         } else if (k->payload_type == KDBUS_PAYLOAD_KERNEL)
910                 r = bus_kernel_translate_message(bus, k);
911         else
912                 r = 0;
913
914         if (r <= 0)
915                 close_kdbus_msg(bus, k);
916
917         return r < 0 ? r : 1;
918 }
919
920 int bus_kernel_pop_memfd(sd_bus *bus, void **address, size_t *size) {
921         struct memfd_cache *c;
922         int fd;
923
924         assert(address);
925         assert(size);
926
927         if (!bus || !bus->is_kernel)
928                 return -ENOTSUP;
929
930         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
931
932         if (bus->n_memfd_cache <= 0) {
933                 int r;
934
935                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
936
937                 r = ioctl(bus->input_fd, KDBUS_CMD_MEMFD_NEW, &fd);
938                 if (r < 0)
939                         return -errno;
940
941                 *address = NULL;
942                 *size = 0;
943                 return fd;
944         }
945
946         c = &bus->memfd_cache[--bus->n_memfd_cache];
947
948         assert(c->fd >= 0);
949         assert(c->size == 0 || c->address);
950
951         *address = c->address;
952         *size = c->size;
953         fd = c->fd;
954
955         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
956
957         return fd;
958 }
959
960 static void close_and_munmap(int fd, void *address, size_t size) {
961         if (size > 0)
962                 assert_se(munmap(address, PAGE_ALIGN(size)) >= 0);
963
964         close_nointr_nofail(fd);
965 }
966
967 void bus_kernel_push_memfd(sd_bus *bus, int fd, void *address, size_t size) {
968         struct memfd_cache *c;
969         uint64_t max_sz = PAGE_ALIGN(MEMFD_CACHE_ITEM_SIZE_MAX);
970
971         assert(fd >= 0);
972         assert(size == 0 || address);
973
974         if (!bus || !bus->is_kernel) {
975                 close_and_munmap(fd, address, size);
976                 return;
977         }
978
979         assert_se(pthread_mutex_lock(&bus->memfd_cache_mutex) >= 0);
980
981         if (bus->n_memfd_cache >= ELEMENTSOF(bus->memfd_cache)) {
982                 assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
983
984                 close_and_munmap(fd, address, size);
985                 return;
986         }
987
988         c = &bus->memfd_cache[bus->n_memfd_cache++];
989         c->fd = fd;
990         c->address = address;
991
992         /* If overly long, let's return a bit to the OS */
993         if (size > max_sz) {
994                 assert_se(ioctl(fd, KDBUS_CMD_MEMFD_SIZE_SET, &max_sz) >= 0);
995                 assert_se(munmap((uint8_t*) address + max_sz, PAGE_ALIGN(size - max_sz)) >= 0);
996                 c->size = max_sz;
997         } else
998                 c->size = size;
999
1000         assert_se(pthread_mutex_unlock(&bus->memfd_cache_mutex) >= 0);
1001 }
1002
1003 void bus_kernel_flush_memfd(sd_bus *b) {
1004         unsigned i;
1005
1006         assert(b);
1007
1008         for (i = 0; i < b->n_memfd_cache; i++)
1009                 close_and_munmap(b->memfd_cache[i].fd, b->memfd_cache[i].address, b->memfd_cache[i].size);
1010 }
1011
1012 int kdbus_translate_request_name_flags(uint64_t flags, uint64_t *kdbus_flags) {
1013         uint64_t f = 0;
1014
1015         assert(kdbus_flags);
1016
1017         if (flags & SD_BUS_NAME_ALLOW_REPLACEMENT)
1018                 f |= KDBUS_NAME_ALLOW_REPLACEMENT;
1019
1020         if (flags & SD_BUS_NAME_REPLACE_EXISTING)
1021                 f |= KDBUS_NAME_REPLACE_EXISTING;
1022
1023         if (!(flags & SD_BUS_NAME_DO_NOT_QUEUE))
1024                 f |= KDBUS_NAME_QUEUE;
1025
1026         *kdbus_flags = f;
1027         return 0;
1028 }
1029
1030 int kdbus_translate_attach_flags(uint64_t mask, uint64_t *kdbus_mask) {
1031         uint64_t m = 0;
1032
1033         assert(kdbus_mask);
1034
1035         if (mask & (SD_BUS_CREDS_UID|SD_BUS_CREDS_GID|SD_BUS_CREDS_PID|SD_BUS_CREDS_PID_STARTTIME|SD_BUS_CREDS_TID))
1036                 m |= KDBUS_ATTACH_CREDS;
1037
1038         if (mask & (SD_BUS_CREDS_COMM|SD_BUS_CREDS_TID_COMM))
1039                 m |= KDBUS_ATTACH_COMM;
1040
1041         if (mask & SD_BUS_CREDS_EXE)
1042                 m |= KDBUS_ATTACH_EXE;
1043
1044         if (mask & SD_BUS_CREDS_CMDLINE)
1045                 m |= KDBUS_ATTACH_CMDLINE;
1046
1047         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))
1048                 m |= KDBUS_ATTACH_CGROUP;
1049
1050         if (mask & (SD_BUS_CREDS_EFFECTIVE_CAPS|SD_BUS_CREDS_PERMITTED_CAPS|SD_BUS_CREDS_INHERITABLE_CAPS|SD_BUS_CREDS_BOUNDING_CAPS))
1051                 m |= KDBUS_ATTACH_CAPS;
1052
1053         if (mask & SD_BUS_CREDS_SELINUX_CONTEXT)
1054                 m |= KDBUS_ATTACH_SECLABEL;
1055
1056         if (mask & (SD_BUS_CREDS_AUDIT_SESSION_ID|SD_BUS_CREDS_AUDIT_LOGIN_UID))
1057                 m |= KDBUS_ATTACH_AUDIT;
1058
1059         if (mask & SD_BUS_CREDS_WELL_KNOWN_NAMES)
1060                 m |= KDBUS_ATTACH_NAMES;
1061
1062         *kdbus_mask = m;
1063         return 0;
1064 }
1065
1066 int bus_kernel_create_bus(const char *name, char **s) {
1067         struct kdbus_cmd_bus_make *make;
1068         struct kdbus_item *n;
1069         int fd;
1070
1071         assert(name);
1072         assert(s);
1073
1074         fd = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
1075         if (fd < 0)
1076                 return -errno;
1077
1078         make = alloca0(ALIGN8(offsetof(struct kdbus_cmd_bus_make, items) +
1079                               offsetof(struct kdbus_item, str) +
1080                               DECIMAL_STR_MAX(uid_t) + 1 + strlen(name) + 1));
1081
1082         n = make->items;
1083         sprintf(n->str, "%lu-%s", (unsigned long) getuid(), name);
1084         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1085         n->type = KDBUS_ITEM_MAKE_NAME;
1086
1087         make->size = ALIGN8(offsetof(struct kdbus_cmd_bus_make, items) + n->size);
1088         make->flags = KDBUS_MAKE_POLICY_OPEN;
1089         make->bloom_size = BLOOM_SIZE;
1090         assert_cc(BLOOM_SIZE % 8 == 0);
1091
1092         if (ioctl(fd, KDBUS_CMD_BUS_MAKE, make) < 0) {
1093                 close_nointr_nofail(fd);
1094                 return -errno;
1095         }
1096
1097         /* The higher 32bit of the flags field are considered
1098          * 'incompatible flags'. Refuse them all for now. */
1099         if (make->flags > 0xFFFFFFFFULL) {
1100                 close_nointr_nofail(fd);
1101                 return -ENOTSUP;
1102         }
1103
1104         if (s) {
1105                 char *p;
1106
1107                 p = strjoin("/dev/kdbus/", n->str, "/bus", NULL);
1108                 if (!p) {
1109                         close_nointr_nofail(fd);
1110                         return -ENOMEM;
1111                 }
1112
1113                 *s = p;
1114         }
1115
1116         return fd;
1117 }
1118
1119 int bus_kernel_create_starter(const char *bus, const char *name) {
1120         struct kdbus_cmd_hello *hello;
1121         struct kdbus_item *n;
1122         char *p;
1123         int fd;
1124
1125         assert(bus);
1126         assert(name);
1127
1128         p = alloca(sizeof("/dev/kdbus/") - 1 + DECIMAL_STR_MAX(uid_t) + 1 + strlen(bus) + sizeof("/bus"));
1129         sprintf(p, "/dev/kdbus/%lu-%s/bus", (unsigned long) getuid(), bus);
1130
1131         fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
1132         if (fd < 0)
1133                 return -errno;
1134
1135         hello = alloca0(ALIGN8(offsetof(struct kdbus_cmd_hello, items) +
1136                                offsetof(struct kdbus_item, str) +
1137                                strlen(name) + 1));
1138
1139         n = hello->items;
1140         strcpy(n->str, name);
1141         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1142         n->type = KDBUS_ITEM_STARTER_NAME;
1143
1144         hello->size = ALIGN8(offsetof(struct kdbus_cmd_hello, items) + n->size);
1145         hello->conn_flags = KDBUS_HELLO_STARTER;
1146         hello->pool_size = KDBUS_POOL_SIZE;
1147
1148         if (ioctl(fd, KDBUS_CMD_HELLO, hello) < 0) {
1149                 close_nointr_nofail(fd);
1150                 return -errno;
1151         }
1152
1153         /* The higher 32bit of both flags fields are considered
1154          * 'incompatible flags'. Refuse them all for now. */
1155         if (hello->bus_flags > 0xFFFFFFFFULL ||
1156             hello->conn_flags > 0xFFFFFFFFULL) {
1157                 close_nointr_nofail(fd);
1158                 return -ENOTSUP;
1159         }
1160
1161         if (hello->bloom_size != BLOOM_SIZE) {
1162                 close_nointr_nofail(fd);
1163                 return -ENOTSUP;
1164         }
1165
1166         return fd;
1167 }
1168
1169 int bus_kernel_create_namespace(const char *name, char **s) {
1170         struct kdbus_cmd_ns_make *make;
1171         struct kdbus_item *n;
1172         int fd;
1173
1174         assert(name);
1175         assert(s);
1176
1177         fd = open("/dev/kdbus/control", O_RDWR|O_NOCTTY|O_CLOEXEC);
1178         if (fd < 0)
1179                 return -errno;
1180
1181         make = alloca0(ALIGN8(offsetof(struct kdbus_cmd_ns_make, items) +
1182                               offsetof(struct kdbus_item, str) +
1183                               strlen(name) + 1));
1184
1185         n = make->items;
1186         strcpy(n->str, name);
1187         n->size = offsetof(struct kdbus_item, str) + strlen(n->str) + 1;
1188         n->type = KDBUS_ITEM_MAKE_NAME;
1189
1190         make->size = ALIGN8(offsetof(struct kdbus_cmd_ns_make, items) + n->size);
1191         make->flags = KDBUS_MAKE_POLICY_OPEN | KDBUS_MAKE_ACCESS_WORLD;
1192
1193         if (ioctl(fd, KDBUS_CMD_NS_MAKE, make) < 0) {
1194                 close_nointr_nofail(fd);
1195                 return -errno;
1196         }
1197
1198         /* The higher 32bit of the flags field are considered
1199          * 'incompatible flags'. Refuse them all for now. */
1200         if (make->flags > 0xFFFFFFFFULL) {
1201                 close_nointr_nofail(fd);
1202                 return -ENOTSUP;
1203         }
1204
1205         if (s) {
1206                 char *p;
1207
1208                 p = strappend("/dev/kdbus/ns/", name);
1209                 if (!p) {
1210                         close_nointr_nofail(fd);
1211                         return -ENOMEM;
1212                 }
1213
1214                 *s = p;
1215         }
1216
1217         return fd;
1218 }
1219
1220 int bus_kernel_monitor(sd_bus *bus) {
1221         struct kdbus_cmd_monitor cmd_monitor;
1222         int r;
1223
1224         assert(bus);
1225
1226         cmd_monitor.id = 0;
1227         cmd_monitor.flags = KDBUS_MONITOR_ENABLE;
1228
1229         r = ioctl(bus->input_fd, KDBUS_CMD_MONITOR, &cmd_monitor);
1230         if (r < 0)
1231                 return -errno;
1232
1233         return 1;
1234 }