activation: Use _dbus_system_log for activation information
[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   name = NULL;
272   exec = NULL;
273   user = NULL;
274   exec_tmp = NULL;
275   entry = NULL;
276   systemd_service = NULL;
277
278   dbus_error_init (&tmp_error);
279
280   if (!_dbus_string_init (&file_path))
281     {
282       BUS_SET_OOM (error);
283       return FALSE;
284     }
285
286   if (!_dbus_string_append (&file_path, s_dir->dir_c) ||
287       !_dbus_concat_dir_and_file (&file_path, filename))
288     {
289       BUS_SET_OOM (error);
290       goto out;
291     }
292
293   if (!_dbus_stat (&file_path, &stat_buf, NULL))
294     {
295       dbus_set_error (error, DBUS_ERROR_FAILED,
296                       "Can't stat the service file\n");
297       goto out;
298     }
299
300   if (!bus_desktop_file_get_string (desktop_file,
301                                     DBUS_SERVICE_SECTION,
302                                     DBUS_SERVICE_NAME,
303                                     &name,
304                                     error))
305     goto out;
306
307   if (!bus_desktop_file_get_string (desktop_file,
308                                     DBUS_SERVICE_SECTION,
309                                     DBUS_SERVICE_EXEC,
310                                     &exec_tmp,
311                                     error))
312     goto out;
313
314   exec = _dbus_strdup (_dbus_replace_install_prefix (exec_tmp));
315   dbus_free (exec_tmp);
316   exec_tmp = NULL;
317
318   /* user is not _required_ unless we are using system activation */
319   if (!bus_desktop_file_get_string (desktop_file,
320                                     DBUS_SERVICE_SECTION,
321                                     DBUS_SERVICE_USER,
322                                     &user, &tmp_error))
323     {
324       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
325       /* if we got OOM, then exit */
326       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
327         {
328           dbus_move_error (&tmp_error, error);
329           goto out;
330         }
331       else
332         {
333           /* if we have error because we didn't find anything then continue */
334           dbus_error_free (&tmp_error);
335           dbus_free (user);
336           user = NULL;
337         }
338     }
339   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
340
341   /* systemd service is never required */
342   if (!bus_desktop_file_get_string (desktop_file,
343                                     DBUS_SERVICE_SECTION,
344                                     DBUS_SERVICE_SYSTEMD_SERVICE,
345                                     &systemd_service, &tmp_error))
346     {
347       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
348       /* if we got OOM, then exit */
349       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
350         {
351           dbus_move_error (&tmp_error, error);
352           goto out;
353         }
354       else
355         {
356           /* if we have error because we didn't find anything then continue */
357           dbus_error_free (&tmp_error);
358           dbus_free (systemd_service);
359           systemd_service = NULL;
360         }
361     }
362
363   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
364
365   entry = _dbus_hash_table_lookup_string (s_dir->entries,
366                                           _dbus_string_get_const_data (filename));
367
368   if (entry == NULL) /* New file */
369     {
370       /* FIXME we need a better-defined algorithm for which service file to
371        * pick than "whichever one is first in the directory listing"
372        */
373       if (_dbus_hash_table_lookup_string (activation->entries, name))
374         {
375           dbus_set_error (error, DBUS_ERROR_FAILED,
376                           "Service %s already exists in activation entry list\n", name);
377           goto out;
378         }
379
380       entry = dbus_new0 (BusActivationEntry, 1);
381       if (entry == NULL)
382         {
383           BUS_SET_OOM (error);
384           goto out;
385         }
386
387       entry->name = name;
388       entry->exec = exec;
389       entry->user = user;
390       entry->systemd_service = systemd_service;
391       entry->refcount = 1;
392
393       /* ownership has been transferred to entry, do not free separately */
394       name = NULL;
395       exec = NULL;
396       user = NULL;
397       systemd_service = NULL;
398
399       entry->s_dir = s_dir;
400       entry->filename = _dbus_strdup (_dbus_string_get_const_data (filename));
401       if (!entry->filename)
402         {
403           BUS_SET_OOM (error);
404           goto out;
405         }
406
407       if (!_dbus_hash_table_insert_string (activation->entries, entry->name, bus_activation_entry_ref (entry)))
408         {
409           BUS_SET_OOM (error);
410           goto out;
411         }
412
413       if (!_dbus_hash_table_insert_string (s_dir->entries, entry->filename, bus_activation_entry_ref (entry)))
414         {
415           /* Revert the insertion in the entries table */
416           _dbus_hash_table_remove_string (activation->entries, entry->name);
417           BUS_SET_OOM (error);
418           goto out;
419         }
420
421       _dbus_verbose ("Added \"%s\" to list of services\n", entry->name);
422     }
423   else /* Just update the entry */
424     {
425       bus_activation_entry_ref (entry);
426       _dbus_hash_table_remove_string (activation->entries, entry->name);
427
428       if (_dbus_hash_table_lookup_string (activation->entries, name))
429         {
430           _dbus_verbose ("The new service name \"%s\" of service file \"%s\" already in cache, ignoring\n",
431                          name, _dbus_string_get_const_data (&file_path));
432           goto out;
433         }
434
435       /* ownership has been transferred to entry, do not free separately */
436       dbus_free (entry->name);
437       entry->name = name;
438       name = NULL;
439
440       dbus_free (entry->exec);
441       entry->exec = exec;
442       exec = NULL;
443
444       dbus_free (entry->user);
445       entry->user = user;
446       user = NULL;
447
448       dbus_free (entry->systemd_service);
449       entry->systemd_service = systemd_service;
450       systemd_service = NULL;
451
452       if (!_dbus_hash_table_insert_string (activation->entries,
453                                            entry->name, bus_activation_entry_ref(entry)))
454         {
455           BUS_SET_OOM (error);
456           /* Also remove path to entries hash since we want this in sync with
457            * the entries hash table */
458           _dbus_hash_table_remove_string (entry->s_dir->entries,
459                                           entry->filename);
460           bus_activation_entry_unref (entry);
461           return FALSE;
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 FALSE;
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   DBusList      *link;
896   char          *dir;
897
898   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
899
900   activation = dbus_new0 (BusActivation, 1);
901   if (activation == NULL)
902     {
903       BUS_SET_OOM (error);
904       return NULL;
905     }
906
907   activation->refcount = 1;
908   activation->context = context;
909   activation->n_pending_activations = 0;
910
911   if (!bus_activation_reload (activation, address, directories, error))
912     goto failed;
913
914    /* Initialize this hash table once, we don't want to lose pending
915    * activations on reload. */
916   activation->pending_activations = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
917                                                           (DBusFreeFunction)bus_pending_activation_unref);
918
919   if (activation->pending_activations == NULL)
920     {
921       BUS_SET_OOM (error);
922       goto failed;
923     }
924
925   activation->environment = _dbus_hash_table_new (DBUS_HASH_STRING,
926                                                   (DBusFreeFunction) dbus_free,
927                                                   (DBusFreeFunction) dbus_free);
928
929   if (activation->environment == NULL)
930     {
931       BUS_SET_OOM (error);
932       goto failed;
933     }
934
935   if (!populate_environment (activation))
936     {
937       BUS_SET_OOM (error);
938       goto failed;
939     }
940
941   return activation;
942
943  failed:
944   bus_activation_unref (activation);
945   return NULL;
946 }
947
948 BusActivation *
949 bus_activation_ref (BusActivation *activation)
950 {
951   _dbus_assert (activation->refcount > 0);
952
953   activation->refcount += 1;
954
955   return activation;
956 }
957
958 void
959 bus_activation_unref (BusActivation *activation)
960 {
961   _dbus_assert (activation->refcount > 0);
962
963   activation->refcount -= 1;
964
965   if (activation->refcount > 0)
966     return;
967
968   dbus_free (activation->server_address);
969   if (activation->entries)
970     _dbus_hash_table_unref (activation->entries);
971   if (activation->pending_activations)
972     _dbus_hash_table_unref (activation->pending_activations);
973   if (activation->directories)
974     _dbus_hash_table_unref (activation->directories);
975   if (activation->environment)
976     _dbus_hash_table_unref (activation->environment);
977
978   dbus_free (activation);
979 }
980
981 static dbus_bool_t
982 add_bus_environment (BusActivation *activation,
983                      DBusError     *error)
984 {
985   const char *type;
986
987   if (!bus_activation_set_environment_variable (activation,
988                                                 "DBUS_STARTER_ADDRESS",
989                                                 activation->server_address,
990                                                 error))
991     return FALSE;
992
993   type = bus_context_get_type (activation->context);
994   if (type != NULL)
995     {
996       if (!bus_activation_set_environment_variable (activation,
997                                                     "DBUS_STARTER_BUS_TYPE", type,
998                                                     error))
999         return FALSE;
1000
1001       if (strcmp (type, "session") == 0)
1002         {
1003           if (!bus_activation_set_environment_variable (activation,
1004                                                         "DBUS_SESSION_BUS_ADDRESS",
1005                                                         activation->server_address,
1006                                                         error))
1007             return FALSE;
1008         }
1009       else if (strcmp (type, "system") == 0)
1010         {
1011           if (!bus_activation_set_environment_variable (activation,
1012                                                         "DBUS_SYSTEM_BUS_ADDRESS",
1013                                                         activation->server_address,
1014                                                         error))
1015             return FALSE;
1016         }
1017     }
1018
1019   return TRUE;
1020 }
1021
1022 typedef struct
1023 {
1024   BusPendingActivation *pending_activation;
1025   DBusPreallocatedHash *hash_entry;
1026 } RestorePendingData;
1027
1028 static void
1029 restore_pending (void *data)
1030 {
1031   RestorePendingData *d = data;
1032
1033   _dbus_assert (d->pending_activation != NULL);
1034   _dbus_assert (d->hash_entry != NULL);
1035
1036   _dbus_verbose ("Restoring pending activation for service %s, has timeout = %d\n",
1037                  d->pending_activation->service_name,
1038                  d->pending_activation->timeout_added);
1039
1040   _dbus_hash_table_insert_string_preallocated (d->pending_activation->activation->pending_activations,
1041                                                d->hash_entry,
1042                                                d->pending_activation->service_name, d->pending_activation);
1043
1044   bus_pending_activation_ref (d->pending_activation);
1045
1046   d->hash_entry = NULL;
1047 }
1048
1049 static void
1050 free_pending_restore_data (void *data)
1051 {
1052   RestorePendingData *d = data;
1053
1054   if (d->hash_entry)
1055     _dbus_hash_table_free_preallocated_entry (d->pending_activation->activation->pending_activations,
1056                                               d->hash_entry);
1057
1058   bus_pending_activation_unref (d->pending_activation);
1059
1060   dbus_free (d);
1061 }
1062
1063 static dbus_bool_t
1064 add_restore_pending_to_transaction (BusTransaction       *transaction,
1065                                     BusPendingActivation *pending_activation)
1066 {
1067   RestorePendingData *d;
1068
1069   d = dbus_new (RestorePendingData, 1);
1070   if (d == NULL)
1071     return FALSE;
1072
1073   d->pending_activation = pending_activation;
1074   d->hash_entry = _dbus_hash_table_preallocate_entry (d->pending_activation->activation->pending_activations);
1075
1076   bus_pending_activation_ref (d->pending_activation);
1077
1078   if (d->hash_entry == NULL ||
1079       !bus_transaction_add_cancel_hook (transaction, restore_pending, d,
1080                                         free_pending_restore_data))
1081     {
1082       free_pending_restore_data (d);
1083       return FALSE;
1084     }
1085
1086   _dbus_verbose ("Saved pending activation to be restored if the transaction fails\n");
1087
1088   return TRUE;
1089 }
1090
1091 dbus_bool_t
1092 bus_activation_service_created (BusActivation  *activation,
1093                                 const char     *service_name,
1094                                 BusTransaction *transaction,
1095                                 DBusError      *error)
1096 {
1097   BusPendingActivation *pending_activation;
1098   DBusMessage *message;
1099   DBusList *link;
1100
1101   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1102
1103   /* Check if it's a pending activation */
1104   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1105
1106   if (!pending_activation)
1107     return TRUE;
1108
1109   bus_context_log (activation->context,
1110                    DBUS_SYSTEM_LOG_INFO, "Successfully activated service '%s'",
1111                    service_name);
1112
1113   link = _dbus_list_get_first_link (&pending_activation->entries);
1114   while (link != NULL)
1115     {
1116       BusPendingActivationEntry *entry = link->data;
1117       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1118
1119       if (dbus_connection_get_is_connected (entry->connection))
1120         {
1121           /* Only send activation replies to regular activation requests. */
1122           if (!entry->auto_activation)
1123             {
1124               dbus_uint32_t result;
1125
1126               message = dbus_message_new_method_return (entry->activation_message);
1127               if (!message)
1128                 {
1129                   BUS_SET_OOM (error);
1130                   goto error;
1131                 }
1132
1133               result = DBUS_START_REPLY_SUCCESS;
1134
1135               if (!dbus_message_append_args (message,
1136                                              DBUS_TYPE_UINT32, &result,
1137                                              DBUS_TYPE_INVALID))
1138                 {
1139                   dbus_message_unref (message);
1140                   BUS_SET_OOM (error);
1141                   goto error;
1142                 }
1143
1144               if (!bus_transaction_send_from_driver (transaction, entry->connection, message))
1145                 {
1146                   dbus_message_unref (message);
1147                   BUS_SET_OOM (error);
1148                   goto error;
1149                 }
1150
1151               dbus_message_unref (message);
1152             }
1153         }
1154
1155       link = next;
1156     }
1157
1158   return TRUE;
1159
1160  error:
1161   return FALSE;
1162 }
1163
1164 dbus_bool_t
1165 bus_activation_send_pending_auto_activation_messages (BusActivation  *activation,
1166                                                       BusService     *service,
1167                                                       BusTransaction *transaction,
1168                                                       DBusError      *error)
1169 {
1170   BusPendingActivation *pending_activation;
1171   DBusList *link;
1172
1173   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1174
1175   /* Check if it's a pending activation */
1176   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations,
1177                                                        bus_service_get_name (service));
1178
1179   if (!pending_activation)
1180     return TRUE;
1181
1182   link = _dbus_list_get_first_link (&pending_activation->entries);
1183   while (link != NULL)
1184     {
1185       BusPendingActivationEntry *entry = link->data;
1186       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1187
1188       if (entry->auto_activation && dbus_connection_get_is_connected (entry->connection))
1189         {
1190           DBusConnection *addressed_recipient;
1191
1192           addressed_recipient = bus_service_get_primary_owners_connection (service);
1193
1194           /* Resume dispatching where we left off in bus_dispatch() */
1195           if (!bus_dispatch_matches (transaction,
1196                                      entry->connection,
1197                                      addressed_recipient,
1198                                      entry->activation_message, error))
1199             goto error;
1200         }
1201
1202       link = next;
1203     }
1204
1205   if (!add_restore_pending_to_transaction (transaction, pending_activation))
1206     {
1207       _dbus_verbose ("Could not add cancel hook to transaction to revert removing pending activation\n");
1208       BUS_SET_OOM (error);
1209       goto error;
1210     }
1211
1212   _dbus_hash_table_remove_string (activation->pending_activations, bus_service_get_name (service));
1213
1214   return TRUE;
1215
1216  error:
1217   return FALSE;
1218 }
1219
1220 /**
1221  * FIXME @todo the error messages here would ideally be preallocated
1222  * so we don't need to allocate memory to send them.
1223  * Using the usual tactic, prealloc an OOM message, then
1224  * if we can't alloc the real error send the OOM error instead.
1225  */
1226 static dbus_bool_t
1227 try_send_activation_failure (BusPendingActivation *pending_activation,
1228                              const DBusError      *how)
1229 {
1230   BusActivation *activation;
1231   DBusList *link;
1232   BusTransaction *transaction;
1233
1234   activation = pending_activation->activation;
1235
1236   transaction = bus_transaction_new (activation->context);
1237   if (transaction == NULL)
1238     return FALSE;
1239
1240   link = _dbus_list_get_first_link (&pending_activation->entries);
1241   while (link != NULL)
1242     {
1243       BusPendingActivationEntry *entry = link->data;
1244       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1245
1246       if (dbus_connection_get_is_connected (entry->connection))
1247         {
1248           if (!bus_transaction_send_error_reply (transaction,
1249                                                  entry->connection,
1250                                                  how,
1251                                                  entry->activation_message))
1252             goto error;
1253         }
1254
1255       link = next;
1256     }
1257
1258   bus_transaction_execute_and_free (transaction);
1259
1260   return TRUE;
1261
1262  error:
1263   if (transaction)
1264     bus_transaction_cancel_and_free (transaction);
1265   return FALSE;
1266 }
1267
1268 /**
1269  * Free the pending activation and send an error message to all the
1270  * connections that were waiting for it.
1271  */
1272 static void
1273 pending_activation_failed (BusPendingActivation *pending_activation,
1274                            const DBusError      *how)
1275 {
1276   /* FIXME use preallocated OOM messages instead of bus_wait_for_memory() */
1277   while (!try_send_activation_failure (pending_activation, how))
1278     _dbus_wait_for_memory ();
1279
1280   /* Destroy this pending activation */
1281   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1282                                   pending_activation->service_name);
1283 }
1284
1285 /**
1286  * Depending on the exit code of the helper, set the error accordingly
1287  */
1288 static void
1289 handle_servicehelper_exit_error (int        exit_code,
1290                                  DBusError *error)
1291 {
1292   switch (exit_code)
1293     {
1294     case BUS_SPAWN_EXIT_CODE_NO_MEMORY:
1295       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1296                       "Launcher could not run (out of memory)");
1297       break;
1298     case BUS_SPAWN_EXIT_CODE_SETUP_FAILED:
1299       dbus_set_error (error, DBUS_ERROR_SPAWN_SETUP_FAILED,
1300                       "Failed to setup environment correctly");
1301       break;
1302     case BUS_SPAWN_EXIT_CODE_NAME_INVALID:
1303       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_INVALID,
1304                       "Bus name is not valid or missing");
1305       break;
1306     case BUS_SPAWN_EXIT_CODE_SERVICE_NOT_FOUND:
1307       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND,
1308                       "Bus name not found in system service directory");
1309       break;
1310     case BUS_SPAWN_EXIT_CODE_PERMISSIONS_INVALID:
1311       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1312                       "The permission of the setuid helper is not correct");
1313       break;
1314     case BUS_SPAWN_EXIT_CODE_FILE_INVALID:
1315       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1316                       "The service file is incorrect or does not have all required attributes");
1317       break;
1318     case BUS_SPAWN_EXIT_CODE_EXEC_FAILED:
1319       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
1320                       "Cannot launch daemon, file not found or permissions invalid");
1321       break;
1322     case BUS_SPAWN_EXIT_CODE_INVALID_ARGS:
1323       dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1324                       "Invalid arguments to command line");
1325       break;
1326     case BUS_SPAWN_EXIT_CODE_CHILD_SIGNALED:
1327       dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
1328                       "Launched child was signaled, it probably crashed");
1329       break;
1330     default:
1331       dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
1332                       "Launch helper exited with unknown return code %i", exit_code);
1333       break;
1334     }
1335 }
1336
1337 static dbus_bool_t
1338 babysitter_watch_callback (DBusWatch     *watch,
1339                            unsigned int   condition,
1340                            void          *data)
1341 {
1342   BusPendingActivation *pending_activation = data;
1343   dbus_bool_t retval;
1344   DBusBabysitter *babysitter;
1345   dbus_bool_t uses_servicehelper;
1346
1347   babysitter = pending_activation->babysitter;
1348
1349   _dbus_babysitter_ref (babysitter);
1350
1351   retval = dbus_watch_handle (watch, condition);
1352
1353   /* There are two major cases here; are we the system bus or the session?  Here this
1354    * is distinguished by whether or not we use a setuid helper launcher.  With the launch helper,
1355    * some process exit codes are meaningful, processed by handle_servicehelper_exit_error.
1356    *
1357    * In both cases though, just ignore when a process exits with status 0; it's possible for
1358    * a program to (misguidedly) "daemonize", and that appears to us as an exit.  This closes a race
1359    * condition between this code and the child process claiming the bus name.
1360    */
1361   uses_servicehelper = bus_context_get_servicehelper (pending_activation->activation->context) != NULL;
1362
1363   /* FIXME this is broken in the same way that
1364    * connection watches used to be; there should be
1365    * a separate callback for status change, instead
1366    * of doing "if we handled a watch status might
1367    * have changed"
1368    *
1369    * Fixing this lets us move dbus_watch_handle
1370    * calls into dbus-mainloop.c
1371    */
1372   if (_dbus_babysitter_get_child_exited (babysitter))
1373     {
1374       DBusError error;
1375       DBusHashIter iter;
1376       dbus_bool_t activation_failed;
1377       int exit_code = 0;
1378
1379       dbus_error_init (&error);
1380
1381       _dbus_babysitter_set_child_exit_error (babysitter, &error);
1382
1383       /* Explicitly check for SPAWN_CHILD_EXITED to avoid overwriting an
1384        * exec error */
1385       if (dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)
1386           && _dbus_babysitter_get_child_exit_status (babysitter, &exit_code))
1387         {
1388           activation_failed = exit_code != 0;
1389
1390           dbus_error_free(&error);
1391
1392           if (activation_failed)
1393             {
1394               if (uses_servicehelper)
1395                 handle_servicehelper_exit_error (exit_code, &error);
1396               else
1397                 _dbus_babysitter_set_child_exit_error (babysitter, &error);
1398             }
1399         }
1400       else
1401         {
1402           activation_failed = TRUE;
1403         }
1404
1405       if (activation_failed)
1406         {
1407           bus_context_log (pending_activation->activation->context,
1408                            DBUS_SYSTEM_LOG_INFO, "Activated service '%s' failed: %s",
1409                            pending_activation->service_name,
1410                            error.message);
1411
1412           /* Destroy all pending activations with the same exec */
1413           _dbus_hash_iter_init (pending_activation->activation->pending_activations,
1414                                 &iter);
1415           while (_dbus_hash_iter_next (&iter))
1416             {
1417               BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1418
1419               if (p != pending_activation && strcmp (p->exec, pending_activation->exec) == 0)
1420                 pending_activation_failed (p, &error);
1421             }
1422
1423           /* Destroys the pending activation */
1424           pending_activation_failed (pending_activation, &error);
1425
1426           dbus_error_free (&error);
1427         }
1428     }
1429
1430   _dbus_babysitter_unref (babysitter);
1431
1432   return retval;
1433 }
1434
1435 static dbus_bool_t
1436 add_babysitter_watch (DBusWatch      *watch,
1437                       void           *data)
1438 {
1439   BusPendingActivation *pending_activation = data;
1440
1441   return _dbus_loop_add_watch (bus_context_get_loop (pending_activation->activation->context),
1442                                watch, babysitter_watch_callback, pending_activation,
1443                                NULL);
1444 }
1445
1446 static void
1447 remove_babysitter_watch (DBusWatch      *watch,
1448                          void           *data)
1449 {
1450   BusPendingActivation *pending_activation = data;
1451
1452   _dbus_loop_remove_watch (bus_context_get_loop (pending_activation->activation->context),
1453                            watch, babysitter_watch_callback, pending_activation);
1454 }
1455
1456 static dbus_bool_t
1457 pending_activation_timed_out (void *data)
1458 {
1459   BusPendingActivation *pending_activation = data;
1460   DBusError error;
1461
1462   /* Kill the spawned process, since it sucks
1463    * (not sure this is what we want to do, but
1464    * may as well try it for now)
1465    */
1466   if (pending_activation->babysitter)
1467     _dbus_babysitter_kill_child (pending_activation->babysitter);
1468
1469   dbus_error_init (&error);
1470
1471   dbus_set_error (&error, DBUS_ERROR_TIMED_OUT,
1472                   "Activation of %s timed out",
1473                   pending_activation->service_name);
1474   bus_context_log (pending_activation->activation->context,
1475                    DBUS_SYSTEM_LOG_INFO,
1476                    "Failed to activate service '%s': timed out",
1477                    pending_activation->service_name);
1478
1479   pending_activation_failed (pending_activation, &error);
1480
1481   dbus_error_free (&error);
1482
1483   return TRUE;
1484 }
1485
1486 static void
1487 cancel_pending (void *data)
1488 {
1489   BusPendingActivation *pending_activation = data;
1490
1491   _dbus_verbose ("Canceling pending activation of %s\n",
1492                  pending_activation->service_name);
1493
1494   if (pending_activation->babysitter)
1495     _dbus_babysitter_kill_child (pending_activation->babysitter);
1496
1497   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1498                                   pending_activation->service_name);
1499 }
1500
1501 static void
1502 free_pending_cancel_data (void *data)
1503 {
1504   BusPendingActivation *pending_activation = data;
1505
1506   bus_pending_activation_unref (pending_activation);
1507 }
1508
1509 static dbus_bool_t
1510 add_cancel_pending_to_transaction (BusTransaction       *transaction,
1511                                    BusPendingActivation *pending_activation)
1512 {
1513   if (!bus_transaction_add_cancel_hook (transaction, cancel_pending,
1514                                         pending_activation,
1515                                         free_pending_cancel_data))
1516     return FALSE;
1517
1518   bus_pending_activation_ref (pending_activation);
1519
1520   _dbus_verbose ("Saved pending activation to be canceled if the transaction fails\n");
1521
1522   return TRUE;
1523 }
1524
1525 static dbus_bool_t
1526 update_service_cache (BusActivation *activation, DBusError *error)
1527 {
1528   DBusHashIter iter;
1529
1530   _dbus_hash_iter_init (activation->directories, &iter);
1531   while (_dbus_hash_iter_next (&iter))
1532     {
1533       DBusError tmp_error;
1534       BusServiceDirectory *s_dir;
1535
1536       s_dir = _dbus_hash_iter_get_value (&iter);
1537
1538       dbus_error_init (&tmp_error);
1539       if (!update_directory (activation, s_dir, &tmp_error))
1540         {
1541           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
1542             {
1543               dbus_move_error (&tmp_error, error);
1544               return FALSE;
1545             }
1546
1547           dbus_error_free (&tmp_error);
1548           continue;
1549         }
1550     }
1551
1552   return TRUE;
1553 }
1554
1555 static BusActivationEntry *
1556 activation_find_entry (BusActivation *activation,
1557                        const char    *service_name,
1558                        DBusError     *error)
1559 {
1560   BusActivationEntry *entry;
1561
1562   entry = _dbus_hash_table_lookup_string (activation->entries, service_name);
1563   if (!entry)
1564     {
1565       if (!update_service_cache (activation, error))
1566         return NULL;
1567
1568       entry = _dbus_hash_table_lookup_string (activation->entries,
1569                                               service_name);
1570     }
1571   else
1572     {
1573       BusActivationEntry *updated_entry;
1574
1575       if (!check_service_file (activation, entry, &updated_entry, error))
1576         return NULL;
1577
1578       entry = updated_entry;
1579     }
1580
1581   if (!entry)
1582     {
1583       dbus_set_error (error, DBUS_ERROR_SERVICE_UNKNOWN,
1584                       "The name %s was not provided by any .service files",
1585                       service_name);
1586       return NULL;
1587     }
1588
1589   return entry;
1590 }
1591
1592 static char **
1593 bus_activation_get_environment (BusActivation *activation)
1594 {
1595   char **environment;
1596   int i, length;
1597   DBusString entry;
1598   DBusHashIter iter;
1599
1600   length = _dbus_hash_table_get_n_entries (activation->environment);
1601
1602   environment = dbus_new0 (char *, length + 1);
1603
1604   if (environment == NULL)
1605     return NULL;
1606
1607   i = 0;
1608   _dbus_hash_iter_init (activation->environment, &iter);
1609
1610   if (!_dbus_string_init (&entry))
1611     {
1612       dbus_free_string_array (environment);
1613       return NULL;
1614     }
1615
1616   while (_dbus_hash_iter_next (&iter))
1617     {
1618       const char *key, *value;
1619
1620       key = (const char *) _dbus_hash_iter_get_string_key (&iter);
1621       value = (const char *) _dbus_hash_iter_get_value (&iter);
1622
1623       if (!_dbus_string_append_printf (&entry, "%s=%s", key, value))
1624         break;
1625
1626       if (!_dbus_string_steal_data (&entry, environment + i))
1627         break;
1628       i++;
1629     }
1630
1631   _dbus_string_free (&entry);
1632
1633   if (i != length)
1634     {
1635       dbus_free_string_array (environment);
1636       environment = NULL;
1637     }
1638
1639   return environment;
1640 }
1641
1642 dbus_bool_t
1643 bus_activation_set_environment_variable (BusActivation     *activation,
1644                                          const char        *key,
1645                                          const char        *value,
1646                                          DBusError         *error)
1647 {
1648   char        *hash_key;
1649   char        *hash_value;
1650   dbus_bool_t  retval;
1651
1652   retval = FALSE;
1653   hash_key = NULL;
1654   hash_value = NULL;
1655   hash_key = _dbus_strdup (key);
1656
1657   if (hash_key == NULL)
1658     goto out;
1659
1660   hash_value = _dbus_strdup (value);
1661
1662   if (hash_value == NULL)
1663     goto out;
1664
1665   if (!_dbus_hash_table_insert_string (activation->environment,
1666                                        hash_key, hash_value))
1667     goto out;
1668
1669   retval = TRUE;
1670 out:
1671   if (retval == FALSE)
1672     {
1673       dbus_free (hash_key);
1674       dbus_free (hash_value);
1675       BUS_SET_OOM (error);
1676     }
1677
1678   return retval;
1679 }
1680
1681 dbus_bool_t
1682 bus_activation_activate_service (BusActivation  *activation,
1683                                  DBusConnection *connection,
1684                                  BusTransaction *transaction,
1685                                  dbus_bool_t     auto_activation,
1686                                  DBusMessage    *activation_message,
1687                                  const char     *service_name,
1688                                  DBusError      *error)
1689 {
1690   DBusError tmp_error;
1691   BusActivationEntry *entry;
1692   BusPendingActivation *pending_activation;
1693   BusPendingActivationEntry *pending_activation_entry;
1694   DBusMessage *message;
1695   DBusString service_str;
1696   const char *servicehelper;
1697   char **argv;
1698   char **envp = NULL;
1699   int argc;
1700   dbus_bool_t retval;
1701   DBusHashIter iter;
1702   dbus_bool_t was_pending_activation;
1703   DBusString command;
1704
1705   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1706
1707   if (activation->n_pending_activations >=
1708       bus_context_get_max_pending_activations (activation->context))
1709     {
1710       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1711                       "The maximum number of pending activations has been reached, activation of %s failed",
1712                       service_name);
1713       return FALSE;
1714     }
1715
1716   entry = activation_find_entry (activation, service_name, error);
1717   if (!entry)
1718     return FALSE;
1719
1720   /* Bypass the registry lookup if we're auto-activating, bus_dispatch would not
1721    * call us if the service is already active.
1722    */
1723   if (!auto_activation)
1724     {
1725       /* Check if the service is active */
1726       _dbus_string_init_const (&service_str, service_name);
1727       if (bus_registry_lookup (bus_context_get_registry (activation->context), &service_str) != NULL)
1728         {
1729           dbus_uint32_t result;
1730
1731           _dbus_verbose ("Service \"%s\" is already active\n", service_name);
1732
1733           message = dbus_message_new_method_return (activation_message);
1734
1735           if (!message)
1736             {
1737               _dbus_verbose ("No memory to create reply to activate message\n");
1738               BUS_SET_OOM (error);
1739               return FALSE;
1740             }
1741
1742           result = DBUS_START_REPLY_ALREADY_RUNNING;
1743
1744           if (!dbus_message_append_args (message,
1745                                          DBUS_TYPE_UINT32, &result,
1746                                          DBUS_TYPE_INVALID))
1747             {
1748               _dbus_verbose ("No memory to set args of reply to activate message\n");
1749               BUS_SET_OOM (error);
1750               dbus_message_unref (message);
1751               return FALSE;
1752             }
1753
1754           retval = bus_transaction_send_from_driver (transaction, connection, message);
1755           dbus_message_unref (message);
1756           if (!retval)
1757             {
1758               _dbus_verbose ("Failed to send reply\n");
1759               BUS_SET_OOM (error);
1760             }
1761
1762           return retval;
1763         }
1764     }
1765
1766   pending_activation_entry = dbus_new0 (BusPendingActivationEntry, 1);
1767   if (!pending_activation_entry)
1768     {
1769       _dbus_verbose ("Failed to create pending activation entry\n");
1770       BUS_SET_OOM (error);
1771       return FALSE;
1772     }
1773
1774   pending_activation_entry->auto_activation = auto_activation;
1775
1776   pending_activation_entry->activation_message = activation_message;
1777   dbus_message_ref (activation_message);
1778   pending_activation_entry->connection = connection;
1779   dbus_connection_ref (connection);
1780
1781   /* Check if the service is being activated */
1782   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1783   was_pending_activation = (pending_activation != NULL);
1784   if (was_pending_activation)
1785     {
1786       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1787         {
1788           _dbus_verbose ("Failed to append a new entry to pending activation\n");
1789
1790           BUS_SET_OOM (error);
1791           bus_pending_activation_entry_free (pending_activation_entry);
1792           return FALSE;
1793         }
1794
1795       pending_activation->n_entries += 1;
1796       pending_activation->activation->n_pending_activations += 1;
1797     }
1798   else
1799     {
1800       pending_activation = dbus_new0 (BusPendingActivation, 1);
1801       if (!pending_activation)
1802         {
1803           _dbus_verbose ("Failed to create pending activation\n");
1804
1805           BUS_SET_OOM (error);
1806           bus_pending_activation_entry_free (pending_activation_entry);
1807           return FALSE;
1808         }
1809
1810       pending_activation->activation = activation;
1811       pending_activation->refcount = 1;
1812
1813       pending_activation->service_name = _dbus_strdup (service_name);
1814       if (!pending_activation->service_name)
1815         {
1816           _dbus_verbose ("Failed to copy service name for pending activation\n");
1817
1818           BUS_SET_OOM (error);
1819           bus_pending_activation_unref (pending_activation);
1820           bus_pending_activation_entry_free (pending_activation_entry);
1821           return FALSE;
1822         }
1823
1824       pending_activation->exec = _dbus_strdup (entry->exec);
1825       if (!pending_activation->exec)
1826         {
1827           _dbus_verbose ("Failed to copy service exec for pending activation\n");
1828           BUS_SET_OOM (error);
1829           bus_pending_activation_unref (pending_activation);
1830           bus_pending_activation_entry_free (pending_activation_entry);
1831           return FALSE;
1832         }
1833
1834       if (entry->systemd_service)
1835         {
1836           pending_activation->systemd_service = _dbus_strdup (entry->systemd_service);
1837           if (!pending_activation->systemd_service)
1838             {
1839               _dbus_verbose ("Failed to copy systemd service for pending activation\n");
1840               BUS_SET_OOM (error);
1841               bus_pending_activation_unref (pending_activation);
1842               bus_pending_activation_entry_free (pending_activation_entry);
1843               return FALSE;
1844             }
1845         }
1846
1847       pending_activation->timeout =
1848         _dbus_timeout_new (bus_context_get_activation_timeout (activation->context),
1849                            pending_activation_timed_out,
1850                            pending_activation,
1851                            NULL);
1852       if (!pending_activation->timeout)
1853         {
1854           _dbus_verbose ("Failed to create timeout for pending activation\n");
1855
1856           BUS_SET_OOM (error);
1857           bus_pending_activation_unref (pending_activation);
1858           bus_pending_activation_entry_free (pending_activation_entry);
1859           return FALSE;
1860         }
1861
1862       if (!_dbus_loop_add_timeout (bus_context_get_loop (activation->context),
1863                                    pending_activation->timeout,
1864                                    handle_timeout_callback,
1865                                    pending_activation,
1866                                    NULL))
1867         {
1868           _dbus_verbose ("Failed to add timeout for pending activation\n");
1869
1870           BUS_SET_OOM (error);
1871           bus_pending_activation_unref (pending_activation);
1872           bus_pending_activation_entry_free (pending_activation_entry);
1873           return FALSE;
1874         }
1875
1876       pending_activation->timeout_added = TRUE;
1877
1878       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1879         {
1880           _dbus_verbose ("Failed to add entry to just-created pending activation\n");
1881
1882           BUS_SET_OOM (error);
1883           bus_pending_activation_unref (pending_activation);
1884           bus_pending_activation_entry_free (pending_activation_entry);
1885           return FALSE;
1886         }
1887
1888       pending_activation->n_entries += 1;
1889       pending_activation->activation->n_pending_activations += 1;
1890
1891       if (!_dbus_hash_table_insert_string (activation->pending_activations,
1892                                            pending_activation->service_name,
1893                                            pending_activation))
1894         {
1895           _dbus_verbose ("Failed to put pending activation in hash table\n");
1896
1897           BUS_SET_OOM (error);
1898           bus_pending_activation_unref (pending_activation);
1899           return FALSE;
1900         }
1901     }
1902
1903   if (!add_cancel_pending_to_transaction (transaction, pending_activation))
1904     {
1905       _dbus_verbose ("Failed to add pending activation cancel hook to transaction\n");
1906       BUS_SET_OOM (error);
1907       _dbus_hash_table_remove_string (activation->pending_activations,
1908                                       pending_activation->service_name);
1909
1910       return FALSE;
1911     }
1912
1913   if (was_pending_activation)
1914     return TRUE;
1915
1916   if (bus_context_get_systemd_activation (activation->context))
1917     {
1918       if (strcmp (service_name, "org.freedesktop.systemd1") == 0)
1919           /* systemd itself is missing apparently. That can happen
1920              only during early startup. Let's just wait until systemd
1921              connects to us and do nothing. */
1922         return TRUE;
1923
1924       if (entry->systemd_service)
1925         {
1926           BusTransaction *activation_transaction;
1927           DBusString service_string;
1928           BusService *service;
1929           BusRegistry *registry;
1930
1931           /* OK, we have a systemd service configured for this entry,
1932              hence let's enqueue an activation request message. This
1933              is implemented as a directed signal, not a method call,
1934              for three reasons: 1) we don't expect a response on
1935              success, where we just expect a name appearing on the
1936              bus; 2) at this time the systemd service might not yet
1937              have connected, so we wouldn't know the message serial at
1938              this point to set up a pending call; 3) it is ugly if the
1939              bus suddenly becomes the caller of a remote method. */
1940
1941           message = dbus_message_new_signal (DBUS_PATH_DBUS,
1942                                              "org.freedesktop.systemd1.Activator",
1943                                              "ActivationRequest");
1944           if (!message)
1945             {
1946               _dbus_verbose ("No memory to create activation message\n");
1947               BUS_SET_OOM (error);
1948               return FALSE;
1949             }
1950
1951           if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS) ||
1952               !dbus_message_set_destination (message, "org.freedesktop.systemd1") ||
1953               !dbus_message_append_args (message,
1954                                          DBUS_TYPE_STRING, &entry->systemd_service,
1955                                          DBUS_TYPE_INVALID))
1956             {
1957               _dbus_verbose ("No memory to set args of activation message\n");
1958               dbus_message_unref (message);
1959               BUS_SET_OOM (error);
1960               return FALSE;
1961             }
1962
1963           /* Create our transaction */
1964           activation_transaction = bus_transaction_new (activation->context);
1965           if (activation_transaction == NULL)
1966             {
1967               _dbus_verbose ("No memory to create activation transaction\n");
1968               dbus_message_unref (message);
1969               BUS_SET_OOM (error);
1970               return FALSE;
1971             }
1972
1973           /* Check whether systemd is already connected */
1974           registry = bus_connection_get_registry (connection);
1975           _dbus_string_init_const (&service_string, "org.freedesktop.systemd1");
1976           service = bus_registry_lookup (registry, &service_string);
1977
1978           if (service != NULL)
1979             {
1980               bus_context_log (activation->context,
1981                                DBUS_SYSTEM_LOG_INFO, "Activating via systemd: service name='%s' unit='%s'",
1982                                service_name,
1983                                entry->systemd_service);
1984               /* Wonderful, systemd is connected, let's just send the msg */
1985               retval = bus_dispatch_matches (activation_transaction, NULL, bus_service_get_primary_owners_connection (service),
1986                                              message, error);
1987             }
1988           else
1989             {
1990               bus_context_log (activation->context,
1991                                DBUS_SYSTEM_LOG_INFO, "Activating systemd to hand-off: service name='%s' unit='%s'",
1992                                service_name,
1993                                entry->systemd_service);
1994               /* systemd is not around, let's "activate" it. */
1995               retval = bus_activation_activate_service (activation, connection, activation_transaction, TRUE,
1996                                                         message, "org.freedesktop.systemd1", error);
1997             }
1998
1999           dbus_message_unref (message);
2000
2001           if (!retval)
2002             {
2003               bus_context_log (activation->context,
2004                                DBUS_SYSTEM_LOG_INFO, "Failed to activate via systemd: service name='%s' unit='%s'",
2005                                service_name,
2006                                entry->systemd_service);
2007               _DBUS_ASSERT_ERROR_IS_SET (error);
2008               _dbus_verbose ("failed to send activation message: %s\n", error->name);
2009               bus_transaction_cancel_and_free (activation_transaction);
2010               return FALSE;
2011             }
2012
2013           bus_transaction_execute_and_free (activation_transaction);
2014           return TRUE;
2015         }
2016
2017       /* OK, we have no configured systemd service, hence let's
2018          proceed with traditional activation. */
2019     }
2020
2021   /* use command as system and session different */
2022   if (!_dbus_string_init (&command))
2023     {
2024       BUS_SET_OOM (error);
2025       return FALSE;
2026     }
2027
2028   /* does the bus use a helper? */
2029   servicehelper = bus_context_get_servicehelper (activation->context);
2030   if (servicehelper != NULL)
2031     {
2032       if (entry->user == NULL)
2033         {
2034           _dbus_string_free (&command);
2035           dbus_set_error (error, DBUS_ERROR_SPAWN_FILE_INVALID,
2036                           "Cannot do system-bus activation with no user\n");
2037           return FALSE;
2038         }
2039
2040       /* join the helper path and the service name */
2041       if (!_dbus_string_append (&command, servicehelper))
2042         {
2043           _dbus_string_free (&command);
2044           BUS_SET_OOM (error);
2045           return FALSE;
2046         }
2047       if (!_dbus_string_append (&command, " "))
2048         {
2049           _dbus_string_free (&command);
2050           BUS_SET_OOM (error);
2051           return FALSE;
2052         }
2053       if (!_dbus_string_append (&command, service_name))
2054         {
2055           _dbus_string_free (&command);
2056           BUS_SET_OOM (error);
2057           return FALSE;
2058         }
2059     }
2060   else
2061     {
2062       /* the bus does not use a helper, so we can append arguments with the exec line */
2063       if (!_dbus_string_append (&command, entry->exec))
2064         {
2065           _dbus_string_free (&command);
2066           BUS_SET_OOM (error);
2067           return FALSE;
2068         }
2069     }
2070
2071   /* convert command into arguments */
2072   if (!_dbus_shell_parse_argv (_dbus_string_get_const_data (&command), &argc, &argv, error))
2073     {
2074       _dbus_verbose ("Failed to parse command line: %s\n", entry->exec);
2075       _DBUS_ASSERT_ERROR_IS_SET (error);
2076
2077       _dbus_hash_table_remove_string (activation->pending_activations,
2078                                       pending_activation->service_name);
2079
2080       _dbus_string_free (&command);
2081       return FALSE;
2082     }
2083   _dbus_string_free (&command);
2084
2085   if (!add_bus_environment (activation, error))
2086     {
2087       _DBUS_ASSERT_ERROR_IS_SET (error);
2088       dbus_free_string_array (argv);
2089       return FALSE;
2090     }
2091
2092   envp = bus_activation_get_environment (activation);
2093
2094   if (envp == NULL)
2095     {
2096       BUS_SET_OOM (error);
2097       dbus_free_string_array (argv);
2098       return FALSE;
2099     }
2100
2101   _dbus_verbose ("Spawning %s ...\n", argv[0]);
2102   if (servicehelper != NULL)
2103     bus_context_log (activation->context,
2104                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s' (using servicehelper)",
2105                      service_name);
2106   else
2107     bus_context_log (activation->context,
2108                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s'",
2109                      service_name);
2110
2111   dbus_error_init (&tmp_error);
2112
2113   if (!_dbus_spawn_async_with_babysitter (&pending_activation->babysitter, argv,
2114                                           envp,
2115                                           NULL, activation,
2116                                           &tmp_error))
2117     {
2118       _dbus_verbose ("Failed to spawn child\n");
2119       bus_context_log (activation->context,
2120                        DBUS_SYSTEM_LOG_INFO, "Failed to activate service %s: %s",
2121                        service_name,
2122                        tmp_error.message);
2123       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
2124       dbus_move_error (&tmp_error, error);
2125       dbus_free_string_array (argv);
2126       dbus_free_string_array (envp);
2127
2128       return FALSE;
2129     }
2130
2131   dbus_free_string_array (argv);
2132   envp = NULL;
2133
2134   _dbus_assert (pending_activation->babysitter != NULL);
2135
2136   if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
2137                                              add_babysitter_watch,
2138                                              remove_babysitter_watch,
2139                                              NULL,
2140                                              pending_activation,
2141                                              NULL))
2142     {
2143       BUS_SET_OOM (error);
2144       _dbus_verbose ("Failed to set babysitter watch functions\n");
2145       return FALSE;
2146     }
2147
2148   return TRUE;
2149 }
2150
2151 dbus_bool_t
2152 bus_activation_list_services (BusActivation *activation,
2153                               char        ***listp,
2154                               int           *array_len)
2155 {
2156   int i, j, len;
2157   char **retval;
2158   DBusHashIter iter;
2159
2160   len = _dbus_hash_table_get_n_entries (activation->entries);
2161   retval = dbus_new (char *, len + 1);
2162
2163   if (retval == NULL)
2164     return FALSE;
2165
2166   _dbus_hash_iter_init (activation->entries, &iter);
2167   i = 0;
2168   while (_dbus_hash_iter_next (&iter))
2169     {
2170       BusActivationEntry *entry = _dbus_hash_iter_get_value (&iter);
2171
2172       retval[i] = _dbus_strdup (entry->name);
2173       if (retval[i] == NULL)
2174         goto error;
2175
2176       i++;
2177     }
2178
2179   retval[i] = NULL;
2180
2181   if (array_len)
2182     *array_len = len;
2183
2184   *listp = retval;
2185   return TRUE;
2186
2187  error:
2188   for (j = 0; j < i; j++)
2189     dbus_free (retval[i]);
2190   dbus_free (retval);
2191
2192   return FALSE;
2193 }
2194
2195 dbus_bool_t
2196 dbus_activation_systemd_failure (BusActivation *activation,
2197                                  DBusMessage   *message)
2198 {
2199   DBusError error;
2200   const char *code, *str, *unit = NULL;
2201
2202   dbus_error_init(&error);
2203
2204   /* This is called whenever the systemd activator sent us a
2205      response. We'll invalidate all pending activations that match the
2206      unit name. */
2207
2208   if (dbus_message_get_args (message, &error,
2209                              DBUS_TYPE_STRING, &unit,
2210                              DBUS_TYPE_STRING, &code,
2211                              DBUS_TYPE_STRING, &str,
2212                              DBUS_TYPE_INVALID))
2213     dbus_set_error(&error, code, str);
2214
2215
2216   if (unit)
2217     {
2218       DBusHashIter iter;
2219
2220       bus_context_log (activation->context,
2221                        DBUS_SYSTEM_LOG_INFO, "Activation via systemd failed for unit '%s': %s",
2222                        unit,
2223                        str);
2224
2225       _dbus_hash_iter_init (activation->pending_activations,
2226                             &iter);
2227
2228       while (_dbus_hash_iter_next (&iter))
2229         {
2230           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
2231
2232           if (p->systemd_service && strcmp (p->systemd_service, unit) == 0)
2233             pending_activation_failed(p, &error);
2234         }
2235     }
2236
2237   dbus_error_free(&error);
2238
2239   return TRUE;
2240 }
2241
2242 #ifdef DBUS_BUILD_TESTS
2243
2244 #include <stdio.h>
2245
2246 #define SERVICE_NAME_1 "MyService1"
2247 #define SERVICE_NAME_2 "MyService2"
2248 #define SERVICE_NAME_3 "MyService3"
2249
2250 #define SERVICE_FILE_1 "service-1.service"
2251 #define SERVICE_FILE_2 "service-2.service"
2252 #define SERVICE_FILE_3 "service-3.service"
2253
2254 static dbus_bool_t
2255 test_create_service_file (DBusString *dir,
2256                           const char *filename,
2257                           const char *name,
2258                           const char *exec)
2259 {
2260   DBusString  file_name, full_path;
2261   FILE        *file;
2262   dbus_bool_t  ret_val;
2263
2264   ret_val = TRUE;
2265   _dbus_string_init_const (&file_name, filename);
2266
2267   if (!_dbus_string_init (&full_path))
2268     return FALSE;
2269
2270   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2271       !_dbus_concat_dir_and_file (&full_path, &file_name))
2272     {
2273       ret_val = FALSE;
2274       goto out;
2275     }
2276
2277   file = fopen (_dbus_string_get_const_data (&full_path), "w");
2278   if (!file)
2279     {
2280       ret_val = FALSE;
2281       goto out;
2282     }
2283
2284   fprintf (file, "[D-BUS Service]\nName=%s\nExec=%s\n", name, exec);
2285   fclose (file);
2286
2287 out:
2288   _dbus_string_free (&full_path);
2289   return ret_val;
2290 }
2291
2292 static dbus_bool_t
2293 test_remove_service_file (DBusString *dir, const char *filename)
2294 {
2295   DBusString  file_name, full_path;
2296   dbus_bool_t ret_val;
2297
2298   ret_val = TRUE;
2299
2300   _dbus_string_init_const (&file_name, filename);
2301
2302   if (!_dbus_string_init (&full_path))
2303     return FALSE;
2304
2305   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2306       !_dbus_concat_dir_and_file (&full_path, &file_name))
2307     {
2308       ret_val = FALSE;
2309       goto out;
2310     }
2311
2312   if (!_dbus_delete_file (&full_path, NULL))
2313     {
2314       ret_val = FALSE;
2315       goto out;
2316     }
2317
2318 out:
2319   _dbus_string_free (&full_path);
2320   return ret_val;
2321 }
2322
2323 static dbus_bool_t
2324 test_remove_directory (DBusString *dir)
2325 {
2326   DBusDirIter *iter;
2327   DBusString   filename, full_path;
2328   dbus_bool_t  ret_val;
2329
2330   ret_val = TRUE;
2331
2332   if (!_dbus_string_init (&filename))
2333     return FALSE;
2334
2335   if (!_dbus_string_init (&full_path))
2336     {
2337       _dbus_string_free (&filename);
2338       return FALSE;
2339     }
2340
2341   iter = _dbus_directory_open (dir, NULL);
2342   if (iter == NULL)
2343     {
2344       ret_val = FALSE;
2345       goto out;
2346     }
2347
2348   while (_dbus_directory_get_next_file (iter, &filename, NULL))
2349     {
2350       if (!test_remove_service_file (dir, _dbus_string_get_const_data (&filename)))
2351         {
2352           ret_val = FALSE;
2353           goto out;
2354         }
2355     }
2356   _dbus_directory_close (iter);
2357
2358   if (!_dbus_delete_directory (dir, NULL))
2359     {
2360       ret_val = FALSE;
2361       goto out;
2362     }
2363
2364 out:
2365   _dbus_string_free (&filename);
2366   _dbus_string_free (&full_path);
2367
2368   return ret_val;
2369 }
2370
2371 static dbus_bool_t
2372 init_service_reload_test (DBusString *dir)
2373 {
2374   DBusStat stat_buf;
2375
2376   if (!_dbus_stat (dir, &stat_buf, NULL))
2377     {
2378       if (!_dbus_create_directory (dir, NULL))
2379         return FALSE;
2380     }
2381   else
2382     {
2383       if (!test_remove_directory (dir))
2384         return FALSE;
2385
2386       if (!_dbus_create_directory (dir, NULL))
2387         return FALSE;
2388     }
2389
2390   /* Create one initial file */
2391   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_1, "exec-1"))
2392     return FALSE;
2393
2394   return TRUE;
2395 }
2396
2397 static dbus_bool_t
2398 cleanup_service_reload_test (DBusString *dir)
2399 {
2400   if (!test_remove_directory (dir))
2401     return FALSE;
2402
2403   return TRUE;
2404 }
2405
2406 typedef struct
2407 {
2408   BusActivation *activation;
2409   const char    *service_name;
2410   dbus_bool_t    expecting_find;
2411 } CheckData;
2412
2413 static dbus_bool_t
2414 check_func (void *data)
2415 {
2416   CheckData          *d;
2417   BusActivationEntry *entry;
2418   DBusError           error;
2419   dbus_bool_t         ret_val;
2420
2421   ret_val = TRUE;
2422   d = data;
2423
2424   dbus_error_init (&error);
2425
2426   entry = activation_find_entry (d->activation, d->service_name, &error);
2427   if (entry == NULL)
2428     {
2429       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
2430         {
2431           ret_val = TRUE;
2432         }
2433       else
2434         {
2435           if (d->expecting_find)
2436             ret_val = FALSE;
2437         }
2438
2439       dbus_error_free (&error);
2440     }
2441   else
2442     {
2443       if (!d->expecting_find)
2444         ret_val = FALSE;
2445     }
2446
2447   return ret_val;
2448 }
2449
2450 static dbus_bool_t
2451 do_test (const char *description, dbus_bool_t oom_test, CheckData *data)
2452 {
2453   dbus_bool_t err;
2454
2455   if (oom_test)
2456     err = !_dbus_test_oom_handling (description, check_func, data);
2457   else
2458     err = !check_func (data);
2459
2460   if (err)
2461     _dbus_assert_not_reached ("Test failed");
2462
2463   return TRUE;
2464 }
2465
2466 static dbus_bool_t
2467 do_service_reload_test (DBusString *dir, dbus_bool_t oom_test)
2468 {
2469   BusActivation *activation;
2470   DBusString     address;
2471   DBusList      *directories;
2472   CheckData      d;
2473
2474   directories = NULL;
2475   _dbus_string_init_const (&address, "");
2476
2477   if (!_dbus_list_append (&directories, _dbus_string_get_data (dir)))
2478     return FALSE;
2479
2480   activation = bus_activation_new (NULL, &address, &directories, NULL);
2481   if (!activation)
2482     return FALSE;
2483
2484   d.activation = activation;
2485
2486   /* Check for existing service file */
2487   d.expecting_find = TRUE;
2488   d.service_name = SERVICE_NAME_1;
2489
2490   if (!do_test ("Existing service file", oom_test, &d))
2491     return FALSE;
2492
2493   /* Check for non-existing service file */
2494   d.expecting_find = FALSE;
2495   d.service_name = SERVICE_NAME_3;
2496
2497   if (!do_test ("Nonexisting service file", oom_test, &d))
2498     return FALSE;
2499
2500   /* Check for added service file */
2501   if (!test_create_service_file (dir, SERVICE_FILE_2, SERVICE_NAME_2, "exec-2"))
2502     return FALSE;
2503
2504   d.expecting_find = TRUE;
2505   d.service_name = SERVICE_NAME_2;
2506
2507   if (!do_test ("Added service file", oom_test, &d))
2508     return FALSE;
2509
2510   /* Check for removed service file */
2511   if (!test_remove_service_file (dir, SERVICE_FILE_2))
2512     return FALSE;
2513
2514   d.expecting_find = FALSE;
2515   d.service_name = SERVICE_FILE_2;
2516
2517   if (!do_test ("Removed service file", oom_test, &d))
2518     return FALSE;
2519
2520   /* Check for updated service file */
2521
2522   _dbus_sleep_milliseconds (1000); /* Sleep a second to make sure the mtime is updated */
2523
2524   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_3, "exec-3"))
2525     return FALSE;
2526
2527   d.expecting_find = TRUE;
2528   d.service_name = SERVICE_NAME_3;
2529
2530   if (!do_test ("Updated service file, part 1", oom_test, &d))
2531     return FALSE;
2532
2533   d.expecting_find = FALSE;
2534   d.service_name = SERVICE_NAME_1;
2535
2536   if (!do_test ("Updated service file, part 2", oom_test, &d))
2537     return FALSE;
2538
2539   bus_activation_unref (activation);
2540   _dbus_list_clear (&directories);
2541
2542   return TRUE;
2543 }
2544
2545 dbus_bool_t
2546 bus_activation_service_reload_test (const DBusString *test_data_dir)
2547 {
2548   DBusString directory;
2549
2550   if (!_dbus_string_init (&directory))
2551     return FALSE;
2552
2553   if (!_dbus_string_append (&directory, _dbus_get_tmpdir()))
2554     return FALSE;
2555
2556   if (!_dbus_string_append (&directory, "/dbus-reload-test-") ||
2557       !_dbus_generate_random_ascii (&directory, 6))
2558      {
2559        return FALSE;
2560      }
2561
2562   /* Do normal tests */
2563   if (!init_service_reload_test (&directory))
2564     _dbus_assert_not_reached ("could not initiate service reload test");
2565
2566   if (!do_service_reload_test (&directory, FALSE))
2567     ; /* Do nothing? */
2568
2569   /* Do OOM tests */
2570   if (!init_service_reload_test (&directory))
2571     _dbus_assert_not_reached ("could not initiate service reload test");
2572
2573   if (!do_service_reload_test (&directory, TRUE))
2574     ; /* Do nothing? */
2575
2576   /* Cleanup test directory */
2577   if (!cleanup_service_reload_test (&directory))
2578     return FALSE;
2579
2580   _dbus_string_free (&directory);
2581
2582   return TRUE;
2583 }
2584
2585 #endif /* DBUS_BUILD_TESTS */