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