bus: Assign a serial number for messages from the driver
[platform/upstream/dbus.git] / bus / activation.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* activation.c  Activation of services
3  *
4  * Copyright (C) 2003  CodeFactory AB
5  * Copyright (C) 2003  Red Hat, Inc.
6  * Copyright (C) 2004  Imendio HB
7  *
8  * Licensed under the Academic Free License version 2.1
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  */
25
26 #include <config.h>
27 #include "activation.h"
28 #include "activation-exit-codes.h"
29 #include "config-parser.h"
30 #include "desktop-file.h"
31 #include "dispatch.h"
32 #include "services.h"
33 #include "test.h"
34 #include "utils.h"
35 #include <dbus/dbus-connection-internal.h>
36 #include <dbus/dbus-internals.h>
37 #include <dbus/dbus-hash.h>
38 #include <dbus/dbus-list.h>
39 #include <dbus/dbus-shell.h>
40 #include <dbus/dbus-spawn.h>
41 #include <dbus/dbus-timeout.h>
42 #include <dbus/dbus-sysdeps.h>
43 #ifdef HAVE_ERRNO_H
44 #include <errno.h>
45 #endif
46
47 struct BusActivation
48 {
49   int refcount;
50   DBusHashTable *entries;
51   DBusHashTable *pending_activations;
52   char *server_address;
53   BusContext *context;
54   int n_pending_activations; /**< This is in fact the number of BusPendingActivationEntry,
55                               * i.e. number of pending activation requests, not pending
56                               * activations per se
57                               */
58   DBusList *directories;
59   DBusHashTable *environment;
60 };
61
62 typedef struct
63 {
64   int refcount;
65   char *dir_c;
66   BusServiceDirFlags flags;
67   DBusHashTable *entries;
68 } BusServiceDirectory;
69
70 struct BusActivationEntry
71 {
72   int refcount;
73   char *name;
74   char *exec;
75   char *user;
76   char *systemd_service;
77   char *assumed_apparmor_label;
78   unsigned long mtime;
79   BusServiceDirectory *s_dir;
80   char *filename;
81 };
82
83 typedef struct BusPendingActivationEntry BusPendingActivationEntry;
84
85 struct BusPendingActivationEntry
86 {
87   /* Normally a method call, but if connection is NULL, this is a signal
88    * instead.
89    */
90   DBusMessage *activation_message;
91   /* NULL if this activation entry is for the dbus-daemon itself,
92    * waiting for systemd to start. In this case, auto_activation is always
93    * TRUE.
94    */
95   DBusConnection *connection;
96
97   dbus_bool_t auto_activation;
98
99   dbus_bool_t is_put_back;
100 };
101
102 typedef struct
103 {
104   int refcount;
105   BusActivation *activation;
106   char *service_name;
107   char *exec;
108   char *systemd_service;
109   DBusList *entries;
110   int n_entries;
111   DBusBabysitter *babysitter;
112   DBusTimeout *timeout;
113   unsigned int timeout_added : 1;
114 } BusPendingActivation;
115
116 #if 0
117 static BusServiceDirectory *
118 bus_service_directory_ref (BusServiceDirectory *dir)
119 {
120   _dbus_assert (dir->refcount);
121
122   dir->refcount++;
123
124   return dir;
125 }
126 #endif
127
128 static void
129 bus_service_directory_unref (BusServiceDirectory *dir)
130 {
131   if (dir == NULL)
132     return;
133
134   _dbus_assert (dir->refcount > 0);
135   dir->refcount--;
136
137   if (dir->refcount > 0)
138     return;
139
140   if (dir->entries)
141     _dbus_hash_table_unref (dir->entries);
142
143   dbus_free (dir->dir_c);
144   dbus_free (dir);
145 }
146
147 static void
148 bus_pending_activation_entry_free (BusPendingActivationEntry *entry)
149 {
150   if (entry->activation_message)
151     dbus_message_unref (entry->activation_message);
152
153   if (entry->connection)
154     dbus_connection_unref (entry->connection);
155
156   dbus_free (entry);
157 }
158
159 static BusPendingActivation *
160 bus_pending_activation_ref (BusPendingActivation *pending_activation)
161 {
162   _dbus_assert (pending_activation->refcount > 0);
163   pending_activation->refcount += 1;
164
165   return pending_activation;
166 }
167
168 static void
169 bus_pending_activation_unref (BusPendingActivation *pending_activation)
170 {
171   DBusList *link;
172
173   if (pending_activation == NULL) /* hash table requires this */
174     return;
175
176   _dbus_assert (pending_activation->refcount > 0);
177   pending_activation->refcount -= 1;
178
179   if (pending_activation->refcount > 0)
180     return;
181
182   if (pending_activation->timeout_added)
183     {
184       _dbus_loop_remove_timeout (bus_context_get_loop (pending_activation->activation->context),
185                                  pending_activation->timeout);
186       pending_activation->timeout_added = FALSE;
187     }
188
189   if (pending_activation->timeout)
190     _dbus_timeout_unref (pending_activation->timeout);
191
192   if (pending_activation->babysitter)
193     {
194       if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
195                                                  NULL, NULL, NULL,
196                                                  pending_activation->babysitter,
197                                                  NULL))
198         _dbus_assert_not_reached ("setting watch functions to NULL failed");
199
200       _dbus_babysitter_unref (pending_activation->babysitter);
201     }
202
203   dbus_free (pending_activation->service_name);
204   dbus_free (pending_activation->exec);
205   dbus_free (pending_activation->systemd_service);
206
207   link = _dbus_list_get_first_link (&pending_activation->entries);
208
209   while (link != NULL)
210     {
211       BusPendingActivationEntry *entry = link->data;
212
213       bus_pending_activation_entry_free (entry);
214
215       link = _dbus_list_get_next_link (&pending_activation->entries, link);
216     }
217   _dbus_list_clear (&pending_activation->entries);
218
219   pending_activation->activation->n_pending_activations -=
220     pending_activation->n_entries;
221
222   _dbus_assert (pending_activation->activation->n_pending_activations >= 0);
223
224   dbus_free (pending_activation);
225 }
226
227 static BusActivationEntry *
228 bus_activation_entry_ref (BusActivationEntry *entry)
229 {
230   _dbus_assert (entry->refcount > 0);
231   entry->refcount++;
232
233   return entry;
234 }
235
236 static void
237 bus_activation_entry_unref (BusActivationEntry *entry)
238 {
239   if (entry == NULL) /* hash table requires this */
240     return;
241
242   _dbus_assert (entry->refcount > 0);
243   entry->refcount--;
244
245   if (entry->refcount > 0)
246     return;
247
248   dbus_free (entry->name);
249   dbus_free (entry->exec);
250   dbus_free (entry->user);
251   dbus_free (entry->filename);
252   dbus_free (entry->systemd_service);
253   dbus_free (entry->assumed_apparmor_label);
254
255   dbus_free (entry);
256 }
257
258 static dbus_bool_t
259 update_desktop_file_entry (BusActivation       *activation,
260                            BusServiceDirectory *s_dir,
261                            DBusString          *filename,
262                            BusDesktopFile      *desktop_file,
263                            DBusError           *error)
264 {
265   char *name, *exec, *user, *exec_tmp, *systemd_service;
266   char *assumed_apparmor_label;
267   BusActivationEntry *entry;
268   DBusStat stat_buf;
269   DBusString file_path;
270   DBusError tmp_error;
271   dbus_bool_t retval;
272   DBusString str;
273
274   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
275
276   retval = FALSE;
277   name = NULL;
278   exec = NULL;
279   user = NULL;
280   exec_tmp = NULL;
281   entry = NULL;
282   systemd_service = NULL;
283   assumed_apparmor_label = NULL;
284
285   dbus_error_init (&tmp_error);
286
287   if (!_dbus_string_init (&file_path))
288     {
289       BUS_SET_OOM (error);
290       return FALSE;
291     }
292
293   if (!_dbus_string_append (&file_path, s_dir->dir_c) ||
294       !_dbus_concat_dir_and_file (&file_path, filename))
295     {
296       BUS_SET_OOM (error);
297       goto out;
298     }
299
300   if (!_dbus_stat (&file_path, &stat_buf, NULL))
301     {
302       dbus_set_error (error, DBUS_ERROR_FAILED,
303                       "Can't stat the service file\n");
304       goto out;
305     }
306
307   if (!bus_desktop_file_get_string (desktop_file,
308                                     DBUS_SERVICE_SECTION,
309                                     DBUS_SERVICE_NAME,
310                                     &name,
311                                     error))
312     goto out;
313
314   if (!bus_desktop_file_get_string (desktop_file,
315                                     DBUS_SERVICE_SECTION,
316                                     DBUS_SERVICE_EXEC,
317                                     &exec_tmp,
318                                     error))
319     goto out;
320
321   if (!_dbus_string_init (&str))
322     goto out;
323
324   if (!_dbus_string_append (&str, exec_tmp) ||
325       !_dbus_replace_install_prefix (&str) ||
326       !_dbus_string_steal_data (&str, &exec))
327     {
328       _dbus_string_free (&str);
329       goto out;
330     }
331
332   _dbus_string_free (&str);
333
334   /* user is not _required_ unless we are using system activation */
335   if (!bus_desktop_file_get_string (desktop_file,
336                                     DBUS_SERVICE_SECTION,
337                                     DBUS_SERVICE_USER,
338                                     &user, &tmp_error))
339     {
340       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
341       /* if we got OOM, then exit */
342       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
343         {
344           dbus_move_error (&tmp_error, error);
345           goto out;
346         }
347       else
348         {
349           /* if we have error because we didn't find anything then continue */
350           dbus_error_free (&tmp_error);
351           dbus_free (user);
352           user = NULL;
353         }
354     }
355   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
356
357   /* systemd service is never required */
358   if (!bus_desktop_file_get_string (desktop_file,
359                                     DBUS_SERVICE_SECTION,
360                                     DBUS_SERVICE_SYSTEMD_SERVICE,
361                                     &systemd_service, &tmp_error))
362     {
363       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
364       /* if we got OOM, then exit */
365       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
366         {
367           dbus_move_error (&tmp_error, error);
368           goto out;
369         }
370       else
371         {
372           /* if we have error because we didn't find anything then continue */
373           dbus_error_free (&tmp_error);
374           dbus_free (systemd_service);
375           systemd_service = NULL;
376         }
377     }
378
379   /* assumed AppArmor label is never required */
380   if (!bus_desktop_file_get_string (desktop_file,
381                                     DBUS_SERVICE_SECTION,
382                                     DBUS_SERVICE_ASSUMED_APPARMOR_LABEL,
383                                     &assumed_apparmor_label, &tmp_error))
384     {
385       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
386       /* if we got OOM, then exit */
387       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
388         {
389           dbus_move_error (&tmp_error, error);
390           goto out;
391         }
392       else
393         {
394           /* if we have error because we didn't find anything then continue */
395           dbus_error_free (&tmp_error);
396           dbus_free (assumed_apparmor_label);
397           assumed_apparmor_label = NULL;
398         }
399     }
400
401   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
402
403   entry = _dbus_hash_table_lookup_string (s_dir->entries,
404                                           _dbus_string_get_const_data (filename));
405
406   if (entry == NULL) /* New file */
407     {
408       DBusString expected_name;
409
410       if (!_dbus_string_init (&expected_name))
411         {
412           BUS_SET_OOM (error);
413           goto out;
414         }
415
416       if (!_dbus_string_append (&expected_name, name) ||
417           !_dbus_string_append (&expected_name, ".service"))
418         {
419           _dbus_string_free (&expected_name);
420           BUS_SET_OOM (error);
421           goto out;
422         }
423
424       if (_dbus_string_equal (&expected_name, filename))
425         {
426           _dbus_verbose ("Name of \"%s\" is as expected\n",
427                          _dbus_string_get_const_data (&file_path));
428         }
429       else if (s_dir->flags & BUS_SERVICE_DIR_FLAGS_STRICT_NAMING)
430         {
431           bus_context_log_and_set_error (activation->context,
432                                          DBUS_SYSTEM_LOG_WARNING, error,
433                                          DBUS_ERROR_FAILED,
434                                          "Service file \"%s\" should have "
435                                          "been named \"%s\": not loading it",
436                                          _dbus_string_get_const_data (&file_path),
437                                          _dbus_string_get_const_data (&expected_name));
438           _dbus_string_free (&expected_name);
439           goto out;
440         }
441       else if (bus_context_get_servicehelper (activation->context) != NULL)
442         {
443           bus_context_log (activation->context, DBUS_SYSTEM_LOG_WARNING,
444                            "Service file \"%s\" should have been named \"%s\" "
445                            "and will not work with system bus activation",
446                            _dbus_string_get_const_data (&file_path),
447                            _dbus_string_get_const_data (&expected_name));
448           /* We don't actually error out here, because *technically* it could
449            * still work on systemd systems, where we tell systemd to start the
450            * SystemdService instead of launching dbus-daemon-launch-helper
451            * ourselves. But maybe we should:
452            * https://bugs.freedesktop.org/show_bug.cgi?id=99874 */
453         }
454       else
455         {
456           /* We could maybe log mismatched names for session services in
457            * a user-visible way too, but not until
458            * https://lintian.debian.org/tags/dbus-session-service-wrong-name.html
459            * is a bit shorter.
460            * https://bugs.freedesktop.org/show_bug.cgi?id=99873 */
461           _dbus_verbose ("Name of \"%s\" should canonically be \"%s\"\n",
462                          _dbus_string_get_const_data (&file_path),
463                          _dbus_string_get_const_data (&expected_name));
464         }
465
466       _dbus_string_free (&expected_name);
467
468       /* FIXME we need a better-defined algorithm for which service file to
469        * pick than "whichever one is first in the directory listing"
470        * See also https://bugs.freedesktop.org/show_bug.cgi?id=99874
471        */
472       if (_dbus_hash_table_lookup_string (activation->entries, name))
473         {
474           dbus_set_error (error, DBUS_ERROR_FAILED,
475                           "Service %s already exists in activation entry list\n", name);
476           goto out;
477         }
478
479       entry = dbus_new0 (BusActivationEntry, 1);
480       if (entry == NULL)
481         {
482           BUS_SET_OOM (error);
483           goto out;
484         }
485
486       entry->name = name;
487       entry->exec = exec;
488       entry->user = user;
489       entry->systemd_service = systemd_service;
490       entry->assumed_apparmor_label = assumed_apparmor_label;
491       entry->refcount = 1;
492
493       /* ownership has been transferred to entry, do not free separately */
494       name = NULL;
495       exec = NULL;
496       user = NULL;
497       systemd_service = NULL;
498       assumed_apparmor_label = NULL;
499
500       entry->s_dir = s_dir;
501       entry->filename = _dbus_strdup (_dbus_string_get_const_data (filename));
502       if (!entry->filename)
503         {
504           BUS_SET_OOM (error);
505           goto out;
506         }
507
508       if (!_dbus_hash_table_insert_string (activation->entries, entry->name, bus_activation_entry_ref (entry)))
509         {
510           BUS_SET_OOM (error);
511           goto out;
512         }
513
514       if (!_dbus_hash_table_insert_string (s_dir->entries, entry->filename, bus_activation_entry_ref (entry)))
515         {
516           /* Revert the insertion in the entries table */
517           _dbus_hash_table_remove_string (activation->entries, entry->name);
518           BUS_SET_OOM (error);
519           goto out;
520         }
521
522       _dbus_verbose ("Added \"%s\" to list of services\n", entry->name);
523     }
524   else /* Just update the entry */
525     {
526       bus_activation_entry_ref (entry);
527       _dbus_hash_table_remove_string (activation->entries, entry->name);
528
529       if (_dbus_hash_table_lookup_string (activation->entries, name))
530         {
531           _dbus_verbose ("The new service name \"%s\" of service file \"%s\" is already in cache, ignoring\n",
532                          name, _dbus_string_get_const_data (&file_path));
533           dbus_set_error (error, DBUS_ERROR_FAILED,
534                           "The new service name \"%s\" of service file \"%s\" is already in cache, ignoring\n",
535                           name, _dbus_string_get_const_data (&file_path));
536           goto out;
537         }
538
539       /* ownership has been transferred to entry, do not free separately */
540       dbus_free (entry->name);
541       entry->name = name;
542       name = NULL;
543
544       dbus_free (entry->exec);
545       entry->exec = exec;
546       exec = NULL;
547
548       dbus_free (entry->user);
549       entry->user = user;
550       user = NULL;
551
552       dbus_free (entry->systemd_service);
553       entry->systemd_service = systemd_service;
554       systemd_service = NULL;
555
556       dbus_free (entry->assumed_apparmor_label);
557       entry->assumed_apparmor_label = assumed_apparmor_label;
558       assumed_apparmor_label = NULL;
559
560       if (!_dbus_hash_table_insert_string (activation->entries,
561                                            entry->name, bus_activation_entry_ref(entry)))
562         {
563           BUS_SET_OOM (error);
564           /* Also remove path to entries hash since we want this in sync with
565            * the entries hash table */
566           _dbus_hash_table_remove_string (entry->s_dir->entries,
567                                           entry->filename);
568           goto out;
569         }
570     }
571
572   entry->mtime = stat_buf.mtime;
573   retval = TRUE;
574
575 out:
576   /* if these have been transferred into entry, the variables will be NULL */
577   dbus_free (exec_tmp);
578   dbus_free (name);
579   dbus_free (exec);
580   dbus_free (user);
581   dbus_free (systemd_service);
582   dbus_free (assumed_apparmor_label);
583   _dbus_string_free (&file_path);
584
585   if (entry)
586     bus_activation_entry_unref (entry);
587
588   return retval;
589 }
590
591 static dbus_bool_t
592 check_service_file (BusActivation       *activation,
593                     BusActivationEntry  *entry,
594                     BusActivationEntry **updated_entry,
595                     DBusError           *error)
596 {
597   DBusStat stat_buf;
598   dbus_bool_t retval;
599   BusActivationEntry *tmp_entry;
600   DBusString file_path;
601   DBusString filename;
602
603   retval = TRUE;
604   tmp_entry = entry;
605
606   _dbus_string_init_const (&filename, entry->filename);
607
608   if (!_dbus_string_init (&file_path))
609     {
610       BUS_SET_OOM (error);
611       return FALSE;
612     }
613
614   if (!_dbus_string_append (&file_path, entry->s_dir->dir_c) ||
615       !_dbus_concat_dir_and_file (&file_path, &filename))
616     {
617       BUS_SET_OOM (error);
618       retval = FALSE;
619       goto out;
620     }
621
622   if (!_dbus_stat (&file_path, &stat_buf, NULL))
623     {
624       _dbus_verbose ("****** Can't stat file \"%s\", removing from cache\n",
625                      _dbus_string_get_const_data (&file_path));
626
627       _dbus_hash_table_remove_string (activation->entries, entry->name);
628       _dbus_hash_table_remove_string (entry->s_dir->entries, entry->filename);
629
630       tmp_entry = NULL;
631       retval = TRUE;
632       goto out;
633     }
634   else
635     {
636       if (stat_buf.mtime > entry->mtime)
637         {
638           BusDesktopFile *desktop_file;
639           DBusError tmp_error;
640
641           dbus_error_init (&tmp_error);
642
643           desktop_file = bus_desktop_file_load (&file_path, &tmp_error);
644           if (desktop_file == NULL)
645             {
646               _dbus_verbose ("Could not load %s: %s\n",
647                              _dbus_string_get_const_data (&file_path),
648                              tmp_error.message);
649               if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
650                 {
651                   dbus_move_error (&tmp_error, error);
652                   retval = FALSE;
653                   goto out;
654                 }
655               dbus_error_free (&tmp_error);
656               retval = TRUE;
657               goto out;
658             }
659
660           /* @todo We can return OOM or a DBUS_ERROR_FAILED error
661            *       Handle these both better
662            */
663           if (!update_desktop_file_entry (activation, entry->s_dir, &filename, desktop_file, &tmp_error))
664             {
665               bus_desktop_file_free (desktop_file);
666               if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
667                 {
668                   dbus_move_error (&tmp_error, error);
669                   retval = FALSE;
670                   goto out;
671                 }
672               dbus_error_free (&tmp_error);
673               retval = TRUE;
674               goto out;
675             }
676
677           bus_desktop_file_free (desktop_file);
678           retval = TRUE;
679         }
680     }
681
682 out:
683   _dbus_string_free (&file_path);
684
685   if (updated_entry != NULL)
686     *updated_entry = tmp_entry;
687   return retval;
688 }
689
690
691 /* warning: this doesn't fully "undo" itself on failure, i.e. doesn't strip
692  * hash entries it already added.
693  */
694 static dbus_bool_t
695 update_directory (BusActivation       *activation,
696                   BusServiceDirectory *s_dir,
697                   DBusError           *error)
698 {
699   DBusDirIter *iter;
700   DBusString dir, filename;
701   BusDesktopFile *desktop_file;
702   DBusError tmp_error;
703   dbus_bool_t retval;
704   BusActivationEntry *entry;
705   DBusString full_path;
706
707   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
708
709   iter = NULL;
710   desktop_file = NULL;
711
712   _dbus_string_init_const (&dir, s_dir->dir_c);
713
714   if (!_dbus_string_init (&filename))
715     {
716       BUS_SET_OOM (error);
717       return FALSE;
718     }
719
720   if (!_dbus_string_init (&full_path))
721     {
722       BUS_SET_OOM (error);
723       _dbus_string_free (&filename);
724       return FALSE;
725     }
726
727   retval = FALSE;
728
729   /* from this point it's safe to "goto out" */
730
731   iter = _dbus_directory_open (&dir, error);
732   if (iter == NULL)
733     {
734       _dbus_verbose ("Failed to open directory %s: %s\n",
735                      s_dir->dir_c,
736                      error ? error->message : "unknown");
737       goto out;
738     }
739
740   /* Now read the files */
741   dbus_error_init (&tmp_error);
742   while (_dbus_directory_get_next_file (iter, &filename, &tmp_error))
743     {
744       _dbus_assert (!dbus_error_is_set (&tmp_error));
745
746       _dbus_string_set_length (&full_path, 0);
747
748       if (!_dbus_string_ends_with_c_str (&filename, ".service"))
749         {
750           _dbus_verbose ("Skipping non-.service file '%s'\n",
751                          _dbus_string_get_const_data (&filename));
752           continue;
753         }
754
755       entry = _dbus_hash_table_lookup_string (s_dir->entries, _dbus_string_get_const_data (&filename));
756       if (entry) /* Already has this service file in the cache */
757         {
758           if (!check_service_file (activation, entry, NULL, error))
759             goto out;
760
761           continue;
762         }
763
764       if (!_dbus_string_append (&full_path, s_dir->dir_c) ||
765           !_dbus_concat_dir_and_file (&full_path, &filename))
766         {
767           BUS_SET_OOM (error);
768           goto out;
769         }
770
771       /* New file */
772       desktop_file = bus_desktop_file_load (&full_path, &tmp_error);
773       if (desktop_file == NULL)
774         {
775           _dbus_verbose ("Could not load %s: %s\n",
776                          _dbus_string_get_const_data (&full_path),
777                          tmp_error.message);
778
779           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
780             {
781               dbus_move_error (&tmp_error, error);
782               goto out;
783             }
784
785           dbus_error_free (&tmp_error);
786           continue;
787         }
788
789       /* @todo We can return OOM or a DBUS_ERROR_FAILED error
790        *       Handle these both better
791        */
792       if (!update_desktop_file_entry (activation, s_dir, &filename, desktop_file, &tmp_error))
793         {
794           bus_desktop_file_free (desktop_file);
795           desktop_file = NULL;
796
797           _dbus_verbose ("Could not add %s to activation entry list: %s\n",
798                          _dbus_string_get_const_data (&full_path), tmp_error.message);
799
800           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
801             {
802               dbus_move_error (&tmp_error, error);
803               goto out;
804             }
805
806           dbus_error_free (&tmp_error);
807           continue;
808         }
809       else
810         {
811           bus_desktop_file_free (desktop_file);
812           desktop_file = NULL;
813           continue;
814         }
815     }
816
817   if (dbus_error_is_set (&tmp_error))
818     {
819       dbus_move_error (&tmp_error, error);
820       goto out;
821     }
822
823   retval = TRUE;
824
825  out:
826   if (!retval)
827     _DBUS_ASSERT_ERROR_IS_SET (error);
828   else
829     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
830
831   if (iter != NULL)
832     _dbus_directory_close (iter);
833   _dbus_string_free (&filename);
834   _dbus_string_free (&full_path);
835
836   return retval;
837 }
838
839 static dbus_bool_t
840 populate_environment (BusActivation *activation)
841 {
842   char       **environment;
843   dbus_bool_t  retval = FALSE;
844
845   environment = _dbus_get_environment ();
846
847   if (environment == NULL)
848     return FALSE;
849
850   retval = _dbus_hash_table_from_array (activation->environment, environment, '=');
851   dbus_free_string_array (environment);
852
853   return retval;
854 }
855
856 dbus_bool_t
857 bus_activation_reload (BusActivation     *activation,
858                        const DBusString  *address,
859                        DBusList         **directories,
860                        DBusError         *error)
861 {
862   DBusList      *link;
863   char          *dir;
864
865   if (activation->server_address != NULL)
866     dbus_free (activation->server_address);
867   if (!_dbus_string_copy_data (address, &activation->server_address))
868     {
869       BUS_SET_OOM (error);
870       goto failed;
871     }
872
873   if (activation->entries != NULL)
874     _dbus_hash_table_unref (activation->entries);
875   activation->entries = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
876                                              (DBusFreeFunction)bus_activation_entry_unref);
877   if (activation->entries == NULL)
878     {
879       BUS_SET_OOM (error);
880       goto failed;
881     }
882
883   _dbus_list_foreach (&activation->directories,
884                       (DBusForeachFunction) bus_service_directory_unref, NULL);
885   _dbus_list_clear (&activation->directories);
886
887   link = _dbus_list_get_first_link (directories);
888   while (link != NULL)
889     {
890       BusConfigServiceDir *config = link->data;
891       BusServiceDirectory *s_dir;
892
893       _dbus_assert (config->path != NULL);
894
895       dir = _dbus_strdup (config->path);
896       if (!dir)
897         {
898           BUS_SET_OOM (error);
899           goto failed;
900         }
901
902       s_dir = dbus_new0 (BusServiceDirectory, 1);
903       if (!s_dir)
904         {
905           dbus_free (dir);
906           BUS_SET_OOM (error);
907           goto failed;
908         }
909
910       s_dir->refcount = 1;
911       s_dir->dir_c = dir;
912       s_dir->flags = config->flags;
913
914       s_dir->entries = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
915                                              (DBusFreeFunction)bus_activation_entry_unref);
916
917       if (!s_dir->entries)
918         {
919           bus_service_directory_unref (s_dir);
920           BUS_SET_OOM (error);
921           goto failed;
922         }
923
924       if (!_dbus_list_append (&activation->directories, s_dir))
925         {
926           bus_service_directory_unref (s_dir);
927           BUS_SET_OOM (error);
928           goto failed;
929         }
930
931       /* only fail on OOM, it is ok if we can't read the directory */
932       if (!update_directory (activation, s_dir, error))
933         {
934           if (dbus_error_has_name (error, DBUS_ERROR_NO_MEMORY))
935             goto failed;
936           else
937             dbus_error_free (error);
938         }
939
940       link = _dbus_list_get_next_link (directories, link);
941     }
942
943   return TRUE;
944  failed:
945   return FALSE;
946 }
947
948 BusActivation*
949 bus_activation_new (BusContext        *context,
950                     const DBusString  *address,
951                     DBusList         **directories,
952                     DBusError         *error)
953 {
954   BusActivation *activation;
955
956   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
957
958   activation = dbus_new0 (BusActivation, 1);
959   if (activation == NULL)
960     {
961       BUS_SET_OOM (error);
962       return NULL;
963     }
964
965   activation->refcount = 1;
966   activation->context = context;
967   activation->n_pending_activations = 0;
968
969   if (!bus_activation_reload (activation, address, directories, error))
970     goto failed;
971
972    /* Initialize this hash table once, we don't want to lose pending
973    * activations on reload. */
974   activation->pending_activations = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
975                                                           (DBusFreeFunction)bus_pending_activation_unref);
976
977   if (activation->pending_activations == NULL)
978     {
979       BUS_SET_OOM (error);
980       goto failed;
981     }
982
983   activation->environment = _dbus_hash_table_new (DBUS_HASH_STRING,
984                                                   (DBusFreeFunction) dbus_free,
985                                                   (DBusFreeFunction) dbus_free);
986
987   if (activation->environment == NULL)
988     {
989       BUS_SET_OOM (error);
990       goto failed;
991     }
992
993   if (!populate_environment (activation))
994     {
995       BUS_SET_OOM (error);
996       goto failed;
997     }
998
999   return activation;
1000
1001  failed:
1002   bus_activation_unref (activation);
1003   return NULL;
1004 }
1005
1006 BusActivation *
1007 bus_activation_ref (BusActivation *activation)
1008 {
1009   _dbus_assert (activation->refcount > 0);
1010
1011   activation->refcount += 1;
1012
1013   return activation;
1014 }
1015
1016 void
1017 bus_activation_unref (BusActivation *activation)
1018 {
1019   _dbus_assert (activation->refcount > 0);
1020
1021   activation->refcount -= 1;
1022
1023   if (activation->refcount > 0)
1024     return;
1025
1026   dbus_free (activation->server_address);
1027   if (activation->entries)
1028     _dbus_hash_table_unref (activation->entries);
1029   if (activation->pending_activations)
1030     _dbus_hash_table_unref (activation->pending_activations);
1031
1032   _dbus_list_foreach (&activation->directories,
1033                       (DBusForeachFunction) bus_service_directory_unref, NULL);
1034   _dbus_list_clear (&activation->directories);
1035
1036   if (activation->environment)
1037     _dbus_hash_table_unref (activation->environment);
1038
1039   dbus_free (activation);
1040 }
1041
1042 static dbus_bool_t
1043 add_bus_environment (BusActivation *activation,
1044                      DBusError     *error)
1045 {
1046   const char *type;
1047
1048   if (!bus_activation_set_environment_variable (activation,
1049                                                 "DBUS_STARTER_ADDRESS",
1050                                                 activation->server_address,
1051                                                 error))
1052     return FALSE;
1053
1054   type = bus_context_get_type (activation->context);
1055   if (type != NULL)
1056     {
1057       if (!bus_activation_set_environment_variable (activation,
1058                                                     "DBUS_STARTER_BUS_TYPE", type,
1059                                                     error))
1060         return FALSE;
1061
1062       if (strcmp (type, "session") == 0)
1063         {
1064           if (!bus_activation_set_environment_variable (activation,
1065                                                         "DBUS_SESSION_BUS_ADDRESS",
1066                                                         activation->server_address,
1067                                                         error))
1068             return FALSE;
1069         }
1070       else if (strcmp (type, "system") == 0)
1071         {
1072           if (!bus_activation_set_environment_variable (activation,
1073                                                         "DBUS_SYSTEM_BUS_ADDRESS",
1074                                                         activation->server_address,
1075                                                         error))
1076             return FALSE;
1077         }
1078     }
1079
1080   return TRUE;
1081 }
1082
1083 typedef struct
1084 {
1085   BusPendingActivation *pending_activation;
1086   DBusPreallocatedHash *hash_entry;
1087 } RestorePendingData;
1088
1089 static void
1090 restore_pending (void *data)
1091 {
1092   RestorePendingData *d = data;
1093
1094   _dbus_assert (d->pending_activation != NULL);
1095   _dbus_assert (d->hash_entry != NULL);
1096
1097   _dbus_verbose ("Restoring pending activation for service %s, has timeout = %d\n",
1098                  d->pending_activation->service_name,
1099                  d->pending_activation->timeout_added);
1100
1101   _dbus_hash_table_insert_string_preallocated (d->pending_activation->activation->pending_activations,
1102                                                d->hash_entry,
1103                                                d->pending_activation->service_name, d->pending_activation);
1104
1105   bus_pending_activation_ref (d->pending_activation);
1106
1107   d->hash_entry = NULL;
1108 }
1109
1110 static void
1111 free_restore_pending_data (void *data)
1112 {
1113   RestorePendingData *d = data;
1114
1115   if (d->hash_entry)
1116     _dbus_hash_table_free_preallocated_entry (d->pending_activation->activation->pending_activations,
1117                                               d->hash_entry);
1118
1119   bus_pending_activation_unref (d->pending_activation);
1120
1121   dbus_free (d);
1122 }
1123
1124 static dbus_bool_t
1125 add_restore_pending_to_transaction (BusTransaction       *transaction,
1126                                     BusPendingActivation *pending_activation)
1127 {
1128   RestorePendingData *d;
1129
1130   d = dbus_new (RestorePendingData, 1);
1131   if (d == NULL)
1132     return FALSE;
1133
1134   d->pending_activation = pending_activation;
1135   d->hash_entry = _dbus_hash_table_preallocate_entry (d->pending_activation->activation->pending_activations);
1136
1137   bus_pending_activation_ref (d->pending_activation);
1138
1139   if (d->hash_entry == NULL ||
1140       !bus_transaction_add_cancel_hook (transaction, restore_pending, d,
1141                                         free_restore_pending_data))
1142     {
1143       free_restore_pending_data (d);
1144       return FALSE;
1145     }
1146
1147   _dbus_verbose ("Saved pending activation to be restored if the transaction fails\n");
1148
1149   return TRUE;
1150 }
1151
1152 dbus_bool_t
1153 bus_activation_service_created (BusActivation  *activation,
1154                                 const char     *service_name,
1155                                 BusTransaction *transaction,
1156                                 DBusError      *error)
1157 {
1158   BusPendingActivation *pending_activation;
1159   DBusMessage *message;
1160   DBusList *link;
1161
1162   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1163
1164   /* Check if it's a pending activation */
1165   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1166
1167   if (!pending_activation)
1168     return TRUE;
1169
1170   bus_context_log (activation->context,
1171                    DBUS_SYSTEM_LOG_INFO, "Successfully activated service '%s'",
1172                    service_name);
1173
1174   link = _dbus_list_get_first_link (&pending_activation->entries);
1175   while (link != NULL)
1176     {
1177       BusPendingActivationEntry *entry = link->data;
1178       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1179
1180       /* entry->connection is NULL for activating systemd */
1181       if (entry->connection && dbus_connection_get_is_connected (entry->connection))
1182         {
1183           /* Only send activation replies to regular activation requests. */
1184           if (!entry->auto_activation)
1185             {
1186               dbus_uint32_t result;
1187
1188               message = dbus_message_new_method_return (entry->activation_message);
1189               if (!message)
1190                 {
1191                   BUS_SET_OOM (error);
1192                   goto error;
1193                 }
1194
1195               result = DBUS_START_REPLY_SUCCESS;
1196
1197               if (!dbus_message_append_args (message,
1198                                              DBUS_TYPE_UINT32, &result,
1199                                              DBUS_TYPE_INVALID))
1200                 {
1201                   dbus_message_unref (message);
1202                   BUS_SET_OOM (error);
1203                   goto error;
1204                 }
1205
1206               if (!bus_transaction_send_from_driver (transaction, entry->connection, message))
1207                 {
1208                   dbus_message_unref (message);
1209                   BUS_SET_OOM (error);
1210                   goto error;
1211                 }
1212
1213               dbus_message_unref (message);
1214             }
1215         }
1216
1217       link = next;
1218     }
1219
1220   return TRUE;
1221
1222  error:
1223   return FALSE;
1224 }
1225
1226 dbus_bool_t
1227 bus_activation_send_pending_auto_activation_messages (BusActivation  *activation,
1228                                                       BusService     *service,
1229                                                       BusTransaction *transaction)
1230 {
1231   BusPendingActivation *pending_activation;
1232   DBusList *link;
1233
1234   /* Check if it's a pending activation */
1235   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations,
1236                                                        bus_service_get_name (service));
1237
1238   if (!pending_activation)
1239     return TRUE;
1240
1241   link = _dbus_list_get_first_link (&pending_activation->entries);
1242   while (link != NULL)
1243     {
1244       BusPendingActivationEntry *entry = link->data;
1245       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1246
1247       if (entry->auto_activation && !entry->is_put_back &&
1248           (entry->connection == NULL || dbus_connection_get_is_connected (entry->connection)))
1249         {
1250           DBusConnection *addressed_recipient;
1251           DBusError error;
1252
1253           dbus_error_init (&error);
1254
1255           addressed_recipient = bus_service_get_primary_owners_connection (service);
1256
1257           /* Resume dispatching where we left off in bus_dispatch() */
1258           switch (bus_dispatch_matches (transaction,
1259                                         entry->connection,
1260                                         addressed_recipient,
1261                                         entry->activation_message, NULL, &error))
1262             {
1263             case BUS_RESULT_TRUE:
1264               break;
1265             case BUS_RESULT_FALSE:
1266               /* If permission is denied, we just want to return the error
1267                * to the original method invoker; in particular, we don't
1268                * want to make the RequestName call fail with that error
1269                * (see fd.o #78979, CVE-2014-3477). */
1270               if (!bus_transaction_send_error_reply (transaction, entry->connection,
1271                                                      &error, entry->activation_message))
1272                 {
1273                   bus_connection_send_oom_error (entry->connection,
1274                                                  entry->activation_message);
1275                 }
1276
1277               dbus_error_free (&error);
1278               link = next;
1279               continue;
1280             case BUS_RESULT_LATER:
1281               {
1282                 DBusList *putback_message_link = link;
1283                 DBusMessage *last_inserted_message = NULL;
1284
1285                 /* NULL entry->connection implies sending pending ActivationRequest message to systemd */
1286                 if (entry->connection == NULL)
1287                   {
1288                     _dbus_assert_not_reached ("bus_dispatch_matches returned BUS_RESULT_LATER unexpectedly when sender is NULL");
1289                     link = next;
1290                     continue;
1291                   }
1292
1293                 /**
1294                  * Getting here means that policy check result is not yet available and dispatching
1295                  * messages from entry->connection has been disabled.
1296                  * Let's put back all messages for the given connection in the incoming queue and mark
1297                  * this entry as put back so they are not handled twice.
1298                  */
1299                 while (putback_message_link != NULL)
1300                   {
1301                     BusPendingActivationEntry *putback_message = putback_message_link->data;
1302                     if (putback_message->connection == entry->connection)
1303                       {
1304                         if (!_dbus_connection_putback_message (putback_message->connection, last_inserted_message,
1305                               putback_message->activation_message, &error))
1306                           goto error;
1307                         last_inserted_message = putback_message->activation_message;
1308                         putback_message->is_put_back = TRUE;
1309                       }
1310
1311                     putback_message_link = _dbus_list_get_next_link(&pending_activation->entries, putback_message_link);
1312                   }
1313                 break;
1314               }
1315             }
1316         }
1317
1318       link = next;
1319     }
1320
1321   if (!add_restore_pending_to_transaction (transaction, pending_activation))
1322     {
1323       _dbus_verbose ("Could not add cancel hook to transaction to revert removing pending activation\n");
1324       goto error;
1325     }
1326
1327   _dbus_hash_table_remove_string (activation->pending_activations, bus_service_get_name (service));
1328
1329   return TRUE;
1330
1331  error:
1332   /* remove all messages that have been put to connections' incoming queues */
1333   link = _dbus_list_get_first_link (&pending_activation->entries);
1334   while (link != NULL)
1335     {
1336       BusPendingActivationEntry *entry = link->data;
1337       if (entry->is_put_back)
1338         {
1339           _dbus_connection_remove_message(entry->connection, entry->activation_message);
1340           entry->is_put_back = FALSE;
1341         }
1342       link = _dbus_list_get_next_link(&pending_activation->entries, link);
1343     }
1344
1345   return FALSE;
1346 }
1347
1348 /**
1349  * FIXME @todo the error messages here would ideally be preallocated
1350  * so we don't need to allocate memory to send them.
1351  * Using the usual tactic, prealloc an OOM message, then
1352  * if we can't alloc the real error send the OOM error instead.
1353  */
1354 static dbus_bool_t
1355 try_send_activation_failure (BusPendingActivation *pending_activation,
1356                              const DBusError      *how)
1357 {
1358   BusActivation *activation;
1359   DBusList *link;
1360   BusTransaction *transaction;
1361
1362   activation = pending_activation->activation;
1363
1364   transaction = bus_transaction_new (activation->context);
1365   if (transaction == NULL)
1366     return FALSE;
1367
1368   link = _dbus_list_get_first_link (&pending_activation->entries);
1369   while (link != NULL)
1370     {
1371       BusPendingActivationEntry *entry = link->data;
1372       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1373
1374       if (entry->connection && dbus_connection_get_is_connected (entry->connection))
1375         {
1376           if (!bus_transaction_send_error_reply (transaction,
1377                                                  entry->connection,
1378                                                  how,
1379                                                  entry->activation_message))
1380             goto error;
1381         }
1382
1383       link = next;
1384     }
1385
1386   bus_transaction_execute_and_free (transaction);
1387
1388   return TRUE;
1389
1390  error:
1391   if (transaction)
1392     bus_transaction_cancel_and_free (transaction);
1393   return FALSE;
1394 }
1395
1396 /**
1397  * Free the pending activation and send an error message to all the
1398  * connections that were waiting for it.
1399  */
1400 static void
1401 pending_activation_failed (BusPendingActivation *pending_activation,
1402                            const DBusError      *how)
1403 {
1404   /* FIXME use preallocated OOM messages instead of bus_wait_for_memory() */
1405   while (!try_send_activation_failure (pending_activation, how))
1406     _dbus_wait_for_memory ();
1407
1408   /* Destroy this pending activation */
1409   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1410                                   pending_activation->service_name);
1411 }
1412
1413 /**
1414  * Depending on the exit code of the helper, set the error accordingly
1415  */
1416 static void
1417 handle_servicehelper_exit_error (int        exit_code,
1418                                  DBusError *error)
1419 {
1420   switch (exit_code)
1421     {
1422     case BUS_SPAWN_EXIT_CODE_CONFIG_INVALID:
1423       dbus_set_error (error, DBUS_ERROR_SPAWN_CONFIG_INVALID,
1424                       "Invalid configuration (missing or empty <user>?)");
1425       break;
1426     case BUS_SPAWN_EXIT_CODE_NO_MEMORY:
1427       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1428                       "Launcher could not run (out of memory)");
1429       break;
1430     case BUS_SPAWN_EXIT_CODE_SETUP_FAILED:
1431       dbus_set_error (error, DBUS_ERROR_SPAWN_SETUP_FAILED,
1432                       "Failed to setup environment correctly");
1433       break;
1434     case BUS_SPAWN_EXIT_CODE_NAME_INVALID:
1435       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_INVALID,
1436                       "Bus name is not valid or missing");
1437       break;
1438     case BUS_SPAWN_EXIT_CODE_SERVICE_NOT_FOUND:
1439       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND,
1440                       "Bus name not found in system service directory");
1441       break;
1442     case BUS_SPAWN_EXIT_CODE_PERMISSIONS_INVALID:
1443       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1444                       "The permission of the setuid helper is not correct");
1445       break;
1446     case BUS_SPAWN_EXIT_CODE_FILE_INVALID:
1447       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1448                       "The service file is incorrect or does not have all required attributes");
1449       break;
1450     case BUS_SPAWN_EXIT_CODE_EXEC_FAILED:
1451       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
1452                       "Cannot launch daemon, file not found or permissions invalid");
1453       break;
1454     case BUS_SPAWN_EXIT_CODE_INVALID_ARGS:
1455       dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1456                       "Invalid arguments to command line");
1457       break;
1458     case BUS_SPAWN_EXIT_CODE_CHILD_SIGNALED:
1459       dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
1460                       "Launched child was signaled, it probably crashed");
1461       break;
1462     case BUS_SPAWN_EXIT_CODE_GENERIC_FAILURE:
1463     default:
1464       dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
1465                       "Launch helper exited with unknown return code %i", exit_code);
1466       break;
1467     }
1468 }
1469
1470 static void
1471 pending_activation_finished_cb (DBusBabysitter *babysitter,
1472                                 void           *data)
1473 {
1474   BusPendingActivation *pending_activation = data;
1475   dbus_bool_t uses_servicehelper;
1476
1477   _dbus_assert (babysitter == pending_activation->babysitter);
1478   _dbus_babysitter_ref (babysitter);
1479
1480   /* There are two major cases here; are we the system bus or the session?  Here this
1481    * is distinguished by whether or not we use a setuid helper launcher.  With the launch helper,
1482    * some process exit codes are meaningful, processed by handle_servicehelper_exit_error.
1483    *
1484    * In both cases though, just ignore when a process exits with status 0; it's possible for
1485    * a program to (misguidedly) "daemonize", and that appears to us as an exit.  This closes a race
1486    * condition between this code and the child process claiming the bus name.
1487    */
1488   uses_servicehelper = bus_context_get_servicehelper (pending_activation->activation->context) != NULL;
1489
1490   /* strictly speaking this is redundant with the check in dbus-spawn now */
1491   if (_dbus_babysitter_get_child_exited (babysitter))
1492     {
1493       DBusError error;
1494       DBusHashIter iter;
1495       dbus_bool_t activation_failed;
1496       int exit_code = 0;
1497
1498       dbus_error_init (&error);
1499
1500       _dbus_babysitter_set_child_exit_error (babysitter, &error);
1501
1502       /* Explicitly check for SPAWN_CHILD_EXITED to avoid overwriting an
1503        * exec error */
1504       if (dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)
1505           && _dbus_babysitter_get_child_exit_status (babysitter, &exit_code))
1506         {
1507           activation_failed = exit_code != 0;
1508
1509           dbus_error_free(&error);
1510
1511           if (activation_failed)
1512             {
1513               if (uses_servicehelper)
1514                 handle_servicehelper_exit_error (exit_code, &error);
1515               else
1516                 _dbus_babysitter_set_child_exit_error (babysitter, &error);
1517             }
1518         }
1519       else
1520         {
1521           activation_failed = TRUE;
1522         }
1523
1524       if (activation_failed)
1525         {
1526           bus_context_log (pending_activation->activation->context,
1527                            DBUS_SYSTEM_LOG_INFO, "Activated service '%s' failed: %s",
1528                            pending_activation->service_name,
1529                            error.message);
1530
1531           /* Destroy all pending activations with the same exec */
1532           _dbus_hash_iter_init (pending_activation->activation->pending_activations,
1533                                 &iter);
1534           while (_dbus_hash_iter_next (&iter))
1535             {
1536               BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1537
1538               if (p != pending_activation && p->exec != NULL &&
1539                   strcmp (p->exec, pending_activation->exec) == 0)
1540                 pending_activation_failed (p, &error);
1541             }
1542
1543           /* Destroys the pending activation */
1544           pending_activation_failed (pending_activation, &error);
1545
1546           dbus_error_free (&error);
1547         }
1548     }
1549
1550   _dbus_babysitter_unref (babysitter);
1551 }
1552
1553 static dbus_bool_t
1554 add_babysitter_watch (DBusWatch      *watch,
1555                       void           *data)
1556 {
1557   BusPendingActivation *pending_activation = data;
1558
1559   return _dbus_loop_add_watch (
1560       bus_context_get_loop (pending_activation->activation->context),
1561       watch);
1562 }
1563
1564 static void
1565 remove_babysitter_watch (DBusWatch      *watch,
1566                          void           *data)
1567 {
1568   BusPendingActivation *pending_activation = data;
1569
1570   _dbus_loop_remove_watch (bus_context_get_loop (pending_activation->activation->context),
1571                            watch);
1572 }
1573
1574 static void
1575 toggle_babysitter_watch (DBusWatch      *watch,
1576                          void           *data)
1577 {
1578   BusPendingActivation *pending_activation = data;
1579
1580   _dbus_loop_toggle_watch (bus_context_get_loop (pending_activation->activation->context),
1581                            watch);
1582 }
1583
1584 static dbus_bool_t
1585 pending_activation_timed_out (void *data)
1586 {
1587   BusPendingActivation *pending_activation = data;
1588   BusContext *context;
1589   DBusError error;
1590   int timeout;
1591
1592   context = pending_activation->activation->context;
1593   timeout = bus_context_get_activation_timeout (context);
1594
1595   /* Kill the spawned process, since it sucks
1596    * (not sure this is what we want to do, but
1597    * may as well try it for now)
1598    */
1599   if (pending_activation->babysitter)
1600     _dbus_babysitter_kill_child (pending_activation->babysitter);
1601
1602   dbus_error_init (&error);
1603
1604   bus_context_log_and_set_error (context, DBUS_SYSTEM_LOG_WARNING, &error,
1605                    DBUS_ERROR_TIMED_OUT,
1606                    "Failed to activate service '%s': timed out "
1607                    "(service_start_timeout=%dms)",
1608                    pending_activation->service_name, timeout);
1609
1610   pending_activation_failed (pending_activation, &error);
1611
1612   dbus_error_free (&error);
1613
1614   return TRUE;
1615 }
1616
1617 static void
1618 cancel_pending (void *data)
1619 {
1620   BusPendingActivation *pending_activation = data;
1621
1622   _dbus_verbose ("Canceling pending activation of %s\n",
1623                  pending_activation->service_name);
1624
1625   if (pending_activation->babysitter)
1626     _dbus_babysitter_kill_child (pending_activation->babysitter);
1627
1628   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1629                                   pending_activation->service_name);
1630 }
1631
1632 static void
1633 free_pending_cancel_data (void *data)
1634 {
1635   BusPendingActivation *pending_activation = data;
1636
1637   bus_pending_activation_unref (pending_activation);
1638 }
1639
1640 static dbus_bool_t
1641 add_cancel_pending_to_transaction (BusTransaction       *transaction,
1642                                    BusPendingActivation *pending_activation)
1643 {
1644   if (!bus_transaction_add_cancel_hook (transaction, cancel_pending,
1645                                         pending_activation,
1646                                         free_pending_cancel_data))
1647     return FALSE;
1648
1649   bus_pending_activation_ref (pending_activation);
1650
1651   _dbus_verbose ("Saved pending activation to be canceled if the transaction fails\n");
1652
1653   return TRUE;
1654 }
1655
1656 static dbus_bool_t
1657 update_service_cache (BusActivation *activation, DBusError *error)
1658 {
1659   DBusList *iter;
1660
1661   for (iter = _dbus_list_get_first_link (&activation->directories);
1662        iter != NULL;
1663        iter = _dbus_list_get_next_link (&activation->directories, iter))
1664     {
1665       DBusError tmp_error;
1666       BusServiceDirectory *s_dir = iter->data;
1667
1668       dbus_error_init (&tmp_error);
1669       if (!update_directory (activation, s_dir, &tmp_error))
1670         {
1671           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
1672             {
1673               dbus_move_error (&tmp_error, error);
1674               return FALSE;
1675             }
1676
1677           dbus_error_free (&tmp_error);
1678           continue;
1679         }
1680     }
1681
1682   return TRUE;
1683 }
1684
1685 static BusActivationEntry *
1686 activation_find_entry (BusActivation *activation,
1687                        const char    *service_name,
1688                        DBusError     *error)
1689 {
1690   BusActivationEntry *entry;
1691
1692   entry = _dbus_hash_table_lookup_string (activation->entries, service_name);
1693   if (!entry)
1694     {
1695       if (!update_service_cache (activation, error))
1696         return NULL;
1697
1698       entry = _dbus_hash_table_lookup_string (activation->entries,
1699                                               service_name);
1700     }
1701   else
1702     {
1703       BusActivationEntry *updated_entry;
1704
1705       if (!check_service_file (activation, entry, &updated_entry, error))
1706         return NULL;
1707
1708       entry = updated_entry;
1709     }
1710
1711   if (!entry)
1712     {
1713       dbus_set_error (error, DBUS_ERROR_SERVICE_UNKNOWN,
1714                       "The name %s was not provided by any .service files",
1715                       service_name);
1716       return NULL;
1717     }
1718
1719   return entry;
1720 }
1721
1722 static char **
1723 bus_activation_get_environment (BusActivation *activation)
1724 {
1725   return _dbus_hash_table_to_array (activation->environment, '=');
1726 }
1727
1728 dbus_bool_t
1729 bus_activation_set_environment_variable (BusActivation     *activation,
1730                                          const char        *key,
1731                                          const char        *value,
1732                                          DBusError         *error)
1733 {
1734   char        *hash_key;
1735   char        *hash_value;
1736   dbus_bool_t  retval;
1737
1738   retval = FALSE;
1739   hash_key = NULL;
1740   hash_value = NULL;
1741   hash_key = _dbus_strdup (key);
1742
1743   if (hash_key == NULL)
1744     goto out;
1745
1746   hash_value = _dbus_strdup (value);
1747
1748   if (hash_value == NULL)
1749     goto out;
1750
1751   if (!_dbus_hash_table_insert_string (activation->environment,
1752                                        hash_key, hash_value))
1753     goto out;
1754
1755   retval = TRUE;
1756 out:
1757   if (retval == FALSE)
1758     {
1759       dbus_free (hash_key);
1760       dbus_free (hash_value);
1761       BUS_SET_OOM (error);
1762     }
1763
1764   return retval;
1765 }
1766
1767 static void
1768 child_setup (void *user_data)
1769 {
1770 #ifdef DBUS_UNIX
1771   BusActivation *activation = user_data;
1772   DBusRLimit *initial_fd_limit;
1773   DBusError error;
1774
1775   dbus_error_init (&error);
1776   initial_fd_limit = bus_context_get_initial_fd_limit (activation->context);
1777
1778   if (initial_fd_limit != NULL &&
1779       !_dbus_rlimit_restore_fd_limit (initial_fd_limit, &error))
1780     {
1781       /* unfortunately we don't actually know the service name here */
1782       bus_context_log (activation->context,
1783                        DBUS_SYSTEM_LOG_WARNING,
1784                        "Failed to reset fd limit before activating "
1785                        "service: %s: %s",
1786                        error.name, error.message);
1787     }
1788 #endif
1789 }
1790
1791
1792 BusResult
1793 bus_activation_activate_service (BusActivation  *activation,
1794                                  DBusConnection *connection,
1795                                  BusTransaction *transaction,
1796                                  dbus_bool_t     auto_activation,
1797                                  DBusMessage    *activation_message,
1798                                  const char     *service_name,
1799                                  DBusError      *error,
1800                                  BusDeferredMessage **deferred_message)
1801 {
1802   DBusError tmp_error;
1803   BusActivationEntry *entry;
1804   BusPendingActivation *pending_activation;
1805   BusPendingActivationEntry *pending_activation_entry;
1806   DBusMessage *message;
1807   DBusString service_str;
1808   const char *servicehelper;
1809   char **argv;
1810   char **envp = NULL;
1811   int argc;
1812   BusResult retval = BUS_RESULT_FALSE;
1813   dbus_bool_t was_pending_activation;
1814   DBusString command;
1815   int limit;
1816   DBusSpawnFlags flags = DBUS_SPAWN_NONE;
1817
1818   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1819
1820   limit = bus_context_get_max_pending_activations (activation->context);
1821
1822   if (activation->n_pending_activations >= limit)
1823     {
1824       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1825                       "The maximum number of pending activations has been "
1826                       "reached, activation of %s failed "
1827                       "(max_pending_service_starts=%d)",
1828                       service_name, limit);
1829       return BUS_RESULT_FALSE;
1830     }
1831
1832   if (bus_context_get_systemd_activation (activation->context) &&
1833       strcmp (service_name, "org.freedesktop.systemd1") == 0)
1834     {
1835       /* if we're doing systemd activation, we assume systemd will connect
1836        * eventually, and it does not need a .service file */
1837       entry = NULL;
1838     }
1839   else
1840     {
1841       entry = activation_find_entry (activation, service_name, error);
1842       if (!entry)
1843         return BUS_RESULT_FALSE;
1844     }
1845
1846   if (auto_activation && entry != NULL)
1847     {
1848       switch (bus_context_check_security_policy (activation->context,
1849         transaction,
1850         connection, /* sender */
1851         NULL, /* addressed recipient */
1852         NULL, /* proposed recipient */
1853         activation_message,
1854         entry,
1855         error,
1856         deferred_message))
1857         {
1858         case BUS_RESULT_TRUE:
1859             break;
1860         case BUS_RESULT_FALSE:
1861           _DBUS_ASSERT_ERROR_IS_SET (error);
1862           _dbus_verbose ("activation not authorized: %s: %s\n",
1863                   error != NULL ? error->name : "(error ignored)",
1864                   error != NULL ? error->message : "(error ignored)");
1865           return BUS_RESULT_FALSE;
1866         case BUS_RESULT_LATER:
1867           return BUS_RESULT_LATER;
1868         }
1869       }
1870
1871   /* Bypass the registry lookup if we're auto-activating, bus_dispatch would not
1872    * call us if the service is already active.
1873    */
1874   if (!auto_activation)
1875     {
1876       /* Check if the service is active */
1877       _dbus_string_init_const (&service_str, service_name);
1878       if (bus_registry_lookup (bus_context_get_registry (activation->context), &service_str) != NULL)
1879         {
1880           dbus_uint32_t result;
1881           dbus_bool_t send_retval;
1882
1883           _dbus_verbose ("Service \"%s\" is already active\n", service_name);
1884
1885           message = dbus_message_new_method_return (activation_message);
1886
1887           if (!message)
1888             {
1889               _dbus_verbose ("No memory to create reply to activate message\n");
1890               BUS_SET_OOM (error);
1891               return BUS_RESULT_FALSE;
1892             }
1893
1894           result = DBUS_START_REPLY_ALREADY_RUNNING;
1895
1896           if (!dbus_message_append_args (message,
1897                                          DBUS_TYPE_UINT32, &result,
1898                                          DBUS_TYPE_INVALID))
1899             {
1900               _dbus_verbose ("No memory to set args of reply to activate message\n");
1901               BUS_SET_OOM (error);
1902               dbus_message_unref (message);
1903               return BUS_RESULT_FALSE;
1904             }
1905
1906           send_retval = bus_transaction_send_from_driver (transaction, connection, message);
1907           dbus_message_unref (message);
1908           if (!send_retval)
1909             {
1910               _dbus_verbose ("Failed to send reply\n");
1911               BUS_SET_OOM (error);
1912               return BUS_RESULT_FALSE;
1913             }
1914
1915           return BUS_RESULT_TRUE;
1916         }
1917     }
1918
1919   pending_activation_entry = dbus_new0 (BusPendingActivationEntry, 1);
1920   if (!pending_activation_entry)
1921     {
1922       _dbus_verbose ("Failed to create pending activation entry\n");
1923       BUS_SET_OOM (error);
1924       return BUS_RESULT_FALSE;
1925     }
1926
1927   pending_activation_entry->auto_activation = auto_activation;
1928
1929   pending_activation_entry->activation_message = activation_message;
1930   dbus_message_ref (activation_message);
1931   pending_activation_entry->connection = connection;
1932   if (connection)
1933     dbus_connection_ref (connection);
1934
1935   /* Check if the service is being activated */
1936   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1937   was_pending_activation = (pending_activation != NULL);
1938   if (was_pending_activation)
1939     {
1940       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1941         {
1942           _dbus_verbose ("Failed to append a new entry to pending activation\n");
1943
1944           BUS_SET_OOM (error);
1945           bus_pending_activation_entry_free (pending_activation_entry);
1946           return BUS_RESULT_FALSE;
1947         }
1948
1949       pending_activation->n_entries += 1;
1950       pending_activation->activation->n_pending_activations += 1;
1951     }
1952   else
1953     {
1954       pending_activation = dbus_new0 (BusPendingActivation, 1);
1955       if (!pending_activation)
1956         {
1957           _dbus_verbose ("Failed to create pending activation\n");
1958
1959           BUS_SET_OOM (error);
1960           bus_pending_activation_entry_free (pending_activation_entry);
1961           return BUS_RESULT_FALSE;
1962         }
1963
1964       pending_activation->activation = activation;
1965       pending_activation->refcount = 1;
1966
1967       pending_activation->service_name = _dbus_strdup (service_name);
1968       if (!pending_activation->service_name)
1969         {
1970           _dbus_verbose ("Failed to copy service name for pending activation\n");
1971
1972           BUS_SET_OOM (error);
1973           bus_pending_activation_unref (pending_activation);
1974           bus_pending_activation_entry_free (pending_activation_entry);
1975           return BUS_RESULT_FALSE;
1976         }
1977
1978       if (entry != NULL)
1979         {
1980           pending_activation->exec = _dbus_strdup (entry->exec);
1981           if (!pending_activation->exec)
1982             {
1983               _dbus_verbose ("Failed to copy service exec for pending activation\n");
1984               BUS_SET_OOM (error);
1985               bus_pending_activation_unref (pending_activation);
1986               bus_pending_activation_entry_free (pending_activation_entry);
1987               return BUS_RESULT_FALSE;
1988             }
1989         }
1990
1991       if (entry != NULL && entry->systemd_service != NULL)
1992         {
1993           pending_activation->systemd_service = _dbus_strdup (entry->systemd_service);
1994           if (!pending_activation->systemd_service)
1995             {
1996               _dbus_verbose ("Failed to copy systemd service for pending activation\n");
1997               BUS_SET_OOM (error);
1998               bus_pending_activation_unref (pending_activation);
1999               bus_pending_activation_entry_free (pending_activation_entry);
2000               return BUS_RESULT_FALSE;
2001             }
2002         }
2003
2004       pending_activation->timeout =
2005         _dbus_timeout_new (bus_context_get_activation_timeout (activation->context),
2006                            pending_activation_timed_out,
2007                            pending_activation,
2008                            NULL);
2009       if (!pending_activation->timeout)
2010         {
2011           _dbus_verbose ("Failed to create timeout for pending activation\n");
2012
2013           BUS_SET_OOM (error);
2014           bus_pending_activation_unref (pending_activation);
2015           bus_pending_activation_entry_free (pending_activation_entry);
2016           return BUS_RESULT_FALSE;
2017         }
2018
2019       if (!_dbus_loop_add_timeout (bus_context_get_loop (activation->context),
2020                                    pending_activation->timeout))
2021         {
2022           _dbus_verbose ("Failed to add timeout for pending activation\n");
2023
2024           BUS_SET_OOM (error);
2025           bus_pending_activation_unref (pending_activation);
2026           bus_pending_activation_entry_free (pending_activation_entry);
2027           return BUS_RESULT_FALSE;
2028         }
2029
2030       pending_activation->timeout_added = TRUE;
2031
2032       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
2033         {
2034           _dbus_verbose ("Failed to add entry to just-created pending activation\n");
2035
2036           BUS_SET_OOM (error);
2037           bus_pending_activation_unref (pending_activation);
2038           bus_pending_activation_entry_free (pending_activation_entry);
2039           return BUS_RESULT_FALSE;
2040         }
2041
2042       pending_activation->n_entries += 1;
2043       pending_activation->activation->n_pending_activations += 1;
2044
2045       if (!_dbus_hash_table_insert_string (activation->pending_activations,
2046                                            pending_activation->service_name,
2047                                            pending_activation))
2048         {
2049           _dbus_verbose ("Failed to put pending activation in hash table\n");
2050
2051           BUS_SET_OOM (error);
2052           bus_pending_activation_unref (pending_activation);
2053           return BUS_RESULT_FALSE;
2054         }
2055     }
2056
2057   if (!add_cancel_pending_to_transaction (transaction, pending_activation))
2058     {
2059       _dbus_verbose ("Failed to add pending activation cancel hook to transaction\n");
2060       BUS_SET_OOM (error);
2061       goto cancel_pending_activation;
2062     }
2063
2064   if (was_pending_activation)
2065     return BUS_RESULT_TRUE;
2066
2067   if (bus_context_get_systemd_activation (activation->context))
2068     {
2069       if (strcmp (service_name, "org.freedesktop.systemd1") == 0)
2070           /* systemd itself is missing apparently. That can happen
2071              only during early startup. Let's just wait until systemd
2072              connects to us and do nothing. */
2073         return BUS_RESULT_TRUE;
2074
2075       if (entry->systemd_service)
2076         {
2077           BusTransaction *activation_transaction;
2078           DBusString service_string;
2079           BusService *service;
2080           BusRegistry *registry;
2081           DBusConnection *systemd = NULL;
2082
2083           /* OK, we have a systemd service configured for this entry,
2084              hence let's enqueue an activation request message. This
2085              is implemented as a directed signal, not a method call,
2086              for three reasons: 1) we don't expect a response on
2087              success, where we just expect a name appearing on the
2088              bus; 2) at this time the systemd service might not yet
2089              have connected, so we wouldn't know the message serial at
2090              this point to set up a pending call; 3) it is ugly if the
2091              bus suddenly becomes the caller of a remote method. */
2092
2093           message = dbus_message_new_signal (DBUS_PATH_DBUS,
2094                                              "org.freedesktop.systemd1.Activator",
2095                                              "ActivationRequest");
2096           if (!message)
2097             {
2098               _dbus_verbose ("No memory to create activation message\n");
2099               BUS_SET_OOM (error);
2100               goto cancel_pending_activation;
2101             }
2102
2103           if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS) ||
2104               !dbus_message_set_destination (message, "org.freedesktop.systemd1") ||
2105               !dbus_message_append_args (message,
2106                                          DBUS_TYPE_STRING, &entry->systemd_service,
2107                                          DBUS_TYPE_INVALID))
2108             {
2109               _dbus_verbose ("No memory to set args of activation message\n");
2110               dbus_message_unref (message);
2111               BUS_SET_OOM (error);
2112               goto cancel_pending_activation;
2113             }
2114
2115           /* Create our transaction */
2116           activation_transaction = bus_transaction_new (activation->context);
2117           if (activation_transaction == NULL)
2118             {
2119               _dbus_verbose ("No memory to create activation transaction\n");
2120               dbus_message_unref (message);
2121               BUS_SET_OOM (error);
2122               goto cancel_pending_activation;
2123             }
2124
2125           /* Check whether systemd is already connected */
2126           registry = bus_connection_get_registry (connection);
2127           _dbus_string_init_const (&service_string, "org.freedesktop.systemd1");
2128           service = bus_registry_lookup (registry, &service_string);
2129
2130           if (service)
2131             systemd = bus_service_get_primary_owners_connection (service);
2132
2133           /* Following the general principle of "log early and often",
2134            * we capture that we *want* to send the activation message, even if
2135            * systemd is not actually there to receive it yet */
2136           if (!bus_transaction_capture (activation_transaction,
2137                                         NULL, systemd, message))
2138             {
2139               dbus_message_unref (message);
2140               BUS_SET_OOM (error);
2141               goto cancel_pending_activation;
2142             }
2143
2144           if (service != NULL)
2145             {
2146               bus_context_log (activation->context,
2147                                DBUS_SYSTEM_LOG_INFO, "Activating via systemd: service name='%s' unit='%s' requested by '%s' (%s)",
2148                                service_name,
2149                                entry->systemd_service,
2150                                bus_connection_get_name (connection),
2151                                bus_connection_get_loginfo (connection));
2152               /* Wonderful, systemd is connected, let's just send the msg */
2153               retval = bus_dispatch_matches (activation_transaction, NULL,
2154                                              systemd, message, NULL, error);
2155               if (BUS_RESULT_LATER == retval)
2156                 _dbus_verbose("Unexpectedly need time to check message from bus driver to systemd - dropping the message.\n");
2157             }
2158           else
2159             {
2160               bus_context_log (activation->context,
2161                                DBUS_SYSTEM_LOG_INFO, "Activating systemd to hand-off: service name='%s' unit='%s' requested by '%s' (%s)",
2162                                service_name,
2163                                entry->systemd_service,
2164                                bus_connection_get_name (connection),
2165                                bus_connection_get_loginfo (connection));
2166               /* systemd is not around, let's "activate" it. */
2167               retval = bus_activation_activate_service (activation, NULL, activation_transaction, TRUE,
2168                                                         message, "org.freedesktop.systemd1", error, deferred_message);
2169             }
2170
2171           dbus_message_unref (message);
2172
2173           if (retval != BUS_RESULT_TRUE)
2174             {
2175               bus_context_log (activation->context,
2176                                DBUS_SYSTEM_LOG_INFO, "Failed to activate via systemd: service name='%s' unit='%s'",
2177                                service_name,
2178                                entry->systemd_service);
2179               _DBUS_ASSERT_ERROR_IS_SET (error);
2180               _dbus_verbose ("failed to send activation message: %s\n", error->name);
2181               bus_transaction_cancel_and_free (activation_transaction);
2182               goto cancel_pending_activation;
2183             }
2184
2185           bus_transaction_execute_and_free (activation_transaction);
2186           return BUS_RESULT_TRUE;
2187         }
2188
2189       /* OK, we have no configured systemd service, hence let's
2190          proceed with traditional activation. */
2191     }
2192
2193   /* If entry was NULL, it would be because we were doing systemd activation
2194    * and activating systemd itself; but we already handled that case with
2195    * an early-return */
2196   _dbus_assert (entry != NULL);
2197
2198   /* use command as system and session different */
2199   if (!_dbus_string_init (&command))
2200     {
2201       BUS_SET_OOM (error);
2202       goto cancel_pending_activation;
2203     }
2204
2205   /* does the bus use a helper? */
2206   servicehelper = bus_context_get_servicehelper (activation->context);
2207   if (servicehelper != NULL)
2208     {
2209       if (entry->user == NULL)
2210         {
2211           _dbus_string_free (&command);
2212           dbus_set_error (error, DBUS_ERROR_SPAWN_FILE_INVALID,
2213                           "Cannot do system-bus activation with no user\n");
2214           goto cancel_pending_activation;
2215         }
2216
2217       /* join the helper path and the service name */
2218       if (!_dbus_string_append (&command, servicehelper))
2219         {
2220           _dbus_string_free (&command);
2221           BUS_SET_OOM (error);
2222           goto cancel_pending_activation;
2223         }
2224       if (!_dbus_string_append (&command, " "))
2225         {
2226           _dbus_string_free (&command);
2227           BUS_SET_OOM (error);
2228           goto cancel_pending_activation;
2229         }
2230       if (!_dbus_string_append (&command, service_name))
2231         {
2232           _dbus_string_free (&command);
2233           BUS_SET_OOM (error);
2234           goto cancel_pending_activation;
2235         }
2236     }
2237   else
2238     {
2239       /* the bus does not use a helper, so we can append arguments with the exec line */
2240       if (!_dbus_string_append (&command, entry->exec))
2241         {
2242           _dbus_string_free (&command);
2243           BUS_SET_OOM (error);
2244           goto cancel_pending_activation;
2245         }
2246     }
2247
2248   /* convert command into arguments */
2249   if (!_dbus_shell_parse_argv (_dbus_string_get_const_data (&command), &argc, &argv, error))
2250     {
2251       _dbus_verbose ("Failed to parse command line: %s\n", entry->exec);
2252       _DBUS_ASSERT_ERROR_IS_SET (error);
2253       _dbus_string_free (&command);
2254       goto cancel_pending_activation;
2255     }
2256   _dbus_string_free (&command);
2257
2258   if (!add_bus_environment (activation, error))
2259     {
2260       _DBUS_ASSERT_ERROR_IS_SET (error);
2261       dbus_free_string_array (argv);
2262       goto cancel_pending_activation;
2263     }
2264
2265   envp = bus_activation_get_environment (activation);
2266
2267   if (envp == NULL)
2268     {
2269       BUS_SET_OOM (error);
2270       dbus_free_string_array (argv);
2271       goto cancel_pending_activation;
2272     }
2273
2274   _dbus_verbose ("Spawning %s ...\n", argv[0]);
2275   if (servicehelper != NULL)
2276     bus_context_log (activation->context,
2277                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s' requested by '%s' (%s) (using servicehelper)",
2278                      service_name,
2279                      bus_connection_get_name (connection),
2280                      bus_connection_get_loginfo (connection));
2281   else
2282     bus_context_log (activation->context,
2283                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s' requested by '%s' (%s)",
2284                      service_name,
2285                      bus_connection_get_name (connection),
2286                      bus_connection_get_loginfo (connection));
2287
2288   dbus_error_init (&tmp_error);
2289
2290   if (bus_context_get_using_syslog (activation->context))
2291     flags |= DBUS_SPAWN_REDIRECT_OUTPUT;
2292
2293   if (!_dbus_spawn_async_with_babysitter (&pending_activation->babysitter,
2294                                           service_name,
2295                                           argv,
2296                                           envp,
2297                                           flags,
2298                                           child_setup,
2299                                           activation,
2300                                           &tmp_error))
2301     {
2302       _dbus_verbose ("Failed to spawn child\n");
2303       bus_context_log (activation->context,
2304                        DBUS_SYSTEM_LOG_INFO, "Failed to activate service %s: %s",
2305                        service_name,
2306                        tmp_error.message);
2307       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
2308       dbus_move_error (&tmp_error, error);
2309       dbus_free_string_array (argv);
2310       dbus_free_string_array (envp);
2311       goto cancel_pending_activation;
2312     }
2313
2314   dbus_free_string_array (argv);
2315   envp = NULL;
2316
2317   _dbus_assert (pending_activation->babysitter != NULL);
2318
2319   _dbus_babysitter_set_result_function (pending_activation->babysitter,
2320                                         pending_activation_finished_cb,
2321                                         pending_activation);
2322
2323   if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
2324                                              add_babysitter_watch,
2325                                              remove_babysitter_watch,
2326                                              toggle_babysitter_watch,
2327                                              pending_activation,
2328                                              NULL))
2329     {
2330       BUS_SET_OOM (error);
2331       _dbus_verbose ("Failed to set babysitter watch functions\n");
2332       goto cancel_pending_activation;
2333     }
2334
2335   return BUS_RESULT_TRUE;
2336
2337 cancel_pending_activation:
2338   _DBUS_ASSERT_ERROR_IS_SET (error);
2339   _dbus_hash_table_remove_string (activation->pending_activations,
2340                                   pending_activation->service_name);
2341   return BUS_RESULT_FALSE;
2342 }
2343
2344 dbus_bool_t
2345 bus_activation_list_services (BusActivation *activation,
2346                               char        ***listp,
2347                               int           *array_len)
2348 {
2349   int i, j, len;
2350   char **retval;
2351   DBusHashIter iter;
2352
2353   len = _dbus_hash_table_get_n_entries (activation->entries);
2354   retval = dbus_new (char *, len + 1);
2355
2356   if (retval == NULL)
2357     return FALSE;
2358
2359   _dbus_hash_iter_init (activation->entries, &iter);
2360   i = 0;
2361   while (_dbus_hash_iter_next (&iter))
2362     {
2363       BusActivationEntry *entry = _dbus_hash_iter_get_value (&iter);
2364
2365       retval[i] = _dbus_strdup (entry->name);
2366       if (retval[i] == NULL)
2367         goto error;
2368
2369       i++;
2370     }
2371
2372   retval[i] = NULL;
2373
2374   if (array_len)
2375     *array_len = len;
2376
2377   *listp = retval;
2378   return TRUE;
2379
2380  error:
2381   for (j = 0; j < i; j++)
2382     dbus_free (retval[j]);
2383   dbus_free (retval);
2384
2385   return FALSE;
2386 }
2387
2388 dbus_bool_t
2389 dbus_activation_systemd_failure (BusActivation *activation,
2390                                  DBusMessage   *message)
2391 {
2392   DBusError error;
2393   const char *code, *str, *unit = NULL;
2394
2395   dbus_error_init(&error);
2396
2397   /* This is called whenever the systemd activator sent us a
2398      response. We'll invalidate all pending activations that match the
2399      unit name. */
2400
2401   if (dbus_message_get_args (message, &error,
2402                              DBUS_TYPE_STRING, &unit,
2403                              DBUS_TYPE_STRING, &code,
2404                              DBUS_TYPE_STRING, &str,
2405                              DBUS_TYPE_INVALID))
2406     dbus_set_error (&error, code, "%s", str);
2407
2408
2409   if (unit)
2410     {
2411       DBusHashIter iter;
2412
2413       bus_context_log (activation->context,
2414                        DBUS_SYSTEM_LOG_INFO, "Activation via systemd failed for unit '%s': %s",
2415                        unit,
2416                        str);
2417
2418       _dbus_hash_iter_init (activation->pending_activations,
2419                             &iter);
2420
2421       while (_dbus_hash_iter_next (&iter))
2422         {
2423           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
2424
2425           if (p->systemd_service && strcmp (p->systemd_service, unit) == 0)
2426             pending_activation_failed(p, &error);
2427         }
2428     }
2429
2430   dbus_error_free(&error);
2431
2432   return TRUE;
2433 }
2434
2435 const char *
2436 bus_activation_entry_get_assumed_apparmor_label (BusActivationEntry *entry)
2437 {
2438   return entry->assumed_apparmor_label;
2439 }
2440
2441 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
2442
2443 #include <stdio.h>
2444
2445 #define SERVICE_NAME_1 "com.example.MyService1"
2446 #define SERVICE_NAME_2 "org.example.MyService2"
2447 #define SERVICE_NAME_3 "net.example.MyService3"
2448
2449 #define SERVICE_FILE_1 "service-1.service"
2450 #define SERVICE_FILE_2 "service-2.service"
2451 #define SERVICE_FILE_3 "service-3.service"
2452
2453 static dbus_bool_t
2454 test_create_service_file (DBusString *dir,
2455                           const char *filename,
2456                           const char *name,
2457                           const char *exec)
2458 {
2459   DBusString  file_name, full_path;
2460   FILE        *file;
2461   dbus_bool_t  ret_val;
2462
2463   ret_val = TRUE;
2464   _dbus_string_init_const (&file_name, filename);
2465
2466   if (!_dbus_string_init (&full_path))
2467     return FALSE;
2468
2469   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2470       !_dbus_concat_dir_and_file (&full_path, &file_name))
2471     {
2472       ret_val = FALSE;
2473       goto out;
2474     }
2475
2476   file = fopen (_dbus_string_get_const_data (&full_path), "w");
2477   if (!file)
2478     {
2479       ret_val = FALSE;
2480       goto out;
2481     }
2482
2483   fprintf (file, "[D-BUS Service]\nName=%s\nExec=%s\n", name, exec);
2484   fclose (file);
2485
2486 out:
2487   _dbus_string_free (&full_path);
2488   return ret_val;
2489 }
2490
2491 static dbus_bool_t
2492 test_remove_service_file (DBusString *dir, const char *filename)
2493 {
2494   DBusString  file_name, full_path;
2495   dbus_bool_t ret_val;
2496
2497   ret_val = TRUE;
2498
2499   _dbus_string_init_const (&file_name, filename);
2500
2501   if (!_dbus_string_init (&full_path))
2502     return FALSE;
2503
2504   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2505       !_dbus_concat_dir_and_file (&full_path, &file_name))
2506     {
2507       ret_val = FALSE;
2508       goto out;
2509     }
2510
2511   if (!_dbus_delete_file (&full_path, NULL))
2512     {
2513       ret_val = FALSE;
2514       goto out;
2515     }
2516
2517 out:
2518   _dbus_string_free (&full_path);
2519   return ret_val;
2520 }
2521
2522 static dbus_bool_t
2523 test_remove_directory (DBusString *dir)
2524 {
2525   DBusDirIter *iter;
2526   DBusString   filename, full_path;
2527   dbus_bool_t  ret_val;
2528
2529   ret_val = TRUE;
2530
2531   if (!_dbus_string_init (&filename))
2532     return FALSE;
2533
2534   if (!_dbus_string_init (&full_path))
2535     {
2536       _dbus_string_free (&filename);
2537       return FALSE;
2538     }
2539
2540   iter = _dbus_directory_open (dir, NULL);
2541   if (iter == NULL)
2542     {
2543       ret_val = FALSE;
2544       goto out;
2545     }
2546
2547   while (_dbus_directory_get_next_file (iter, &filename, NULL))
2548     {
2549       if (!test_remove_service_file (dir, _dbus_string_get_const_data (&filename)))
2550         {
2551           ret_val = FALSE;
2552           _dbus_directory_close (iter);
2553           goto out;
2554         }
2555     }
2556   _dbus_directory_close (iter);
2557
2558   if (!_dbus_delete_directory (dir, NULL))
2559     {
2560       ret_val = FALSE;
2561       goto out;
2562     }
2563
2564 out:
2565   _dbus_string_free (&filename);
2566   _dbus_string_free (&full_path);
2567
2568   return ret_val;
2569 }
2570
2571 static dbus_bool_t
2572 init_service_reload_test (DBusString *dir)
2573 {
2574   if (!_dbus_create_directory (dir, NULL))
2575     return FALSE;
2576
2577   /* Create one initial file */
2578   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_1, "exec-1"))
2579     return FALSE;
2580
2581   return TRUE;
2582 }
2583
2584 static dbus_bool_t
2585 cleanup_service_reload_test (DBusString *dir)
2586 {
2587   if (!test_remove_directory (dir))
2588     return FALSE;
2589
2590   return TRUE;
2591 }
2592
2593 typedef struct
2594 {
2595   BusActivation *activation;
2596   const char    *service_name;
2597   dbus_bool_t    expecting_find;
2598 } CheckData;
2599
2600 static dbus_bool_t
2601 check_func (void *data)
2602 {
2603   CheckData          *d;
2604   BusActivationEntry *entry;
2605   DBusError           error;
2606   dbus_bool_t         ret_val;
2607
2608   ret_val = TRUE;
2609   d = data;
2610
2611   dbus_error_init (&error);
2612
2613   entry = activation_find_entry (d->activation, d->service_name, &error);
2614   if (entry == NULL)
2615     {
2616       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
2617         {
2618           ret_val = TRUE;
2619         }
2620       else
2621         {
2622           if (d->expecting_find)
2623             ret_val = FALSE;
2624         }
2625
2626       dbus_error_free (&error);
2627     }
2628   else
2629     {
2630       if (!d->expecting_find)
2631         ret_val = FALSE;
2632     }
2633
2634   return ret_val;
2635 }
2636
2637 static dbus_bool_t
2638 do_test (const char *description, dbus_bool_t oom_test, CheckData *data)
2639 {
2640   dbus_bool_t err;
2641
2642   if (oom_test)
2643     err = !_dbus_test_oom_handling (description, check_func, data);
2644   else
2645     err = !check_func (data);
2646
2647   if (err)
2648     _dbus_assert_not_reached ("Test failed");
2649
2650   return TRUE;
2651 }
2652
2653 static dbus_bool_t
2654 do_service_reload_test (const DBusString *test_data_dir,
2655                         DBusString       *dir,
2656                         dbus_bool_t       oom_test)
2657 {
2658   BusActivation *activation;
2659   BusConfigServiceDir config;
2660   BusContext    *context;
2661   DBusString     address;
2662   DBusList      *directories;
2663   CheckData      d;
2664
2665   directories = NULL;
2666   _dbus_string_init_const (&address, "");
2667
2668   config.path = _dbus_string_get_data (dir);
2669   config.flags = BUS_SERVICE_DIR_FLAGS_NONE;
2670
2671   if (!_dbus_list_append (&directories, &config))
2672     return FALSE;
2673
2674   context = bus_context_new_test (test_data_dir,
2675                                   "valid-config-files/debug-allow-all.conf");
2676   if (context == NULL)
2677     return FALSE;
2678
2679   activation = bus_activation_new (context, &address, &directories, NULL);
2680   if (!activation)
2681     return FALSE;
2682
2683   d.activation = activation;
2684
2685   /* Check for existing service file */
2686   d.expecting_find = TRUE;
2687   d.service_name = SERVICE_NAME_1;
2688
2689   if (!do_test ("Existing service file", oom_test, &d))
2690     return FALSE;
2691
2692   /* Check for non-existing service file */
2693   d.expecting_find = FALSE;
2694   d.service_name = SERVICE_NAME_3;
2695
2696   if (!do_test ("Nonexisting service file", oom_test, &d))
2697     return FALSE;
2698
2699   /* Check for added service file */
2700   if (!test_create_service_file (dir, SERVICE_FILE_2, SERVICE_NAME_2, "exec-2"))
2701     return FALSE;
2702
2703   d.expecting_find = TRUE;
2704   d.service_name = SERVICE_NAME_2;
2705
2706   if (!do_test ("Added service file", oom_test, &d))
2707     return FALSE;
2708
2709   /* Check for removed service file */
2710   if (!test_remove_service_file (dir, SERVICE_FILE_2))
2711     return FALSE;
2712
2713   d.expecting_find = FALSE;
2714   d.service_name = SERVICE_FILE_2;
2715
2716   if (!do_test ("Removed service file", oom_test, &d))
2717     return FALSE;
2718
2719   /* Check for updated service file */
2720
2721   _dbus_sleep_milliseconds (1000); /* Sleep a second to make sure the mtime is updated */
2722
2723   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_3, "exec-3"))
2724     return FALSE;
2725
2726   d.expecting_find = TRUE;
2727   d.service_name = SERVICE_NAME_3;
2728
2729   if (!do_test ("Updated service file, part 1", oom_test, &d))
2730     return FALSE;
2731
2732   d.expecting_find = FALSE;
2733   d.service_name = SERVICE_NAME_1;
2734
2735   if (!do_test ("Updated service file, part 2", oom_test, &d))
2736     return FALSE;
2737
2738   bus_activation_unref (activation);
2739   _dbus_list_clear (&directories);
2740   bus_context_unref (context);
2741
2742   return TRUE;
2743 }
2744
2745 dbus_bool_t
2746 bus_activation_service_reload_test (const DBusString *test_data_dir)
2747 {
2748   DBusString directory;
2749   const char *tmp;
2750   dbus_bool_t ret = FALSE;
2751
2752   if (!_dbus_string_init (&directory))
2753     return FALSE;
2754
2755   tmp = _dbus_get_tmpdir ();
2756
2757   if (tmp == NULL)
2758     goto out;
2759
2760   if (!_dbus_string_append (&directory, tmp))
2761     goto out;
2762
2763   if (!_dbus_string_append (&directory, "/dbus-reload-test-") ||
2764       !_dbus_generate_random_ascii (&directory, 6, NULL))
2765     goto out;
2766
2767   /* Do normal tests */
2768   if (!init_service_reload_test (&directory))
2769     _dbus_assert_not_reached ("could not initiate service reload test");
2770
2771   if (!do_service_reload_test (test_data_dir, &directory, FALSE))
2772     {
2773       /* Do nothing? */
2774     }
2775
2776   if (!cleanup_service_reload_test (&directory))
2777     goto out;
2778
2779   /* Do OOM tests */
2780   if (!init_service_reload_test (&directory))
2781     _dbus_assert_not_reached ("could not initiate service reload test");
2782
2783   if (!do_service_reload_test (test_data_dir, &directory, TRUE))
2784     {
2785       /* Do nothing? */
2786     }
2787
2788   /* Cleanup test directory */
2789   if (!cleanup_service_reload_test (&directory))
2790     goto out;
2791
2792   ret = TRUE;
2793
2794 out:
2795   _dbus_string_free (&directory);
2796   return ret;
2797 }
2798
2799 #endif /* DBUS_ENABLE_EMBEDDED_TESTS */