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