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