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