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