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