DBusLoop: remove second layer of watch callbacks where possible
[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 dbus_bool_t
1327 babysitter_watch_callback (DBusWatch     *watch,
1328                            unsigned int   condition,
1329                            void          *data)
1330 {
1331   BusPendingActivation *pending_activation = data;
1332   dbus_bool_t retval;
1333   DBusBabysitter *babysitter;
1334   dbus_bool_t uses_servicehelper;
1335
1336   babysitter = pending_activation->babysitter;
1337
1338   _dbus_babysitter_ref (babysitter);
1339
1340   retval = dbus_watch_handle (watch, condition);
1341
1342   /* There are two major cases here; are we the system bus or the session?  Here this
1343    * is distinguished by whether or not we use a setuid helper launcher.  With the launch helper,
1344    * some process exit codes are meaningful, processed by handle_servicehelper_exit_error.
1345    *
1346    * In both cases though, just ignore when a process exits with status 0; it's possible for
1347    * a program to (misguidedly) "daemonize", and that appears to us as an exit.  This closes a race
1348    * condition between this code and the child process claiming the bus name.
1349    */
1350   uses_servicehelper = bus_context_get_servicehelper (pending_activation->activation->context) != NULL;
1351
1352   /* FIXME this is broken in the same way that
1353    * connection watches used to be; there should be
1354    * a separate callback for status change, instead
1355    * of doing "if we handled a watch status might
1356    * have changed"
1357    *
1358    * Fixing this lets us move dbus_watch_handle
1359    * calls into dbus-mainloop.c
1360    */
1361   if (_dbus_babysitter_get_child_exited (babysitter))
1362     {
1363       DBusError error;
1364       DBusHashIter iter;
1365       dbus_bool_t activation_failed;
1366       int exit_code = 0;
1367
1368       dbus_error_init (&error);
1369
1370       _dbus_babysitter_set_child_exit_error (babysitter, &error);
1371
1372       /* Explicitly check for SPAWN_CHILD_EXITED to avoid overwriting an
1373        * exec error */
1374       if (dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)
1375           && _dbus_babysitter_get_child_exit_status (babysitter, &exit_code))
1376         {
1377           activation_failed = exit_code != 0;
1378
1379           dbus_error_free(&error);
1380
1381           if (activation_failed)
1382             {
1383               if (uses_servicehelper)
1384                 handle_servicehelper_exit_error (exit_code, &error);
1385               else
1386                 _dbus_babysitter_set_child_exit_error (babysitter, &error);
1387             }
1388         }
1389       else
1390         {
1391           activation_failed = TRUE;
1392         }
1393
1394       if (activation_failed)
1395         {
1396           bus_context_log (pending_activation->activation->context,
1397                            DBUS_SYSTEM_LOG_INFO, "Activated service '%s' failed: %s",
1398                            pending_activation->service_name,
1399                            error.message);
1400
1401           /* Destroy all pending activations with the same exec */
1402           _dbus_hash_iter_init (pending_activation->activation->pending_activations,
1403                                 &iter);
1404           while (_dbus_hash_iter_next (&iter))
1405             {
1406               BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1407
1408               if (p != pending_activation && strcmp (p->exec, pending_activation->exec) == 0)
1409                 pending_activation_failed (p, &error);
1410             }
1411
1412           /* Destroys the pending activation */
1413           pending_activation_failed (pending_activation, &error);
1414
1415           dbus_error_free (&error);
1416         }
1417     }
1418
1419   _dbus_babysitter_unref (babysitter);
1420
1421   return retval;
1422 }
1423
1424 static dbus_bool_t
1425 add_babysitter_watch (DBusWatch      *watch,
1426                       void           *data)
1427 {
1428   BusPendingActivation *pending_activation = data;
1429
1430   return _dbus_loop_add_watch_full (
1431       bus_context_get_loop (pending_activation->activation->context),
1432       watch, babysitter_watch_callback, pending_activation, NULL);
1433 }
1434
1435 static void
1436 remove_babysitter_watch (DBusWatch      *watch,
1437                          void           *data)
1438 {
1439   BusPendingActivation *pending_activation = data;
1440
1441   _dbus_loop_remove_watch (bus_context_get_loop (pending_activation->activation->context),
1442                            watch);
1443 }
1444
1445 static dbus_bool_t
1446 pending_activation_timed_out (void *data)
1447 {
1448   BusPendingActivation *pending_activation = data;
1449   DBusError error;
1450
1451   /* Kill the spawned process, since it sucks
1452    * (not sure this is what we want to do, but
1453    * may as well try it for now)
1454    */
1455   if (pending_activation->babysitter)
1456     _dbus_babysitter_kill_child (pending_activation->babysitter);
1457
1458   dbus_error_init (&error);
1459
1460   dbus_set_error (&error, DBUS_ERROR_TIMED_OUT,
1461                   "Activation of %s timed out",
1462                   pending_activation->service_name);
1463   bus_context_log (pending_activation->activation->context,
1464                    DBUS_SYSTEM_LOG_INFO,
1465                    "Failed to activate service '%s': timed out",
1466                    pending_activation->service_name);
1467
1468   pending_activation_failed (pending_activation, &error);
1469
1470   dbus_error_free (&error);
1471
1472   return TRUE;
1473 }
1474
1475 static void
1476 cancel_pending (void *data)
1477 {
1478   BusPendingActivation *pending_activation = data;
1479
1480   _dbus_verbose ("Canceling pending activation of %s\n",
1481                  pending_activation->service_name);
1482
1483   if (pending_activation->babysitter)
1484     _dbus_babysitter_kill_child (pending_activation->babysitter);
1485
1486   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1487                                   pending_activation->service_name);
1488 }
1489
1490 static void
1491 free_pending_cancel_data (void *data)
1492 {
1493   BusPendingActivation *pending_activation = data;
1494
1495   bus_pending_activation_unref (pending_activation);
1496 }
1497
1498 static dbus_bool_t
1499 add_cancel_pending_to_transaction (BusTransaction       *transaction,
1500                                    BusPendingActivation *pending_activation)
1501 {
1502   if (!bus_transaction_add_cancel_hook (transaction, cancel_pending,
1503                                         pending_activation,
1504                                         free_pending_cancel_data))
1505     return FALSE;
1506
1507   bus_pending_activation_ref (pending_activation);
1508
1509   _dbus_verbose ("Saved pending activation to be canceled if the transaction fails\n");
1510
1511   return TRUE;
1512 }
1513
1514 static dbus_bool_t
1515 update_service_cache (BusActivation *activation, DBusError *error)
1516 {
1517   DBusHashIter iter;
1518
1519   _dbus_hash_iter_init (activation->directories, &iter);
1520   while (_dbus_hash_iter_next (&iter))
1521     {
1522       DBusError tmp_error;
1523       BusServiceDirectory *s_dir;
1524
1525       s_dir = _dbus_hash_iter_get_value (&iter);
1526
1527       dbus_error_init (&tmp_error);
1528       if (!update_directory (activation, s_dir, &tmp_error))
1529         {
1530           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
1531             {
1532               dbus_move_error (&tmp_error, error);
1533               return FALSE;
1534             }
1535
1536           dbus_error_free (&tmp_error);
1537           continue;
1538         }
1539     }
1540
1541   return TRUE;
1542 }
1543
1544 static BusActivationEntry *
1545 activation_find_entry (BusActivation *activation,
1546                        const char    *service_name,
1547                        DBusError     *error)
1548 {
1549   BusActivationEntry *entry;
1550
1551   entry = _dbus_hash_table_lookup_string (activation->entries, service_name);
1552   if (!entry)
1553     {
1554       if (!update_service_cache (activation, error))
1555         return NULL;
1556
1557       entry = _dbus_hash_table_lookup_string (activation->entries,
1558                                               service_name);
1559     }
1560   else
1561     {
1562       BusActivationEntry *updated_entry;
1563
1564       if (!check_service_file (activation, entry, &updated_entry, error))
1565         return NULL;
1566
1567       entry = updated_entry;
1568     }
1569
1570   if (!entry)
1571     {
1572       dbus_set_error (error, DBUS_ERROR_SERVICE_UNKNOWN,
1573                       "The name %s was not provided by any .service files",
1574                       service_name);
1575       return NULL;
1576     }
1577
1578   return entry;
1579 }
1580
1581 static char **
1582 bus_activation_get_environment (BusActivation *activation)
1583 {
1584   char **environment;
1585   int i, length;
1586   DBusString entry;
1587   DBusHashIter iter;
1588
1589   length = _dbus_hash_table_get_n_entries (activation->environment);
1590
1591   environment = dbus_new0 (char *, length + 1);
1592
1593   if (environment == NULL)
1594     return NULL;
1595
1596   i = 0;
1597   _dbus_hash_iter_init (activation->environment, &iter);
1598
1599   if (!_dbus_string_init (&entry))
1600     {
1601       dbus_free_string_array (environment);
1602       return NULL;
1603     }
1604
1605   while (_dbus_hash_iter_next (&iter))
1606     {
1607       const char *key, *value;
1608
1609       key = (const char *) _dbus_hash_iter_get_string_key (&iter);
1610       value = (const char *) _dbus_hash_iter_get_value (&iter);
1611
1612       if (!_dbus_string_append_printf (&entry, "%s=%s", key, value))
1613         break;
1614
1615       if (!_dbus_string_steal_data (&entry, environment + i))
1616         break;
1617       i++;
1618     }
1619
1620   _dbus_string_free (&entry);
1621
1622   if (i != length)
1623     {
1624       dbus_free_string_array (environment);
1625       environment = NULL;
1626     }
1627
1628   return environment;
1629 }
1630
1631 dbus_bool_t
1632 bus_activation_set_environment_variable (BusActivation     *activation,
1633                                          const char        *key,
1634                                          const char        *value,
1635                                          DBusError         *error)
1636 {
1637   char        *hash_key;
1638   char        *hash_value;
1639   dbus_bool_t  retval;
1640
1641   retval = FALSE;
1642   hash_key = NULL;
1643   hash_value = NULL;
1644   hash_key = _dbus_strdup (key);
1645
1646   if (hash_key == NULL)
1647     goto out;
1648
1649   hash_value = _dbus_strdup (value);
1650
1651   if (hash_value == NULL)
1652     goto out;
1653
1654   if (!_dbus_hash_table_insert_string (activation->environment,
1655                                        hash_key, hash_value))
1656     goto out;
1657
1658   retval = TRUE;
1659 out:
1660   if (retval == FALSE)
1661     {
1662       dbus_free (hash_key);
1663       dbus_free (hash_value);
1664       BUS_SET_OOM (error);
1665     }
1666
1667   return retval;
1668 }
1669
1670 dbus_bool_t
1671 bus_activation_activate_service (BusActivation  *activation,
1672                                  DBusConnection *connection,
1673                                  BusTransaction *transaction,
1674                                  dbus_bool_t     auto_activation,
1675                                  DBusMessage    *activation_message,
1676                                  const char     *service_name,
1677                                  DBusError      *error)
1678 {
1679   DBusError tmp_error;
1680   BusActivationEntry *entry;
1681   BusPendingActivation *pending_activation;
1682   BusPendingActivationEntry *pending_activation_entry;
1683   DBusMessage *message;
1684   DBusString service_str;
1685   const char *servicehelper;
1686   char **argv;
1687   char **envp = NULL;
1688   int argc;
1689   dbus_bool_t retval;
1690   DBusHashIter iter;
1691   dbus_bool_t was_pending_activation;
1692   DBusString command;
1693
1694   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1695
1696   if (activation->n_pending_activations >=
1697       bus_context_get_max_pending_activations (activation->context))
1698     {
1699       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1700                       "The maximum number of pending activations has been reached, activation of %s failed",
1701                       service_name);
1702       return FALSE;
1703     }
1704
1705   entry = activation_find_entry (activation, service_name, error);
1706   if (!entry)
1707     return FALSE;
1708
1709   /* Bypass the registry lookup if we're auto-activating, bus_dispatch would not
1710    * call us if the service is already active.
1711    */
1712   if (!auto_activation)
1713     {
1714       /* Check if the service is active */
1715       _dbus_string_init_const (&service_str, service_name);
1716       if (bus_registry_lookup (bus_context_get_registry (activation->context), &service_str) != NULL)
1717         {
1718           dbus_uint32_t result;
1719
1720           _dbus_verbose ("Service \"%s\" is already active\n", service_name);
1721
1722           message = dbus_message_new_method_return (activation_message);
1723
1724           if (!message)
1725             {
1726               _dbus_verbose ("No memory to create reply to activate message\n");
1727               BUS_SET_OOM (error);
1728               return FALSE;
1729             }
1730
1731           result = DBUS_START_REPLY_ALREADY_RUNNING;
1732
1733           if (!dbus_message_append_args (message,
1734                                          DBUS_TYPE_UINT32, &result,
1735                                          DBUS_TYPE_INVALID))
1736             {
1737               _dbus_verbose ("No memory to set args of reply to activate message\n");
1738               BUS_SET_OOM (error);
1739               dbus_message_unref (message);
1740               return FALSE;
1741             }
1742
1743           retval = bus_transaction_send_from_driver (transaction, connection, message);
1744           dbus_message_unref (message);
1745           if (!retval)
1746             {
1747               _dbus_verbose ("Failed to send reply\n");
1748               BUS_SET_OOM (error);
1749             }
1750
1751           return retval;
1752         }
1753     }
1754
1755   pending_activation_entry = dbus_new0 (BusPendingActivationEntry, 1);
1756   if (!pending_activation_entry)
1757     {
1758       _dbus_verbose ("Failed to create pending activation entry\n");
1759       BUS_SET_OOM (error);
1760       return FALSE;
1761     }
1762
1763   pending_activation_entry->auto_activation = auto_activation;
1764
1765   pending_activation_entry->activation_message = activation_message;
1766   dbus_message_ref (activation_message);
1767   pending_activation_entry->connection = connection;
1768   dbus_connection_ref (connection);
1769
1770   /* Check if the service is being activated */
1771   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1772   was_pending_activation = (pending_activation != NULL);
1773   if (was_pending_activation)
1774     {
1775       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1776         {
1777           _dbus_verbose ("Failed to append a new entry to pending activation\n");
1778
1779           BUS_SET_OOM (error);
1780           bus_pending_activation_entry_free (pending_activation_entry);
1781           return FALSE;
1782         }
1783
1784       pending_activation->n_entries += 1;
1785       pending_activation->activation->n_pending_activations += 1;
1786     }
1787   else
1788     {
1789       pending_activation = dbus_new0 (BusPendingActivation, 1);
1790       if (!pending_activation)
1791         {
1792           _dbus_verbose ("Failed to create pending activation\n");
1793
1794           BUS_SET_OOM (error);
1795           bus_pending_activation_entry_free (pending_activation_entry);
1796           return FALSE;
1797         }
1798
1799       pending_activation->activation = activation;
1800       pending_activation->refcount = 1;
1801
1802       pending_activation->service_name = _dbus_strdup (service_name);
1803       if (!pending_activation->service_name)
1804         {
1805           _dbus_verbose ("Failed to copy service name for pending activation\n");
1806
1807           BUS_SET_OOM (error);
1808           bus_pending_activation_unref (pending_activation);
1809           bus_pending_activation_entry_free (pending_activation_entry);
1810           return FALSE;
1811         }
1812
1813       pending_activation->exec = _dbus_strdup (entry->exec);
1814       if (!pending_activation->exec)
1815         {
1816           _dbus_verbose ("Failed to copy service exec for pending activation\n");
1817           BUS_SET_OOM (error);
1818           bus_pending_activation_unref (pending_activation);
1819           bus_pending_activation_entry_free (pending_activation_entry);
1820           return FALSE;
1821         }
1822
1823       if (entry->systemd_service)
1824         {
1825           pending_activation->systemd_service = _dbus_strdup (entry->systemd_service);
1826           if (!pending_activation->systemd_service)
1827             {
1828               _dbus_verbose ("Failed to copy systemd service for pending activation\n");
1829               BUS_SET_OOM (error);
1830               bus_pending_activation_unref (pending_activation);
1831               bus_pending_activation_entry_free (pending_activation_entry);
1832               return FALSE;
1833             }
1834         }
1835
1836       pending_activation->timeout =
1837         _dbus_timeout_new (bus_context_get_activation_timeout (activation->context),
1838                            pending_activation_timed_out,
1839                            pending_activation,
1840                            NULL);
1841       if (!pending_activation->timeout)
1842         {
1843           _dbus_verbose ("Failed to create timeout for pending activation\n");
1844
1845           BUS_SET_OOM (error);
1846           bus_pending_activation_unref (pending_activation);
1847           bus_pending_activation_entry_free (pending_activation_entry);
1848           return FALSE;
1849         }
1850
1851       if (!_dbus_loop_add_timeout (bus_context_get_loop (activation->context),
1852                                    pending_activation->timeout))
1853         {
1854           _dbus_verbose ("Failed to add timeout for pending activation\n");
1855
1856           BUS_SET_OOM (error);
1857           bus_pending_activation_unref (pending_activation);
1858           bus_pending_activation_entry_free (pending_activation_entry);
1859           return FALSE;
1860         }
1861
1862       pending_activation->timeout_added = TRUE;
1863
1864       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1865         {
1866           _dbus_verbose ("Failed to add entry to just-created pending activation\n");
1867
1868           BUS_SET_OOM (error);
1869           bus_pending_activation_unref (pending_activation);
1870           bus_pending_activation_entry_free (pending_activation_entry);
1871           return FALSE;
1872         }
1873
1874       pending_activation->n_entries += 1;
1875       pending_activation->activation->n_pending_activations += 1;
1876
1877       if (!_dbus_hash_table_insert_string (activation->pending_activations,
1878                                            pending_activation->service_name,
1879                                            pending_activation))
1880         {
1881           _dbus_verbose ("Failed to put pending activation in hash table\n");
1882
1883           BUS_SET_OOM (error);
1884           bus_pending_activation_unref (pending_activation);
1885           return FALSE;
1886         }
1887     }
1888
1889   if (!add_cancel_pending_to_transaction (transaction, pending_activation))
1890     {
1891       _dbus_verbose ("Failed to add pending activation cancel hook to transaction\n");
1892       BUS_SET_OOM (error);
1893       _dbus_hash_table_remove_string (activation->pending_activations,
1894                                       pending_activation->service_name);
1895
1896       return FALSE;
1897     }
1898
1899   if (was_pending_activation)
1900     return TRUE;
1901
1902   if (bus_context_get_systemd_activation (activation->context))
1903     {
1904       if (strcmp (service_name, "org.freedesktop.systemd1") == 0)
1905           /* systemd itself is missing apparently. That can happen
1906              only during early startup. Let's just wait until systemd
1907              connects to us and do nothing. */
1908         return TRUE;
1909
1910       if (entry->systemd_service)
1911         {
1912           BusTransaction *activation_transaction;
1913           DBusString service_string;
1914           BusService *service;
1915           BusRegistry *registry;
1916
1917           /* OK, we have a systemd service configured for this entry,
1918              hence let's enqueue an activation request message. This
1919              is implemented as a directed signal, not a method call,
1920              for three reasons: 1) we don't expect a response on
1921              success, where we just expect a name appearing on the
1922              bus; 2) at this time the systemd service might not yet
1923              have connected, so we wouldn't know the message serial at
1924              this point to set up a pending call; 3) it is ugly if the
1925              bus suddenly becomes the caller of a remote method. */
1926
1927           message = dbus_message_new_signal (DBUS_PATH_DBUS,
1928                                              "org.freedesktop.systemd1.Activator",
1929                                              "ActivationRequest");
1930           if (!message)
1931             {
1932               _dbus_verbose ("No memory to create activation message\n");
1933               BUS_SET_OOM (error);
1934               return FALSE;
1935             }
1936
1937           if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS) ||
1938               !dbus_message_set_destination (message, "org.freedesktop.systemd1") ||
1939               !dbus_message_append_args (message,
1940                                          DBUS_TYPE_STRING, &entry->systemd_service,
1941                                          DBUS_TYPE_INVALID))
1942             {
1943               _dbus_verbose ("No memory to set args of activation message\n");
1944               dbus_message_unref (message);
1945               BUS_SET_OOM (error);
1946               return FALSE;
1947             }
1948
1949           /* Create our transaction */
1950           activation_transaction = bus_transaction_new (activation->context);
1951           if (activation_transaction == NULL)
1952             {
1953               _dbus_verbose ("No memory to create activation transaction\n");
1954               dbus_message_unref (message);
1955               BUS_SET_OOM (error);
1956               return FALSE;
1957             }
1958
1959           /* Check whether systemd is already connected */
1960           registry = bus_connection_get_registry (connection);
1961           _dbus_string_init_const (&service_string, "org.freedesktop.systemd1");
1962           service = bus_registry_lookup (registry, &service_string);
1963
1964           if (service != NULL)
1965             {
1966               bus_context_log (activation->context,
1967                                DBUS_SYSTEM_LOG_INFO, "Activating via systemd: service name='%s' unit='%s'",
1968                                service_name,
1969                                entry->systemd_service);
1970               /* Wonderful, systemd is connected, let's just send the msg */
1971               retval = bus_dispatch_matches (activation_transaction, NULL, bus_service_get_primary_owners_connection (service),
1972                                              message, error);
1973             }
1974           else
1975             {
1976               bus_context_log (activation->context,
1977                                DBUS_SYSTEM_LOG_INFO, "Activating systemd to hand-off: service name='%s' unit='%s'",
1978                                service_name,
1979                                entry->systemd_service);
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
1985           dbus_message_unref (message);
1986
1987           if (!retval)
1988             {
1989               bus_context_log (activation->context,
1990                                DBUS_SYSTEM_LOG_INFO, "Failed to activate via systemd: service name='%s' unit='%s'",
1991                                service_name,
1992                                entry->systemd_service);
1993               _DBUS_ASSERT_ERROR_IS_SET (error);
1994               _dbus_verbose ("failed to send activation message: %s\n", error->name);
1995               bus_transaction_cancel_and_free (activation_transaction);
1996               return FALSE;
1997             }
1998
1999           bus_transaction_execute_and_free (activation_transaction);
2000           return TRUE;
2001         }
2002
2003       /* OK, we have no configured systemd service, hence let's
2004          proceed with traditional activation. */
2005     }
2006
2007   /* use command as system and session different */
2008   if (!_dbus_string_init (&command))
2009     {
2010       BUS_SET_OOM (error);
2011       return FALSE;
2012     }
2013
2014   /* does the bus use a helper? */
2015   servicehelper = bus_context_get_servicehelper (activation->context);
2016   if (servicehelper != NULL)
2017     {
2018       if (entry->user == NULL)
2019         {
2020           _dbus_string_free (&command);
2021           dbus_set_error (error, DBUS_ERROR_SPAWN_FILE_INVALID,
2022                           "Cannot do system-bus activation with no user\n");
2023           return FALSE;
2024         }
2025
2026       /* join the helper path and the service name */
2027       if (!_dbus_string_append (&command, servicehelper))
2028         {
2029           _dbus_string_free (&command);
2030           BUS_SET_OOM (error);
2031           return FALSE;
2032         }
2033       if (!_dbus_string_append (&command, " "))
2034         {
2035           _dbus_string_free (&command);
2036           BUS_SET_OOM (error);
2037           return FALSE;
2038         }
2039       if (!_dbus_string_append (&command, service_name))
2040         {
2041           _dbus_string_free (&command);
2042           BUS_SET_OOM (error);
2043           return FALSE;
2044         }
2045     }
2046   else
2047     {
2048       /* the bus does not use a helper, so we can append arguments with the exec line */
2049       if (!_dbus_string_append (&command, entry->exec))
2050         {
2051           _dbus_string_free (&command);
2052           BUS_SET_OOM (error);
2053           return FALSE;
2054         }
2055     }
2056
2057   /* convert command into arguments */
2058   if (!_dbus_shell_parse_argv (_dbus_string_get_const_data (&command), &argc, &argv, error))
2059     {
2060       _dbus_verbose ("Failed to parse command line: %s\n", entry->exec);
2061       _DBUS_ASSERT_ERROR_IS_SET (error);
2062
2063       _dbus_hash_table_remove_string (activation->pending_activations,
2064                                       pending_activation->service_name);
2065
2066       _dbus_string_free (&command);
2067       return FALSE;
2068     }
2069   _dbus_string_free (&command);
2070
2071   if (!add_bus_environment (activation, error))
2072     {
2073       _DBUS_ASSERT_ERROR_IS_SET (error);
2074       dbus_free_string_array (argv);
2075       return FALSE;
2076     }
2077
2078   envp = bus_activation_get_environment (activation);
2079
2080   if (envp == NULL)
2081     {
2082       BUS_SET_OOM (error);
2083       dbus_free_string_array (argv);
2084       return FALSE;
2085     }
2086
2087   _dbus_verbose ("Spawning %s ...\n", argv[0]);
2088   if (servicehelper != NULL)
2089     bus_context_log (activation->context,
2090                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s' (using servicehelper)",
2091                      service_name);
2092   else
2093     bus_context_log (activation->context,
2094                      DBUS_SYSTEM_LOG_INFO, "Activating service name='%s'",
2095                      service_name);
2096
2097   dbus_error_init (&tmp_error);
2098
2099   if (!_dbus_spawn_async_with_babysitter (&pending_activation->babysitter, argv,
2100                                           envp,
2101                                           NULL, activation,
2102                                           &tmp_error))
2103     {
2104       _dbus_verbose ("Failed to spawn child\n");
2105       bus_context_log (activation->context,
2106                        DBUS_SYSTEM_LOG_INFO, "Failed to activate service %s: %s",
2107                        service_name,
2108                        tmp_error.message);
2109       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
2110       dbus_move_error (&tmp_error, error);
2111       dbus_free_string_array (argv);
2112       dbus_free_string_array (envp);
2113
2114       return FALSE;
2115     }
2116
2117   dbus_free_string_array (argv);
2118   envp = NULL;
2119
2120   _dbus_assert (pending_activation->babysitter != NULL);
2121
2122   if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
2123                                              add_babysitter_watch,
2124                                              remove_babysitter_watch,
2125                                              NULL,
2126                                              pending_activation,
2127                                              NULL))
2128     {
2129       BUS_SET_OOM (error);
2130       _dbus_verbose ("Failed to set babysitter watch functions\n");
2131       return FALSE;
2132     }
2133
2134   return TRUE;
2135 }
2136
2137 dbus_bool_t
2138 bus_activation_list_services (BusActivation *activation,
2139                               char        ***listp,
2140                               int           *array_len)
2141 {
2142   int i, j, len;
2143   char **retval;
2144   DBusHashIter iter;
2145
2146   len = _dbus_hash_table_get_n_entries (activation->entries);
2147   retval = dbus_new (char *, len + 1);
2148
2149   if (retval == NULL)
2150     return FALSE;
2151
2152   _dbus_hash_iter_init (activation->entries, &iter);
2153   i = 0;
2154   while (_dbus_hash_iter_next (&iter))
2155     {
2156       BusActivationEntry *entry = _dbus_hash_iter_get_value (&iter);
2157
2158       retval[i] = _dbus_strdup (entry->name);
2159       if (retval[i] == NULL)
2160         goto error;
2161
2162       i++;
2163     }
2164
2165   retval[i] = NULL;
2166
2167   if (array_len)
2168     *array_len = len;
2169
2170   *listp = retval;
2171   return TRUE;
2172
2173  error:
2174   for (j = 0; j < i; j++)
2175     dbus_free (retval[i]);
2176   dbus_free (retval);
2177
2178   return FALSE;
2179 }
2180
2181 dbus_bool_t
2182 dbus_activation_systemd_failure (BusActivation *activation,
2183                                  DBusMessage   *message)
2184 {
2185   DBusError error;
2186   const char *code, *str, *unit = NULL;
2187
2188   dbus_error_init(&error);
2189
2190   /* This is called whenever the systemd activator sent us a
2191      response. We'll invalidate all pending activations that match the
2192      unit name. */
2193
2194   if (dbus_message_get_args (message, &error,
2195                              DBUS_TYPE_STRING, &unit,
2196                              DBUS_TYPE_STRING, &code,
2197                              DBUS_TYPE_STRING, &str,
2198                              DBUS_TYPE_INVALID))
2199     dbus_set_error(&error, code, str);
2200
2201
2202   if (unit)
2203     {
2204       DBusHashIter iter;
2205
2206       bus_context_log (activation->context,
2207                        DBUS_SYSTEM_LOG_INFO, "Activation via systemd failed for unit '%s': %s",
2208                        unit,
2209                        str);
2210
2211       _dbus_hash_iter_init (activation->pending_activations,
2212                             &iter);
2213
2214       while (_dbus_hash_iter_next (&iter))
2215         {
2216           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
2217
2218           if (p->systemd_service && strcmp (p->systemd_service, unit) == 0)
2219             pending_activation_failed(p, &error);
2220         }
2221     }
2222
2223   dbus_error_free(&error);
2224
2225   return TRUE;
2226 }
2227
2228 #ifdef DBUS_BUILD_TESTS
2229
2230 #include <stdio.h>
2231
2232 #define SERVICE_NAME_1 "MyService1"
2233 #define SERVICE_NAME_2 "MyService2"
2234 #define SERVICE_NAME_3 "MyService3"
2235
2236 #define SERVICE_FILE_1 "service-1.service"
2237 #define SERVICE_FILE_2 "service-2.service"
2238 #define SERVICE_FILE_3 "service-3.service"
2239
2240 static dbus_bool_t
2241 test_create_service_file (DBusString *dir,
2242                           const char *filename,
2243                           const char *name,
2244                           const char *exec)
2245 {
2246   DBusString  file_name, full_path;
2247   FILE        *file;
2248   dbus_bool_t  ret_val;
2249
2250   ret_val = TRUE;
2251   _dbus_string_init_const (&file_name, filename);
2252
2253   if (!_dbus_string_init (&full_path))
2254     return FALSE;
2255
2256   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2257       !_dbus_concat_dir_and_file (&full_path, &file_name))
2258     {
2259       ret_val = FALSE;
2260       goto out;
2261     }
2262
2263   file = fopen (_dbus_string_get_const_data (&full_path), "w");
2264   if (!file)
2265     {
2266       ret_val = FALSE;
2267       goto out;
2268     }
2269
2270   fprintf (file, "[D-BUS Service]\nName=%s\nExec=%s\n", name, exec);
2271   fclose (file);
2272
2273 out:
2274   _dbus_string_free (&full_path);
2275   return ret_val;
2276 }
2277
2278 static dbus_bool_t
2279 test_remove_service_file (DBusString *dir, const char *filename)
2280 {
2281   DBusString  file_name, full_path;
2282   dbus_bool_t ret_val;
2283
2284   ret_val = TRUE;
2285
2286   _dbus_string_init_const (&file_name, filename);
2287
2288   if (!_dbus_string_init (&full_path))
2289     return FALSE;
2290
2291   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
2292       !_dbus_concat_dir_and_file (&full_path, &file_name))
2293     {
2294       ret_val = FALSE;
2295       goto out;
2296     }
2297
2298   if (!_dbus_delete_file (&full_path, NULL))
2299     {
2300       ret_val = FALSE;
2301       goto out;
2302     }
2303
2304 out:
2305   _dbus_string_free (&full_path);
2306   return ret_val;
2307 }
2308
2309 static dbus_bool_t
2310 test_remove_directory (DBusString *dir)
2311 {
2312   DBusDirIter *iter;
2313   DBusString   filename, full_path;
2314   dbus_bool_t  ret_val;
2315
2316   ret_val = TRUE;
2317
2318   if (!_dbus_string_init (&filename))
2319     return FALSE;
2320
2321   if (!_dbus_string_init (&full_path))
2322     {
2323       _dbus_string_free (&filename);
2324       return FALSE;
2325     }
2326
2327   iter = _dbus_directory_open (dir, NULL);
2328   if (iter == NULL)
2329     {
2330       ret_val = FALSE;
2331       goto out;
2332     }
2333
2334   while (_dbus_directory_get_next_file (iter, &filename, NULL))
2335     {
2336       if (!test_remove_service_file (dir, _dbus_string_get_const_data (&filename)))
2337         {
2338           ret_val = FALSE;
2339           goto out;
2340         }
2341     }
2342   _dbus_directory_close (iter);
2343
2344   if (!_dbus_delete_directory (dir, NULL))
2345     {
2346       ret_val = FALSE;
2347       goto out;
2348     }
2349
2350 out:
2351   _dbus_string_free (&filename);
2352   _dbus_string_free (&full_path);
2353
2354   return ret_val;
2355 }
2356
2357 static dbus_bool_t
2358 init_service_reload_test (DBusString *dir)
2359 {
2360   DBusStat stat_buf;
2361
2362   if (!_dbus_stat (dir, &stat_buf, NULL))
2363     {
2364       if (!_dbus_create_directory (dir, NULL))
2365         return FALSE;
2366     }
2367   else
2368     {
2369       if (!test_remove_directory (dir))
2370         return FALSE;
2371
2372       if (!_dbus_create_directory (dir, NULL))
2373         return FALSE;
2374     }
2375
2376   /* Create one initial file */
2377   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_1, "exec-1"))
2378     return FALSE;
2379
2380   return TRUE;
2381 }
2382
2383 static dbus_bool_t
2384 cleanup_service_reload_test (DBusString *dir)
2385 {
2386   if (!test_remove_directory (dir))
2387     return FALSE;
2388
2389   return TRUE;
2390 }
2391
2392 typedef struct
2393 {
2394   BusActivation *activation;
2395   const char    *service_name;
2396   dbus_bool_t    expecting_find;
2397 } CheckData;
2398
2399 static dbus_bool_t
2400 check_func (void *data)
2401 {
2402   CheckData          *d;
2403   BusActivationEntry *entry;
2404   DBusError           error;
2405   dbus_bool_t         ret_val;
2406
2407   ret_val = TRUE;
2408   d = data;
2409
2410   dbus_error_init (&error);
2411
2412   entry = activation_find_entry (d->activation, d->service_name, &error);
2413   if (entry == NULL)
2414     {
2415       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
2416         {
2417           ret_val = TRUE;
2418         }
2419       else
2420         {
2421           if (d->expecting_find)
2422             ret_val = FALSE;
2423         }
2424
2425       dbus_error_free (&error);
2426     }
2427   else
2428     {
2429       if (!d->expecting_find)
2430         ret_val = FALSE;
2431     }
2432
2433   return ret_val;
2434 }
2435
2436 static dbus_bool_t
2437 do_test (const char *description, dbus_bool_t oom_test, CheckData *data)
2438 {
2439   dbus_bool_t err;
2440
2441   if (oom_test)
2442     err = !_dbus_test_oom_handling (description, check_func, data);
2443   else
2444     err = !check_func (data);
2445
2446   if (err)
2447     _dbus_assert_not_reached ("Test failed");
2448
2449   return TRUE;
2450 }
2451
2452 static dbus_bool_t
2453 do_service_reload_test (DBusString *dir, dbus_bool_t oom_test)
2454 {
2455   BusActivation *activation;
2456   DBusString     address;
2457   DBusList      *directories;
2458   CheckData      d;
2459
2460   directories = NULL;
2461   _dbus_string_init_const (&address, "");
2462
2463   if (!_dbus_list_append (&directories, _dbus_string_get_data (dir)))
2464     return FALSE;
2465
2466   activation = bus_activation_new (NULL, &address, &directories, NULL);
2467   if (!activation)
2468     return FALSE;
2469
2470   d.activation = activation;
2471
2472   /* Check for existing service file */
2473   d.expecting_find = TRUE;
2474   d.service_name = SERVICE_NAME_1;
2475
2476   if (!do_test ("Existing service file", oom_test, &d))
2477     return FALSE;
2478
2479   /* Check for non-existing service file */
2480   d.expecting_find = FALSE;
2481   d.service_name = SERVICE_NAME_3;
2482
2483   if (!do_test ("Nonexisting service file", oom_test, &d))
2484     return FALSE;
2485
2486   /* Check for added service file */
2487   if (!test_create_service_file (dir, SERVICE_FILE_2, SERVICE_NAME_2, "exec-2"))
2488     return FALSE;
2489
2490   d.expecting_find = TRUE;
2491   d.service_name = SERVICE_NAME_2;
2492
2493   if (!do_test ("Added service file", oom_test, &d))
2494     return FALSE;
2495
2496   /* Check for removed service file */
2497   if (!test_remove_service_file (dir, SERVICE_FILE_2))
2498     return FALSE;
2499
2500   d.expecting_find = FALSE;
2501   d.service_name = SERVICE_FILE_2;
2502
2503   if (!do_test ("Removed service file", oom_test, &d))
2504     return FALSE;
2505
2506   /* Check for updated service file */
2507
2508   _dbus_sleep_milliseconds (1000); /* Sleep a second to make sure the mtime is updated */
2509
2510   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_3, "exec-3"))
2511     return FALSE;
2512
2513   d.expecting_find = TRUE;
2514   d.service_name = SERVICE_NAME_3;
2515
2516   if (!do_test ("Updated service file, part 1", oom_test, &d))
2517     return FALSE;
2518
2519   d.expecting_find = FALSE;
2520   d.service_name = SERVICE_NAME_1;
2521
2522   if (!do_test ("Updated service file, part 2", oom_test, &d))
2523     return FALSE;
2524
2525   bus_activation_unref (activation);
2526   _dbus_list_clear (&directories);
2527
2528   return TRUE;
2529 }
2530
2531 dbus_bool_t
2532 bus_activation_service_reload_test (const DBusString *test_data_dir)
2533 {
2534   DBusString directory;
2535
2536   if (!_dbus_string_init (&directory))
2537     return FALSE;
2538
2539   if (!_dbus_string_append (&directory, _dbus_get_tmpdir()))
2540     return FALSE;
2541
2542   if (!_dbus_string_append (&directory, "/dbus-reload-test-") ||
2543       !_dbus_generate_random_ascii (&directory, 6))
2544      {
2545        return FALSE;
2546      }
2547
2548   /* Do normal tests */
2549   if (!init_service_reload_test (&directory))
2550     _dbus_assert_not_reached ("could not initiate service reload test");
2551
2552   if (!do_service_reload_test (&directory, FALSE))
2553     ; /* Do nothing? */
2554
2555   /* Do OOM tests */
2556   if (!init_service_reload_test (&directory))
2557     _dbus_assert_not_reached ("could not initiate service reload test");
2558
2559   if (!do_service_reload_test (&directory, TRUE))
2560     ; /* Do nothing? */
2561
2562   /* Cleanup test directory */
2563   if (!cleanup_service_reload_test (&directory))
2564     return FALSE;
2565
2566   _dbus_string_free (&directory);
2567
2568   return TRUE;
2569 }
2570
2571 #endif /* DBUS_BUILD_TESTS */