1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <stdlib.h>
7 #include <sys/ioctl.h>
8 #include <sys/resource.h>
9 #include <sys/socket.h>
10 #include <unistd.h>
11 
12 #include "sd-bus.h"
13 #include "sd-daemon.h"
14 #include "sd-event.h"
15 #include "sd-id128.h"
16 
17 #include "bus-common-errors.h"
18 #include "bus-internal.h"
19 #include "bus-label.h"
20 #include "bus-util.h"
21 #include "path-util.h"
22 #include "socket-util.h"
23 #include "stdio-util.h"
24 
name_owner_change_callback(sd_bus_message * m,void * userdata,sd_bus_error * ret_error)25 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
26         sd_event *e = userdata;
27 
28         assert(m);
29         assert(e);
30 
31         sd_bus_close(sd_bus_message_get_bus(m));
32         sd_event_exit(e, 0);
33 
34         return 1;
35 }
36 
bus_log_address_error(int r,BusTransport transport)37 int bus_log_address_error(int r, BusTransport transport) {
38         bool hint = transport == BUS_TRANSPORT_LOCAL && r == -ENOMEDIUM;
39 
40         return log_error_errno(r,
41                                hint ? "Failed to set bus address: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
42                                       "Failed to set bus address: %m");
43 }
44 
bus_log_connect_error(int r,BusTransport transport)45 int bus_log_connect_error(int r, BusTransport transport) {
46         bool hint_vars = transport == BUS_TRANSPORT_LOCAL && r == -ENOMEDIUM,
47              hint_addr = transport == BUS_TRANSPORT_LOCAL && ERRNO_IS_PRIVILEGE(r);
48 
49         return log_error_errno(r,
50                                r == hint_vars ? "Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
51                                r == hint_addr ? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
52                                                 "Failed to connect to bus: %m");
53 }
54 
bus_async_unregister_and_exit(sd_event * e,sd_bus * bus,const char * name)55 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
56         const char *match;
57         const char *unique;
58         int r;
59 
60         assert(e);
61         assert(bus);
62         assert(name);
63 
64         /* We unregister the name here and then wait for the
65          * NameOwnerChanged signal for this event to arrive before we
66          * quit. We do this in order to make sure that any queued
67          * requests are still processed before we really exit. */
68 
69         r = sd_bus_get_unique_name(bus, &unique);
70         if (r < 0)
71                 return r;
72 
73         match = strjoina(
74                         "sender='org.freedesktop.DBus',"
75                         "type='signal',"
76                         "interface='org.freedesktop.DBus',"
77                         "member='NameOwnerChanged',"
78                         "path='/org/freedesktop/DBus',"
79                         "arg0='", name, "',",
80                         "arg1='", unique, "',",
81                         "arg2=''");
82 
83         r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
84         if (r < 0)
85                 return r;
86 
87         r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
88         if (r < 0)
89                 return r;
90 
91         return 0;
92 }
93 
bus_event_loop_with_idle(sd_event * e,sd_bus * bus,const char * name,usec_t timeout,check_idle_t check_idle,void * userdata)94 int bus_event_loop_with_idle(
95                 sd_event *e,
96                 sd_bus *bus,
97                 const char *name,
98                 usec_t timeout,
99                 check_idle_t check_idle,
100                 void *userdata) {
101         bool exiting = false;
102         int r, code;
103 
104         assert(e);
105         assert(bus);
106         assert(name);
107 
108         for (;;) {
109                 bool idle;
110 
111                 r = sd_event_get_state(e);
112                 if (r < 0)
113                         return r;
114                 if (r == SD_EVENT_FINISHED)
115                         break;
116 
117                 if (check_idle)
118                         idle = check_idle(userdata);
119                 else
120                         idle = true;
121 
122                 r = sd_event_run(e, exiting || !idle ? UINT64_MAX : timeout);
123                 if (r < 0)
124                         return r;
125 
126                 if (r == 0 && !exiting && idle) {
127                         /* Inform the service manager that we are going down, so that it will queue all
128                          * further start requests, instead of assuming we are already running. */
129                         sd_notify(false, "STOPPING=1");
130 
131                         r = bus_async_unregister_and_exit(e, bus, name);
132                         if (r < 0)
133                                 return r;
134 
135                         exiting = true;
136                         continue;
137                 }
138         }
139 
140         r = sd_event_get_exit_code(e, &code);
141         if (r < 0)
142                 return r;
143 
144         return code;
145 }
146 
bus_name_has_owner(sd_bus * c,const char * name,sd_bus_error * error)147 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
148         _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
149         int r, has_owner = 0;
150 
151         assert(c);
152         assert(name);
153 
154         r = sd_bus_call_method(c,
155                                "org.freedesktop.DBus",
156                                "/org/freedesktop/dbus",
157                                "org.freedesktop.DBus",
158                                "NameHasOwner",
159                                error,
160                                &rep,
161                                "s",
162                                name);
163         if (r < 0)
164                 return r;
165 
166         r = sd_bus_message_read_basic(rep, 'b', &has_owner);
167         if (r < 0)
168                 return sd_bus_error_set_errno(error, r);
169 
170         return has_owner;
171 }
172 
bus_error_is_unknown_service(const sd_bus_error * error)173 bool bus_error_is_unknown_service(const sd_bus_error *error) {
174         return sd_bus_error_has_names(error,
175                                       SD_BUS_ERROR_SERVICE_UNKNOWN,
176                                       SD_BUS_ERROR_NAME_HAS_NO_OWNER,
177                                       BUS_ERROR_NO_SUCH_UNIT);
178 }
179 
bus_check_peercred(sd_bus * c)180 int bus_check_peercred(sd_bus *c) {
181         struct ucred ucred;
182         int fd, r;
183 
184         assert(c);
185 
186         fd = sd_bus_get_fd(c);
187         if (fd < 0)
188                 return fd;
189 
190         r = getpeercred(fd, &ucred);
191         if (r < 0)
192                 return r;
193 
194         if (ucred.uid != 0 && ucred.uid != geteuid())
195                 return -EPERM;
196 
197         return 1;
198 }
199 
bus_connect_system_systemd(sd_bus ** _bus)200 int bus_connect_system_systemd(sd_bus **_bus) {
201         _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
202         int r;
203 
204         assert(_bus);
205 
206         if (geteuid() != 0)
207                 return sd_bus_default_system(_bus);
208 
209         /* If we are root then let's talk directly to the system
210          * instance, instead of going via the bus */
211 
212         r = sd_bus_new(&bus);
213         if (r < 0)
214                 return r;
215 
216         r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
217         if (r < 0)
218                 return r;
219 
220         r = sd_bus_start(bus);
221         if (r < 0)
222                 return sd_bus_default_system(_bus);
223 
224         r = bus_check_peercred(bus);
225         if (r < 0)
226                 return r;
227 
228         *_bus = TAKE_PTR(bus);
229 
230         return 0;
231 }
232 
bus_connect_user_systemd(sd_bus ** _bus)233 int bus_connect_user_systemd(sd_bus **_bus) {
234         _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
235         _cleanup_free_ char *ee = NULL;
236         const char *e;
237         int r;
238 
239         assert(_bus);
240 
241         e = secure_getenv("XDG_RUNTIME_DIR");
242         if (!e)
243                 return sd_bus_default_user(_bus);
244 
245         ee = bus_address_escape(e);
246         if (!ee)
247                 return -ENOMEM;
248 
249         r = sd_bus_new(&bus);
250         if (r < 0)
251                 return r;
252 
253         bus->address = strjoin("unix:path=", ee, "/systemd/private");
254         if (!bus->address)
255                 return -ENOMEM;
256 
257         r = sd_bus_start(bus);
258         if (r < 0)
259                 return sd_bus_default_user(_bus);
260 
261         r = bus_check_peercred(bus);
262         if (r < 0)
263                 return r;
264 
265         *_bus = TAKE_PTR(bus);
266 
267         return 0;
268 }
269 
bus_connect_transport(BusTransport transport,const char * host,bool user,sd_bus ** ret)270 int bus_connect_transport(
271                 BusTransport transport,
272                 const char *host,
273                 bool user,
274                 sd_bus **ret) {
275 
276         _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
277         int r;
278 
279         assert(transport >= 0);
280         assert(transport < _BUS_TRANSPORT_MAX);
281         assert(ret);
282 
283         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
284         assert_return(transport != BUS_TRANSPORT_REMOTE || !user, -EOPNOTSUPP);
285 
286         switch (transport) {
287 
288         case BUS_TRANSPORT_LOCAL:
289                 if (user)
290                         r = sd_bus_default_user(&bus);
291                 else {
292                         if (sd_booted() <= 0)
293                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
294                                 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
295                                                        "System has not been booted with systemd as init system (PID 1). Can't operate.");
296                         r = sd_bus_default_system(&bus);
297                 }
298                 break;
299 
300         case BUS_TRANSPORT_REMOTE:
301                 r = sd_bus_open_system_remote(&bus, host);
302                 break;
303 
304         case BUS_TRANSPORT_MACHINE:
305                 if (user)
306                         r = sd_bus_open_user_machine(&bus, host);
307                 else
308                         r = sd_bus_open_system_machine(&bus, host);
309                 break;
310 
311         default:
312                 assert_not_reached();
313         }
314         if (r < 0)
315                 return r;
316 
317         r = sd_bus_set_exit_on_disconnect(bus, true);
318         if (r < 0)
319                 return r;
320 
321         *ret = TAKE_PTR(bus);
322         return 0;
323 }
324 
bus_connect_transport_systemd(BusTransport transport,const char * host,bool user,sd_bus ** bus)325 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
326         int r;
327 
328         assert(transport >= 0);
329         assert(transport < _BUS_TRANSPORT_MAX);
330         assert(bus);
331 
332         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
333         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
334 
335         switch (transport) {
336 
337         case BUS_TRANSPORT_LOCAL:
338                 if (user)
339                         r = bus_connect_user_systemd(bus);
340                 else {
341                         if (sd_booted() <= 0)
342                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
343                                 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
344                                                        "System has not been booted with systemd as init system (PID 1). Can't operate.");
345                         r = bus_connect_system_systemd(bus);
346                 }
347                 break;
348 
349         case BUS_TRANSPORT_REMOTE:
350                 r = sd_bus_open_system_remote(bus, host);
351                 break;
352 
353         case BUS_TRANSPORT_MACHINE:
354                 r = sd_bus_open_system_machine(bus, host);
355                 break;
356 
357         default:
358                 assert_not_reached();
359         }
360 
361         return r;
362 }
363 
364 /**
365  * bus_path_encode_unique() - encode unique object path
366  * @b: bus connection or NULL
367  * @prefix: object path prefix
368  * @sender_id: unique-name of client, or NULL
369  * @external_id: external ID to be chosen by client, or NULL
370  * @ret_path: storage for encoded object path pointer
371  *
372  * Whenever we provide a bus API that allows clients to create and manage
373  * server-side objects, we need to provide a unique name for these objects. If
374  * we let the server choose the name, we suffer from a race condition: If a
375  * client creates an object asynchronously, it cannot destroy that object until
376  * it received the method reply. It cannot know the name of the new object,
377  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
378  *
379  * Therefore, many APIs allow the client to choose the unique name for newly
380  * created objects. There're two problems to solve, though:
381  *    1) Object names are usually defined via dbus object paths, which are
382  *       usually globally namespaced. Therefore, multiple clients must be able
383  *       to choose unique object names without interference.
384  *    2) If multiple libraries share the same bus connection, they must be
385  *       able to choose unique object names without interference.
386  * The first problem is solved easily by prefixing a name with the
387  * unique-bus-name of a connection. The server side must enforce this and
388  * reject any other name. The second problem is solved by providing unique
389  * suffixes from within sd-bus.
390  *
391  * This helper allows clients to create unique object-paths. It uses the
392  * template '/prefix/sender_id/external_id' and returns the new path in
393  * @ret_path (must be freed by the caller).
394  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
395  * NULL, this function allocates a unique suffix via @b (by requesting a new
396  * cookie). If both @sender_id and @external_id are given, @b can be passed as
397  * NULL.
398  *
399  * Returns: 0 on success, negative error code on failure.
400  */
bus_path_encode_unique(sd_bus * b,const char * prefix,const char * sender_id,const char * external_id,char ** ret_path)401 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
402         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
403         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
404         int r;
405 
406         assert_return(b || (sender_id && external_id), -EINVAL);
407         assert_return(sd_bus_object_path_is_valid(prefix), -EINVAL);
408         assert_return(ret_path, -EINVAL);
409 
410         if (!sender_id) {
411                 r = sd_bus_get_unique_name(b, &sender_id);
412                 if (r < 0)
413                         return r;
414         }
415 
416         if (!external_id) {
417                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
418                 external_id = external_buf;
419         }
420 
421         sender_label = bus_label_escape(sender_id);
422         if (!sender_label)
423                 return -ENOMEM;
424 
425         external_label = bus_label_escape(external_id);
426         if (!external_label)
427                 return -ENOMEM;
428 
429         p = path_join(prefix, sender_label, external_label);
430         if (!p)
431                 return -ENOMEM;
432 
433         *ret_path = p;
434         return 0;
435 }
436 
437 /**
438  * bus_path_decode_unique() - decode unique object path
439  * @path: object path to decode
440  * @prefix: object path prefix
441  * @ret_sender: output parameter for sender-id label
442  * @ret_external: output parameter for external-id label
443  *
444  * This does the reverse of bus_path_encode_unique() (see its description for
445  * details). Both trailing labels, sender-id and external-id, are unescaped and
446  * returned in the given output parameters (the caller must free them).
447  *
448  * Note that this function returns 0 if the path does not match the template
449  * (see bus_path_encode_unique()), 1 if it matched.
450  *
451  * Returns: Negative error code on failure, 0 if the given object path does not
452  *          match the template (return parameters are set to NULL), 1 if it was
453  *          parsed successfully (return parameters contain allocated labels).
454  */
bus_path_decode_unique(const char * path,const char * prefix,char ** ret_sender,char ** ret_external)455 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
456         const char *p, *q;
457         char *sender, *external;
458 
459         assert(sd_bus_object_path_is_valid(path));
460         assert(sd_bus_object_path_is_valid(prefix));
461         assert(ret_sender);
462         assert(ret_external);
463 
464         p = object_path_startswith(path, prefix);
465         if (!p) {
466                 *ret_sender = NULL;
467                 *ret_external = NULL;
468                 return 0;
469         }
470 
471         q = strchr(p, '/');
472         if (!q) {
473                 *ret_sender = NULL;
474                 *ret_external = NULL;
475                 return 0;
476         }
477 
478         sender = bus_label_unescape_n(p, q - p);
479         external = bus_label_unescape(q + 1);
480         if (!sender || !external) {
481                 free(sender);
482                 free(external);
483                 return -ENOMEM;
484         }
485 
486         *ret_sender = sender;
487         *ret_external = external;
488         return 1;
489 }
490 
bus_track_add_name_many(sd_bus_track * t,char ** l)491 int bus_track_add_name_many(sd_bus_track *t, char **l) {
492         int r = 0;
493 
494         assert(t);
495 
496         /* Continues adding after failure, and returns the first failure. */
497 
498         STRV_FOREACH(i, l) {
499                 int k;
500 
501                 k = sd_bus_track_add_name(t, *i);
502                 if (k < 0 && r >= 0)
503                         r = k;
504         }
505 
506         return r;
507 }
508 
bus_open_system_watch_bind_with_description(sd_bus ** ret,const char * description)509 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
510         _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
511         const char *e;
512         int r;
513 
514         assert(ret);
515 
516         /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
517          * turned on. */
518 
519         r = sd_bus_new(&bus);
520         if (r < 0)
521                 return r;
522 
523         if (description) {
524                 r = sd_bus_set_description(bus, description);
525                 if (r < 0)
526                         return r;
527         }
528 
529         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
530         if (!e)
531                 e = DEFAULT_SYSTEM_BUS_ADDRESS;
532 
533         r = sd_bus_set_address(bus, e);
534         if (r < 0)
535                 return r;
536 
537         r = sd_bus_set_bus_client(bus, true);
538         if (r < 0)
539                 return r;
540 
541         r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
542         if (r < 0)
543                 return r;
544 
545         r = sd_bus_set_watch_bind(bus, true);
546         if (r < 0)
547                 return r;
548 
549         r = sd_bus_set_connected_signal(bus, true);
550         if (r < 0)
551                 return r;
552 
553         r = sd_bus_start(bus);
554         if (r < 0)
555                 return r;
556 
557         *ret = TAKE_PTR(bus);
558 
559         return 0;
560 }
561 
bus_reply_pair_array(sd_bus_message * m,char ** l)562 int bus_reply_pair_array(sd_bus_message *m, char **l) {
563         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
564         int r;
565 
566         assert(m);
567 
568         /* Reply to the specified message with a message containing a dictionary put together from the
569          * specified strv */
570 
571         r = sd_bus_message_new_method_return(m, &reply);
572         if (r < 0)
573                 return r;
574 
575         r = sd_bus_message_open_container(reply, 'a', "{ss}");
576         if (r < 0)
577                 return r;
578 
579         STRV_FOREACH_PAIR(k, v, l) {
580                 r = sd_bus_message_append(reply, "{ss}", *k, *v);
581                 if (r < 0)
582                         return r;
583         }
584 
585         r = sd_bus_message_close_container(reply);
586         if (r < 0)
587                 return r;
588 
589         return sd_bus_send(NULL, reply, NULL);
590 }
591 
bus_message_unref_wrapper(void * m)592 static void bus_message_unref_wrapper(void *m) {
593         sd_bus_message_unref(m);
594 }
595 
596 const struct hash_ops bus_message_hash_ops = {
597         .hash = trivial_hash_func,
598         .compare = trivial_compare_func,
599         .free_value = bus_message_unref_wrapper,
600 };
601