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