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