2007-07-24 Richard Hughes <richard@hughsie.com>
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  */
25 #include "activation.h"
26 #include "activation-exit-codes.h"
27 #include "desktop-file.h"
28 #include "services.h"
29 #include "test.h"
30 #include "utils.h"
31 #include <dbus/dbus-internals.h>
32 #include <dbus/dbus-hash.h>
33 #include <dbus/dbus-list.h>
34 #include <dbus/dbus-shell.h>
35 #include <dbus/dbus-spawn.h>
36 #include <dbus/dbus-timeout.h>
37 #include <dbus/dbus-sysdeps.h>
38 #ifdef HAVE_ERRNO_H
39 #include <errno.h>
40 #endif
41
42 struct BusActivation
43 {
44   int refcount;
45   DBusHashTable *entries;
46   DBusHashTable *pending_activations;
47   char *server_address;
48   BusContext *context;
49   int n_pending_activations; /**< This is in fact the number of BusPendingActivationEntry,
50                               * i.e. number of pending activation requests, not pending
51                               * activations per se
52                               */
53   DBusHashTable *directories;
54 };
55
56 typedef struct
57 {
58   int refcount;
59   char *dir_c;
60   DBusHashTable *entries;
61 } BusServiceDirectory;
62
63 typedef struct
64 {
65   int refcount;
66   char *name;
67   char *exec;
68   char *user;
69   unsigned long mtime;
70   BusServiceDirectory *s_dir;
71   char *filename;
72 } BusActivationEntry;
73
74 typedef struct BusPendingActivationEntry BusPendingActivationEntry;
75
76 struct BusPendingActivationEntry
77 {
78   DBusMessage *activation_message;
79   DBusConnection *connection;
80
81   dbus_bool_t auto_activation;
82 };
83
84 typedef struct
85 {
86   int refcount;
87   BusActivation *activation;
88   char *service_name;
89   char *exec;
90   DBusList *entries;
91   int n_entries;
92   DBusBabysitter *babysitter;
93   DBusTimeout *timeout;
94   unsigned int timeout_added : 1;
95 } BusPendingActivation;
96
97 #if 0
98 static BusServiceDirectory *
99 bus_service_directory_ref (BusServiceDirectory *dir)
100 {
101   _dbus_assert (dir->refcount);
102   
103   dir->refcount++;
104
105   return dir;
106 }
107 #endif
108
109 static void
110 bus_service_directory_unref (BusServiceDirectory *dir)
111 {
112   if (dir == NULL) 
113     return; 
114
115   _dbus_assert (dir->refcount > 0);
116   dir->refcount--;
117
118   if (dir->refcount > 0)
119     return;
120
121   if (dir->entries)
122     _dbus_hash_table_unref (dir->entries);
123
124   dbus_free (dir->dir_c);
125   dbus_free (dir);
126 }
127
128 static void
129 bus_pending_activation_entry_free (BusPendingActivationEntry *entry)
130 {
131   if (entry->activation_message)
132     dbus_message_unref (entry->activation_message);
133   
134   if (entry->connection)
135     dbus_connection_unref (entry->connection);
136   
137   dbus_free (entry);
138 }
139
140 static void
141 handle_timeout_callback (DBusTimeout   *timeout,
142                          void          *data)
143 {
144   BusPendingActivation *pending_activation = data;
145
146   while (!dbus_timeout_handle (pending_activation->timeout))
147     _dbus_wait_for_memory ();
148 }
149
150 static BusPendingActivation * 
151 bus_pending_activation_ref (BusPendingActivation *pending_activation)
152 {
153   _dbus_assert (pending_activation->refcount > 0);
154   pending_activation->refcount += 1;
155
156   return pending_activation;
157 }
158
159 static void
160 bus_pending_activation_unref (BusPendingActivation *pending_activation)
161 {
162   DBusList *link;
163   
164   if (pending_activation == NULL) /* hash table requires this */
165     return;
166
167   _dbus_assert (pending_activation->refcount > 0);
168   pending_activation->refcount -= 1;
169
170   if (pending_activation->refcount > 0)
171     return;
172   
173   if (pending_activation->timeout_added)
174     {
175       _dbus_loop_remove_timeout (bus_context_get_loop (pending_activation->activation->context),
176                                  pending_activation->timeout,
177                                  handle_timeout_callback, pending_activation);
178       pending_activation->timeout_added = FALSE;
179     }
180
181   if (pending_activation->timeout)
182     _dbus_timeout_unref (pending_activation->timeout);
183   
184   if (pending_activation->babysitter)
185     {
186       if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
187                                                  NULL, NULL, NULL,
188                                                  pending_activation->babysitter,
189                                                  NULL))
190         _dbus_assert_not_reached ("setting watch functions to NULL failed");
191       
192       _dbus_babysitter_unref (pending_activation->babysitter);
193     }
194   
195   dbus_free (pending_activation->service_name);
196   dbus_free (pending_activation->exec);
197
198   link = _dbus_list_get_first_link (&pending_activation->entries);
199
200   while (link != NULL)
201     {
202       BusPendingActivationEntry *entry = link->data;
203
204       bus_pending_activation_entry_free (entry);
205
206       link = _dbus_list_get_next_link (&pending_activation->entries, link);
207     }
208   _dbus_list_clear (&pending_activation->entries);
209
210   pending_activation->activation->n_pending_activations -=
211     pending_activation->n_entries;
212
213   _dbus_assert (pending_activation->activation->n_pending_activations >= 0);
214   
215   dbus_free (pending_activation);
216 }
217
218 static BusActivationEntry *
219 bus_activation_entry_ref (BusActivationEntry *entry)
220 {
221   _dbus_assert (entry->refcount > 0);
222   entry->refcount++;
223
224   return entry;
225 }
226
227 static void
228 bus_activation_entry_unref (BusActivationEntry *entry)
229 {
230   if (entry == NULL) /* hash table requires this */
231     return;
232   
233   _dbus_assert (entry->refcount > 0);
234   entry->refcount--;
235   
236   if (entry->refcount > 0) 
237     return;
238   
239   dbus_free (entry->name);
240   dbus_free (entry->exec);
241   dbus_free (entry->user);
242   dbus_free (entry->filename);
243
244   dbus_free (entry);
245 }
246
247 static dbus_bool_t
248 update_desktop_file_entry (BusActivation       *activation,
249                            BusServiceDirectory *s_dir,
250                            DBusString          *filename,
251                            BusDesktopFile      *desktop_file,
252                            DBusError           *error)
253 {
254   char *name, *exec, *user;
255   BusActivationEntry *entry;
256   DBusStat stat_buf;
257   DBusString file_path;
258   DBusError tmp_error;
259
260   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
261   
262   name = NULL;
263   exec = NULL;
264   user = NULL;
265   entry = NULL;
266   
267   dbus_error_init (&tmp_error);
268
269   if (!_dbus_string_init (&file_path))
270     {
271       BUS_SET_OOM (error);
272       return FALSE;
273     }
274  
275   if (!_dbus_string_append (&file_path, s_dir->dir_c) ||
276       !_dbus_concat_dir_and_file (&file_path, filename))
277     {
278       BUS_SET_OOM (error);
279       goto failed;
280     }
281  
282   if (!_dbus_stat (&file_path, &stat_buf, NULL)) 
283     {
284       dbus_set_error (error, DBUS_ERROR_FAILED,
285                       "Can't stat the service file\n");
286       goto failed;
287     }
288  
289   if (!bus_desktop_file_get_string (desktop_file,
290                                     DBUS_SERVICE_SECTION,
291                                     DBUS_SERVICE_NAME,
292                                     &name,
293                                     error))
294     goto failed;
295
296   if (!bus_desktop_file_get_string (desktop_file,
297                                     DBUS_SERVICE_SECTION,
298                                     DBUS_SERVICE_EXEC,
299                                     &exec,
300                                     error))
301     goto failed;
302
303   /* user is not _required_ unless we are using system activation */
304   if (!bus_desktop_file_get_string (desktop_file,
305                                     DBUS_SERVICE_SECTION,
306                                     DBUS_SERVICE_USER,
307                                     &user, &tmp_error))
308     {
309       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
310       /* if we got OOM, then exit */
311       if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
312         {
313           dbus_move_error (&tmp_error, error);
314           goto failed;
315         }
316       else
317         {
318           /* if we have error because we didn't find anything then continue */
319           dbus_error_free (&tmp_error);
320           dbus_free (user);
321           user = NULL;
322         }
323     }
324   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
325
326   entry = _dbus_hash_table_lookup_string (s_dir->entries, 
327                                           _dbus_string_get_const_data (filename));
328   if (entry == NULL) /* New file */
329     { 
330       /* FIXME we need a better-defined algorithm for which service file to
331        * pick than "whichever one is first in the directory listing"
332        */
333       if (_dbus_hash_table_lookup_string (activation->entries, name))
334         {
335           dbus_set_error (error, DBUS_ERROR_FAILED,
336                           "Service %s already exists in activation entry list\n", name);
337           goto failed;
338         }
339       
340       entry = dbus_new0 (BusActivationEntry, 1);
341       if (entry == NULL)
342         {
343           BUS_SET_OOM (error);
344           goto failed;
345         }
346      
347       entry->name = name;
348       entry->exec = exec;
349       entry->user = user;
350       entry->refcount = 1;
351     
352       entry->s_dir = s_dir;
353       entry->filename = _dbus_strdup (_dbus_string_get_const_data (filename));
354       if (!entry->filename)
355         {
356           BUS_SET_OOM (error);
357           goto failed;
358         }
359
360       if (!_dbus_hash_table_insert_string (activation->entries, entry->name, bus_activation_entry_ref (entry)))
361         {
362           BUS_SET_OOM (error);
363           goto failed;
364         }
365      
366       if (!_dbus_hash_table_insert_string (s_dir->entries, entry->filename, bus_activation_entry_ref (entry)))
367         {
368           /* Revert the insertion in the entries table */
369           _dbus_hash_table_remove_string (activation->entries, entry->name);
370           BUS_SET_OOM (error);
371           goto failed;
372         }
373
374       _dbus_verbose ("Added \"%s\" to list of services\n", entry->name);
375     }
376   else /* Just update the entry */
377     {
378       bus_activation_entry_ref (entry);
379       _dbus_hash_table_remove_string (activation->entries, entry->name);
380
381       if (_dbus_hash_table_lookup_string (activation->entries, name))
382         {
383           _dbus_verbose ("The new service name \"%s\" of service file \"%s\" already in cache, ignoring\n",
384                          name, _dbus_string_get_const_data (&file_path));
385           goto failed;
386         }
387  
388       dbus_free (entry->name);
389       dbus_free (entry->exec);
390       dbus_free (entry->user);
391       entry->name = name;
392       entry->exec = exec;
393       entry->user = user;
394       if (!_dbus_hash_table_insert_string (activation->entries,
395                                            entry->name, bus_activation_entry_ref(entry)))
396         {
397           BUS_SET_OOM (error);
398           /* Also remove path to entries hash since we want this in sync with
399            * the entries hash table */
400           _dbus_hash_table_remove_string (entry->s_dir->entries, 
401                                           entry->filename);
402           bus_activation_entry_unref (entry);
403           return FALSE;
404         }
405     }
406   
407   entry->mtime = stat_buf.mtime;
408   
409   _dbus_string_free (&file_path);
410   bus_activation_entry_unref (entry);
411
412   return TRUE;
413
414 failed:
415   dbus_free (name);
416   dbus_free (exec);
417   dbus_free (user);
418   _dbus_string_free (&file_path);
419
420   if (entry)
421     bus_activation_entry_unref (entry);
422   
423   return FALSE;
424 }
425
426 static dbus_bool_t
427 check_service_file (BusActivation       *activation,
428                     BusActivationEntry  *entry,
429                     BusActivationEntry **updated_entry,
430                     DBusError           *error)
431 {
432   DBusStat stat_buf;
433   dbus_bool_t retval;
434   BusActivationEntry *tmp_entry;
435   DBusString file_path;
436   DBusString filename;
437
438   retval = TRUE;
439   tmp_entry = entry;
440   
441   _dbus_string_init_const (&filename, entry->filename);
442   
443   if (!_dbus_string_init (&file_path))
444     {
445       BUS_SET_OOM (error);
446       return FALSE;
447     }
448  
449   if (!_dbus_string_append (&file_path, entry->s_dir->dir_c) ||
450       !_dbus_concat_dir_and_file (&file_path, &filename))
451     {
452       BUS_SET_OOM (error);
453       retval = FALSE;
454       goto out;
455     }
456   
457   if (!_dbus_stat (&file_path, &stat_buf, NULL))
458     {
459       _dbus_verbose ("****** Can't stat file \"%s\", removing from cache\n",
460                      _dbus_string_get_const_data (&file_path));
461
462       _dbus_hash_table_remove_string (activation->entries, entry->name);
463       _dbus_hash_table_remove_string (entry->s_dir->entries, entry->filename);
464
465       tmp_entry = NULL;
466       retval = TRUE;
467       goto out;
468     }
469   else 
470     {
471       if (stat_buf.mtime > entry->mtime) 
472         {
473           BusDesktopFile *desktop_file;
474           DBusError tmp_error;
475           
476           dbus_error_init (&tmp_error);
477           
478           desktop_file = bus_desktop_file_load (&file_path, &tmp_error);
479           if (desktop_file == NULL)
480             {
481               _dbus_verbose ("Could not load %s: %s\n",
482                              _dbus_string_get_const_data (&file_path), 
483                              tmp_error.message);
484               if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
485                 {
486                   dbus_move_error (&tmp_error, error);
487                   retval = FALSE;
488                   goto out;
489                 }
490               dbus_error_free (&tmp_error);
491               retval = TRUE;
492               goto out;
493             }
494          
495           /* @todo We can return OOM or a DBUS_ERROR_FAILED error 
496            *       Handle these both better
497            */ 
498           if (!update_desktop_file_entry (activation, entry->s_dir, &filename, desktop_file, &tmp_error))
499             {
500               bus_desktop_file_free (desktop_file);
501               if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
502                 {
503                   dbus_move_error (&tmp_error, error);
504                   retval = FALSE;
505                   goto out;
506                 }
507               dbus_error_free (&tmp_error);
508               retval = TRUE;
509               goto out;
510             }
511          
512           bus_desktop_file_free (desktop_file);
513           retval = TRUE;
514         }
515     }
516   
517 out:
518   _dbus_string_free (&file_path);
519
520   if (updated_entry != NULL)
521     *updated_entry = tmp_entry;
522   return retval;
523 }
524
525
526 /* warning: this doesn't fully "undo" itself on failure, i.e. doesn't strip
527  * hash entries it already added.
528  */
529 static dbus_bool_t
530 update_directory (BusActivation       *activation,
531                   BusServiceDirectory *s_dir,
532                   DBusError           *error)
533 {
534   DBusDirIter *iter;
535   DBusString dir, filename;
536   BusDesktopFile *desktop_file;
537   DBusError tmp_error;
538   dbus_bool_t retval;
539   BusActivationEntry *entry;
540   DBusString full_path;
541   
542   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
543   
544   iter = NULL;
545   desktop_file = NULL;
546   
547   _dbus_string_init_const (&dir, s_dir->dir_c);
548   
549   if (!_dbus_string_init (&filename))
550     {
551       BUS_SET_OOM (error);
552       return FALSE;
553     }
554
555   if (!_dbus_string_init (&full_path))
556     {
557       BUS_SET_OOM (error);
558       _dbus_string_free (&filename);
559       return FALSE;
560     }
561
562   retval = FALSE;
563
564   /* from this point it's safe to "goto out" */
565   
566   iter = _dbus_directory_open (&dir, error);
567   if (iter == NULL)
568     {
569       _dbus_verbose ("Failed to open directory %s: %s\n",
570                      s_dir->dir_c, 
571                      error ? error->message : "unknown");
572       goto out;
573     }
574   
575   /* Now read the files */
576   dbus_error_init (&tmp_error);
577   while (_dbus_directory_get_next_file (iter, &filename, &tmp_error))
578     {
579       _dbus_assert (!dbus_error_is_set (&tmp_error));
580       
581       _dbus_string_set_length (&full_path, 0);
582       
583       if (!_dbus_string_ends_with_c_str (&filename, ".service"))
584         {
585           _dbus_verbose ("Skipping non-.service file %s\n",
586                          _dbus_string_get_const_data (&filename));
587           continue;
588         }
589
590       entry = _dbus_hash_table_lookup_string (s_dir->entries, _dbus_string_get_const_data (&filename));
591       if (entry) /* Already has this service file in the cache */ 
592         {
593           if (!check_service_file (activation, entry, NULL, error))
594             goto out;
595
596           continue;
597         }
598       
599       if (!_dbus_string_append (&full_path, s_dir->dir_c) ||
600           !_dbus_concat_dir_and_file (&full_path, &filename))
601         {
602           BUS_SET_OOM (error);
603           goto out;
604         }
605           
606       /* New file */
607       desktop_file = bus_desktop_file_load (&full_path, &tmp_error);
608       if (desktop_file == NULL)
609         {
610           _dbus_verbose ("Could not load %s: %s\n",
611                          _dbus_string_get_const_data (&full_path),
612                          tmp_error.message);
613
614           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
615             {
616               dbus_move_error (&tmp_error, error);
617               goto out;
618             }
619           
620           dbus_error_free (&tmp_error);
621           continue;
622         }
623
624       /* @todo We can return OOM or a DBUS_ERROR_FAILED error 
625        *       Handle these both better
626        */ 
627       if (!update_desktop_file_entry (activation, s_dir, &filename, desktop_file, &tmp_error))
628         {
629           bus_desktop_file_free (desktop_file);
630           desktop_file = NULL;
631           
632           _dbus_verbose ("Could not add %s to activation entry list: %s\n",
633                          _dbus_string_get_const_data (&full_path), tmp_error.message);
634
635           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
636             {
637               dbus_move_error (&tmp_error, error);
638               goto out;
639             }
640
641           dbus_error_free (&tmp_error);
642           continue;
643         }
644       else
645         {
646           bus_desktop_file_free (desktop_file);
647           desktop_file = NULL;
648           continue;
649         }
650     }
651
652   if (dbus_error_is_set (&tmp_error))
653     {
654       dbus_move_error (&tmp_error, error);
655       goto out;
656     }
657   
658   retval = TRUE;
659
660  out:
661   if (!retval)
662     _DBUS_ASSERT_ERROR_IS_SET (error);
663   else
664     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
665   
666   if (iter != NULL)
667     _dbus_directory_close (iter);
668   _dbus_string_free (&filename);
669   _dbus_string_free (&full_path);
670   
671   return retval;
672 }
673
674 BusActivation*
675 bus_activation_new (BusContext        *context,
676                     const DBusString  *address,
677                     DBusList         **directories,
678                     DBusError         *error)
679 {
680   BusActivation *activation;
681   DBusList      *link;
682   char          *dir;
683   
684   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
685   
686   activation = dbus_new0 (BusActivation, 1);
687   if (activation == NULL)
688     {
689       BUS_SET_OOM (error);
690       return NULL;
691     }
692   
693   activation->refcount = 1;
694   activation->context = context;
695   activation->n_pending_activations = 0;
696   
697   if (!_dbus_string_copy_data (address, &activation->server_address))
698     {
699       BUS_SET_OOM (error);
700       goto failed;
701     }
702   
703   activation->entries = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
704                                              (DBusFreeFunction)bus_activation_entry_unref);
705   if (activation->entries == NULL)
706     {      
707       BUS_SET_OOM (error);
708       goto failed;
709     }
710
711   activation->pending_activations = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
712                                                           (DBusFreeFunction)bus_pending_activation_unref);
713
714   if (activation->pending_activations == NULL)
715     {
716       BUS_SET_OOM (error);
717       goto failed;
718     }
719
720   activation->directories = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
721                                                   (DBusFreeFunction)bus_service_directory_unref);
722   
723   if (activation->directories == NULL) 
724     {
725       BUS_SET_OOM (error);
726       goto failed;
727     }
728  
729   /* Load service files */
730   link = _dbus_list_get_first_link (directories);
731   while (link != NULL)
732     {
733       BusServiceDirectory *s_dir;
734       
735       dir = _dbus_strdup ((const char *) link->data);
736       if (!dir)
737         {
738           BUS_SET_OOM (error);
739           goto failed;
740         }
741       
742       s_dir = dbus_new0 (BusServiceDirectory, 1);
743       if (!s_dir)
744         {
745           dbus_free (dir);
746           BUS_SET_OOM (error);
747           goto failed;
748         }
749
750       s_dir->refcount = 1;
751       s_dir->dir_c = dir;
752       
753       s_dir->entries = _dbus_hash_table_new (DBUS_HASH_STRING, NULL,
754                                              (DBusFreeFunction)bus_activation_entry_unref);
755
756       if (!s_dir->entries)
757         {
758           bus_service_directory_unref (s_dir);
759           BUS_SET_OOM (error);
760           goto failed;
761         }
762
763       if (!_dbus_hash_table_insert_string (activation->directories, s_dir->dir_c, s_dir))
764         {
765           bus_service_directory_unref (s_dir);
766           BUS_SET_OOM (error);
767           goto failed;
768         }
769
770       /* only fail on OOM, it is ok if we can't read the directory */
771       if (!update_directory (activation, s_dir, error))
772         { 
773           if (dbus_error_has_name (error, DBUS_ERROR_NO_MEMORY)) 
774             goto failed;
775           else
776             dbus_error_free (error);
777         }
778
779       link = _dbus_list_get_next_link (directories, link);
780     }
781
782   return activation;
783   
784  failed:
785   bus_activation_unref (activation);  
786   return NULL;
787 }
788
789 BusActivation *
790 bus_activation_ref (BusActivation *activation)
791 {
792   _dbus_assert (activation->refcount > 0);
793   
794   activation->refcount += 1;
795
796   return activation;
797 }
798
799 void
800 bus_activation_unref (BusActivation *activation)
801 {
802   _dbus_assert (activation->refcount > 0);
803
804   activation->refcount -= 1;
805
806   if (activation->refcount > 0)
807     return;
808   
809   dbus_free (activation->server_address);
810   if (activation->entries)
811     _dbus_hash_table_unref (activation->entries);
812   if (activation->pending_activations)
813     _dbus_hash_table_unref (activation->pending_activations);
814   if (activation->directories)  
815     _dbus_hash_table_unref (activation->directories);
816   
817   dbus_free (activation);
818 }
819
820 static void
821 child_setup (void *data)
822 {
823   BusActivation *activation = data;
824   const char *type;
825   
826   /* If no memory, we simply have the child exit, so it won't try
827    * to connect to the wrong thing.
828    */
829   if (!_dbus_setenv ("DBUS_STARTER_ADDRESS", activation->server_address))
830     _dbus_exit (1);
831   
832   type = bus_context_get_type (activation->context);
833   if (type != NULL)
834     {
835       if (!_dbus_setenv ("DBUS_STARTER_BUS_TYPE", type))
836         _dbus_exit (1);
837
838       if (strcmp (type, "session") == 0)
839         {
840           if (!_dbus_setenv ("DBUS_SESSION_BUS_ADDRESS",
841                              activation->server_address))
842             _dbus_exit (1);
843         }
844       else if (strcmp (type, "system") == 0)
845         {
846           if (!_dbus_setenv ("DBUS_SYSTEM_BUS_ADDRESS",
847                              activation->server_address))
848             _dbus_exit (1);
849         }
850     }
851 }
852
853 typedef struct
854 {
855   BusPendingActivation *pending_activation;
856   DBusPreallocatedHash *hash_entry;
857 } RestorePendingData;
858
859 static void
860 restore_pending (void *data)
861 {
862   RestorePendingData *d = data;
863
864   _dbus_assert (d->pending_activation != NULL);
865   _dbus_assert (d->hash_entry != NULL);
866
867   _dbus_verbose ("Restoring pending activation for service %s, has timeout = %d\n",
868                  d->pending_activation->service_name,
869                  d->pending_activation->timeout_added);
870   
871   _dbus_hash_table_insert_string_preallocated (d->pending_activation->activation->pending_activations,
872                                                d->hash_entry,
873                                                d->pending_activation->service_name, d->pending_activation);
874
875   bus_pending_activation_ref (d->pending_activation);
876   
877   d->hash_entry = NULL;
878 }
879
880 static void
881 free_pending_restore_data (void *data)
882 {
883   RestorePendingData *d = data;
884
885   if (d->hash_entry)
886     _dbus_hash_table_free_preallocated_entry (d->pending_activation->activation->pending_activations,
887                                               d->hash_entry);
888
889   bus_pending_activation_unref (d->pending_activation);
890   
891   dbus_free (d);
892 }
893
894 static dbus_bool_t
895 add_restore_pending_to_transaction (BusTransaction       *transaction,
896                                     BusPendingActivation *pending_activation)
897 {
898   RestorePendingData *d;
899
900   d = dbus_new (RestorePendingData, 1);
901   if (d == NULL)
902     return FALSE;
903   
904   d->pending_activation = pending_activation;
905   d->hash_entry = _dbus_hash_table_preallocate_entry (d->pending_activation->activation->pending_activations);
906   
907   bus_pending_activation_ref (d->pending_activation);
908   
909   if (d->hash_entry == NULL ||
910       !bus_transaction_add_cancel_hook (transaction, restore_pending, d,
911                                         free_pending_restore_data))
912     {
913       free_pending_restore_data (d);
914       return FALSE;
915     }
916
917   _dbus_verbose ("Saved pending activation to be restored if the transaction fails\n");
918   
919   return TRUE;
920 }
921
922 dbus_bool_t
923 bus_activation_service_created (BusActivation  *activation,
924                                 const char     *service_name,
925                                 BusTransaction *transaction,
926                                 DBusError      *error)
927 {
928   BusPendingActivation *pending_activation;
929   DBusMessage *message;
930   DBusList *link;
931
932   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
933   
934   /* Check if it's a pending activation */
935   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
936
937   if (!pending_activation)
938     return TRUE;
939
940   link = _dbus_list_get_first_link (&pending_activation->entries);
941   while (link != NULL)
942     {
943       BusPendingActivationEntry *entry = link->data;
944       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
945       
946       if (dbus_connection_get_is_connected (entry->connection))
947         {
948           /* Only send activation replies to regular activation requests. */
949           if (!entry->auto_activation)
950             {
951               dbus_uint32_t result;
952               
953               message = dbus_message_new_method_return (entry->activation_message);
954               if (!message)
955                 {
956                   BUS_SET_OOM (error);
957                   goto error;
958                 }
959
960               result = DBUS_START_REPLY_SUCCESS;
961               
962               if (!dbus_message_append_args (message,
963                                              DBUS_TYPE_UINT32, &result,
964                                              DBUS_TYPE_INVALID))
965                 {
966                   dbus_message_unref (message);
967                   BUS_SET_OOM (error);
968                   goto error;
969                 }
970               
971               if (!bus_transaction_send_from_driver (transaction, entry->connection, message))
972                 {
973                   dbus_message_unref (message);
974                   BUS_SET_OOM (error);
975                   goto error;
976                 }
977               
978               dbus_message_unref (message);
979             }
980         }
981       
982       link = next;
983     }
984
985   return TRUE;
986
987  error:
988   return FALSE;
989 }
990
991 dbus_bool_t
992 bus_activation_send_pending_auto_activation_messages (BusActivation  *activation,
993                                                       BusService     *service,
994                                                       BusTransaction *transaction,
995                                                       DBusError      *error)
996 {
997   BusPendingActivation *pending_activation;
998   DBusList *link;
999
1000   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1001   
1002   /* Check if it's a pending activation */
1003   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations,
1004                                                        bus_service_get_name (service));
1005
1006   if (!pending_activation)
1007     return TRUE;
1008
1009   link = _dbus_list_get_first_link (&pending_activation->entries);
1010   while (link != NULL)
1011     {
1012       BusPendingActivationEntry *entry = link->data;
1013       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1014
1015       if (entry->auto_activation && dbus_connection_get_is_connected (entry->connection))
1016         {
1017           DBusConnection *addressed_recipient;
1018           
1019           addressed_recipient = bus_service_get_primary_owners_connection (service);
1020
1021           /* Check the security policy, which has the side-effect of adding an
1022            * expected pending reply.
1023            */
1024           if (!bus_context_check_security_policy (activation->context, transaction,
1025                                                   entry->connection,
1026                                                   addressed_recipient,
1027                                                   addressed_recipient,
1028                                                   entry->activation_message, error))
1029             goto error;
1030
1031           if (!bus_transaction_send (transaction, addressed_recipient, entry->activation_message))
1032             {
1033               BUS_SET_OOM (error);
1034               goto error;
1035             }
1036         }
1037
1038       link = next;
1039     }
1040
1041   if (!add_restore_pending_to_transaction (transaction, pending_activation))
1042     {
1043       _dbus_verbose ("Could not add cancel hook to transaction to revert removing pending activation\n");
1044       BUS_SET_OOM (error);
1045       goto error;
1046     }
1047   
1048   _dbus_hash_table_remove_string (activation->pending_activations, bus_service_get_name (service));
1049
1050   return TRUE;
1051
1052  error:
1053   return FALSE;
1054 }
1055
1056 /**
1057  * FIXME @todo the error messages here would ideally be preallocated
1058  * so we don't need to allocate memory to send them.
1059  * Using the usual tactic, prealloc an OOM message, then
1060  * if we can't alloc the real error send the OOM error instead.
1061  */
1062 static dbus_bool_t
1063 try_send_activation_failure (BusPendingActivation *pending_activation,
1064                              const DBusError      *how)
1065 {
1066   BusActivation *activation;
1067   DBusList *link;
1068   BusTransaction *transaction;
1069   
1070   activation = pending_activation->activation;
1071
1072   transaction = bus_transaction_new (activation->context);
1073   if (transaction == NULL)
1074     return FALSE;
1075   
1076   link = _dbus_list_get_first_link (&pending_activation->entries);
1077   while (link != NULL)
1078     {
1079       BusPendingActivationEntry *entry = link->data;
1080       DBusList *next = _dbus_list_get_next_link (&pending_activation->entries, link);
1081       
1082       if (dbus_connection_get_is_connected (entry->connection))
1083         {
1084           if (!bus_transaction_send_error_reply (transaction,
1085                                                  entry->connection,
1086                                                  how,
1087                                                  entry->activation_message))
1088             goto error;
1089         }
1090       
1091       link = next;
1092     }
1093
1094   bus_transaction_execute_and_free (transaction);
1095   
1096   return TRUE;
1097
1098  error:
1099   if (transaction)
1100     bus_transaction_cancel_and_free (transaction);
1101   return FALSE;
1102 }
1103
1104 /**
1105  * Free the pending activation and send an error message to all the
1106  * connections that were waiting for it.
1107  */
1108 static void
1109 pending_activation_failed (BusPendingActivation *pending_activation,
1110                            const DBusError      *how)
1111 {
1112   /* FIXME use preallocated OOM messages instead of bus_wait_for_memory() */
1113   while (!try_send_activation_failure (pending_activation, how))
1114     _dbus_wait_for_memory ();
1115
1116   /* Destroy this pending activation */
1117   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1118                                   pending_activation->service_name);
1119 }
1120
1121 static dbus_bool_t
1122 babysitter_watch_callback (DBusWatch     *watch,
1123                            unsigned int   condition,
1124                            void          *data)
1125 {
1126   BusPendingActivation *pending_activation = data;
1127   dbus_bool_t retval;
1128   DBusBabysitter *babysitter;
1129
1130   babysitter = pending_activation->babysitter;
1131   
1132   _dbus_babysitter_ref (babysitter);
1133   
1134   retval = dbus_watch_handle (watch, condition);
1135
1136   /* FIXME this is broken in the same way that
1137    * connection watches used to be; there should be
1138    * a separate callback for status change, instead
1139    * of doing "if we handled a watch status might
1140    * have changed"
1141    *
1142    * Fixing this lets us move dbus_watch_handle
1143    * calls into dbus-mainloop.c
1144    */
1145   
1146   if (_dbus_babysitter_get_child_exited (babysitter))
1147     {
1148       DBusError error;
1149       DBusHashIter iter;
1150       
1151       dbus_error_init (&error);
1152       _dbus_babysitter_set_child_exit_error (babysitter, &error);
1153
1154       /* Destroy all pending activations with the same exec */
1155       _dbus_hash_iter_init (pending_activation->activation->pending_activations,
1156                             &iter);
1157       while (_dbus_hash_iter_next (&iter))
1158         {
1159           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1160          
1161           if (p != pending_activation && strcmp (p->exec, pending_activation->exec) == 0)
1162             pending_activation_failed (p, &error);
1163         }
1164       
1165       /* Destroys the pending activation */
1166       pending_activation_failed (pending_activation, &error);
1167
1168       dbus_error_free (&error);
1169     }
1170   
1171   _dbus_babysitter_unref (babysitter);
1172
1173   return retval;
1174 }
1175
1176 static dbus_bool_t
1177 add_babysitter_watch (DBusWatch      *watch,
1178                       void           *data)
1179 {
1180   BusPendingActivation *pending_activation = data;
1181
1182   return _dbus_loop_add_watch (bus_context_get_loop (pending_activation->activation->context),
1183                                watch, babysitter_watch_callback, pending_activation,
1184                                NULL);
1185 }
1186
1187 static void
1188 remove_babysitter_watch (DBusWatch      *watch,
1189                          void           *data)
1190 {
1191   BusPendingActivation *pending_activation = data;
1192   
1193   _dbus_loop_remove_watch (bus_context_get_loop (pending_activation->activation->context),
1194                            watch, babysitter_watch_callback, pending_activation);
1195 }
1196
1197 static dbus_bool_t
1198 pending_activation_timed_out (void *data)
1199 {
1200   BusPendingActivation *pending_activation = data;
1201   DBusError error;
1202   
1203   /* Kill the spawned process, since it sucks
1204    * (not sure this is what we want to do, but
1205    * may as well try it for now)
1206    */
1207   if (pending_activation->babysitter) 
1208     _dbus_babysitter_kill_child (pending_activation->babysitter);
1209
1210   dbus_error_init (&error);
1211
1212   dbus_set_error (&error, DBUS_ERROR_TIMED_OUT,
1213                   "Activation of %s timed out",
1214                   pending_activation->service_name);
1215
1216   pending_activation_failed (pending_activation, &error);
1217
1218   dbus_error_free (&error);
1219
1220   return TRUE;
1221 }
1222
1223 static void
1224 cancel_pending (void *data)
1225 {
1226   BusPendingActivation *pending_activation = data;
1227
1228   _dbus_verbose ("Canceling pending activation of %s\n",
1229                  pending_activation->service_name);
1230
1231   if (pending_activation->babysitter)
1232     _dbus_babysitter_kill_child (pending_activation->babysitter);
1233   
1234   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1235                                   pending_activation->service_name);
1236 }
1237
1238 static void
1239 free_pending_cancel_data (void *data)
1240 {
1241   BusPendingActivation *pending_activation = data;
1242   
1243   bus_pending_activation_unref (pending_activation);
1244 }
1245
1246 static dbus_bool_t
1247 add_cancel_pending_to_transaction (BusTransaction       *transaction,
1248                                    BusPendingActivation *pending_activation)
1249 {  
1250   if (!bus_transaction_add_cancel_hook (transaction, cancel_pending,
1251                                         pending_activation,
1252                                         free_pending_cancel_data))
1253     return FALSE;
1254
1255   bus_pending_activation_ref (pending_activation); 
1256   
1257   _dbus_verbose ("Saved pending activation to be canceled if the transaction fails\n");
1258   
1259   return TRUE;
1260 }
1261
1262 static dbus_bool_t 
1263 update_service_cache (BusActivation *activation, DBusError *error)
1264 {
1265   DBusHashIter iter;
1266  
1267   _dbus_hash_iter_init (activation->directories, &iter);
1268   while (_dbus_hash_iter_next (&iter))
1269     {
1270       DBusError tmp_error;
1271       BusServiceDirectory *s_dir;
1272
1273       s_dir = _dbus_hash_iter_get_value (&iter);
1274
1275       dbus_error_init (&tmp_error);
1276       if (!update_directory (activation, s_dir, &tmp_error))
1277         {
1278           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
1279             {
1280               dbus_move_error (&tmp_error, error);
1281               return FALSE;
1282             }
1283
1284           dbus_error_free (&tmp_error);
1285           continue;
1286         }
1287     }
1288   
1289   return TRUE;
1290 }
1291
1292 static BusActivationEntry *
1293 activation_find_entry (BusActivation *activation, 
1294                        const char    *service_name,
1295                        DBusError     *error)
1296 {
1297   BusActivationEntry *entry;
1298   
1299   entry = _dbus_hash_table_lookup_string (activation->entries, service_name);
1300   if (!entry)
1301     { 
1302       if (!update_service_cache (activation, error)) 
1303         return NULL;
1304
1305       entry = _dbus_hash_table_lookup_string (activation->entries,
1306                                               service_name);
1307     }
1308   else 
1309     {
1310       BusActivationEntry *updated_entry;
1311
1312       if (!check_service_file (activation, entry, &updated_entry, error)) 
1313         return NULL;
1314
1315       entry = updated_entry;
1316     }
1317
1318   if (!entry) 
1319     {
1320       dbus_set_error (error, DBUS_ERROR_SERVICE_UNKNOWN,
1321                       "The name %s was not provided by any .service files",
1322                       service_name);
1323       return NULL;
1324     }
1325
1326   return entry;
1327 }
1328
1329 dbus_bool_t
1330 bus_activation_activate_service (BusActivation  *activation,
1331                                  DBusConnection *connection,
1332                                  BusTransaction *transaction,
1333                                  dbus_bool_t     auto_activation,
1334                                  DBusMessage    *activation_message,
1335                                  const char     *service_name,
1336                                  DBusError      *error)
1337 {
1338   BusActivationEntry *entry;
1339   BusPendingActivation *pending_activation;
1340   BusPendingActivationEntry *pending_activation_entry;
1341   DBusMessage *message;
1342   DBusString service_str;
1343   char **argv;
1344   char **envp = NULL;
1345   int argc;
1346   dbus_bool_t retval;
1347   DBusHashIter iter;
1348   dbus_bool_t activated;
1349   
1350   activated = TRUE;
1351
1352   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1353
1354   if (activation->n_pending_activations >=
1355       bus_context_get_max_pending_activations (activation->context))
1356     {
1357       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1358                       "The maximum number of pending activations has been reached, activation of %s failed",
1359                       service_name);
1360       return FALSE;
1361     }
1362
1363   entry = activation_find_entry (activation, service_name, error);
1364   if (!entry) 
1365     return FALSE;
1366
1367   /* Bypass the registry lookup if we're auto-activating, bus_dispatch would not
1368    * call us if the service is already active.
1369    */
1370   if (!auto_activation)
1371     {
1372       /* Check if the service is active */
1373       _dbus_string_init_const (&service_str, service_name);
1374       if (bus_registry_lookup (bus_context_get_registry (activation->context), &service_str) != NULL)
1375         {
1376           dbus_uint32_t result;
1377           
1378           _dbus_verbose ("Service \"%s\" is already active\n", service_name);
1379       
1380           message = dbus_message_new_method_return (activation_message);
1381
1382           if (!message)
1383             {
1384               _dbus_verbose ("No memory to create reply to activate message\n");
1385               BUS_SET_OOM (error);
1386               return FALSE;
1387             }
1388
1389           result = DBUS_START_REPLY_ALREADY_RUNNING;
1390           
1391           if (!dbus_message_append_args (message,
1392                                          DBUS_TYPE_UINT32, &result,
1393                                          DBUS_TYPE_INVALID))
1394             {
1395               _dbus_verbose ("No memory to set args of reply to activate message\n");
1396               BUS_SET_OOM (error);
1397               dbus_message_unref (message);
1398               return FALSE;
1399             }
1400
1401           retval = bus_transaction_send_from_driver (transaction, connection, message);
1402           dbus_message_unref (message);
1403           if (!retval)
1404             {
1405               _dbus_verbose ("Failed to send reply\n");
1406               BUS_SET_OOM (error);
1407             }
1408
1409           return retval;
1410         }
1411     }
1412   
1413   pending_activation_entry = dbus_new0 (BusPendingActivationEntry, 1);
1414   if (!pending_activation_entry)
1415     {
1416       _dbus_verbose ("Failed to create pending activation entry\n");
1417       BUS_SET_OOM (error);
1418       return FALSE;
1419     }
1420
1421   pending_activation_entry->auto_activation = auto_activation;
1422
1423   pending_activation_entry->activation_message = activation_message;
1424   dbus_message_ref (activation_message);
1425   pending_activation_entry->connection = connection;
1426   dbus_connection_ref (connection);
1427   
1428   /* Check if the service is being activated */
1429   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1430   if (pending_activation)
1431     {
1432       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1433         {
1434           _dbus_verbose ("Failed to append a new entry to pending activation\n");
1435           
1436           BUS_SET_OOM (error);
1437           bus_pending_activation_entry_free (pending_activation_entry);
1438           return FALSE;
1439         }
1440
1441       pending_activation->n_entries += 1;
1442       pending_activation->activation->n_pending_activations += 1;
1443     }
1444   else
1445     {
1446       pending_activation = dbus_new0 (BusPendingActivation, 1);
1447       if (!pending_activation)
1448         {
1449           _dbus_verbose ("Failed to create pending activation\n");
1450           
1451           BUS_SET_OOM (error);
1452           bus_pending_activation_entry_free (pending_activation_entry);          
1453           return FALSE;
1454         }
1455
1456       pending_activation->activation = activation;
1457       pending_activation->refcount = 1;
1458       
1459       pending_activation->service_name = _dbus_strdup (service_name);
1460       if (!pending_activation->service_name)
1461         {
1462           _dbus_verbose ("Failed to copy service name for pending activation\n");
1463           
1464           BUS_SET_OOM (error);
1465           bus_pending_activation_unref (pending_activation);
1466           bus_pending_activation_entry_free (pending_activation_entry);          
1467           return FALSE;
1468         }
1469
1470       pending_activation->exec = _dbus_strdup (entry->exec);
1471       if (!pending_activation->exec)
1472         {
1473           _dbus_verbose ("Failed to copy service exec for pending activation\n");
1474           BUS_SET_OOM (error);
1475           bus_pending_activation_unref (pending_activation);
1476           bus_pending_activation_entry_free (pending_activation_entry);
1477           return FALSE;
1478         }
1479
1480       pending_activation->timeout =
1481         _dbus_timeout_new (bus_context_get_activation_timeout (activation->context),
1482                            pending_activation_timed_out,
1483                            pending_activation,
1484                            NULL);
1485       if (!pending_activation->timeout)
1486         {
1487           _dbus_verbose ("Failed to create timeout for pending activation\n");
1488           
1489           BUS_SET_OOM (error);
1490           bus_pending_activation_unref (pending_activation);
1491           bus_pending_activation_entry_free (pending_activation_entry);
1492           return FALSE;
1493         }
1494
1495       if (!_dbus_loop_add_timeout (bus_context_get_loop (activation->context),
1496                                    pending_activation->timeout,
1497                                    handle_timeout_callback,
1498                                    pending_activation,
1499                                    NULL))
1500         {
1501           _dbus_verbose ("Failed to add timeout for pending activation\n");
1502           
1503           BUS_SET_OOM (error);
1504           bus_pending_activation_unref (pending_activation);
1505           bus_pending_activation_entry_free (pending_activation_entry);          
1506           return FALSE;
1507         }
1508
1509       pending_activation->timeout_added = TRUE;
1510       
1511       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1512         {
1513           _dbus_verbose ("Failed to add entry to just-created pending activation\n");
1514           
1515           BUS_SET_OOM (error);
1516           bus_pending_activation_unref (pending_activation);
1517           bus_pending_activation_entry_free (pending_activation_entry);          
1518           return FALSE;
1519         }
1520
1521       pending_activation->n_entries += 1;
1522       pending_activation->activation->n_pending_activations += 1;
1523     
1524       activated = FALSE;
1525       _dbus_hash_iter_init (activation->pending_activations, &iter);
1526       while (_dbus_hash_iter_next (&iter))
1527         {
1528           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1529           
1530           if (strcmp (p->exec, entry->exec) == 0) 
1531             {
1532               activated = TRUE;
1533               break;
1534             }
1535         }
1536      
1537       if (!_dbus_hash_table_insert_string (activation->pending_activations,
1538                                            pending_activation->service_name,
1539                                            pending_activation))
1540         {
1541           _dbus_verbose ("Failed to put pending activation in hash table\n");
1542           
1543           BUS_SET_OOM (error);
1544           bus_pending_activation_unref (pending_activation);
1545           return FALSE;
1546         }
1547     }
1548   
1549   if (!add_cancel_pending_to_transaction (transaction, pending_activation))
1550     {
1551       _dbus_verbose ("Failed to add pending activation cancel hook to transaction\n");
1552       BUS_SET_OOM (error);
1553       _dbus_hash_table_remove_string (activation->pending_activations,
1554                                       pending_activation->service_name);
1555
1556       return FALSE;
1557     }
1558   
1559   if (activated)
1560     return TRUE;
1561
1562   /* Now try to spawn the process */
1563   if (!_dbus_shell_parse_argv (entry->exec, &argc, &argv, error))
1564     {
1565       _dbus_verbose ("Failed to parse command line: %s\n", entry->exec);
1566       _DBUS_ASSERT_ERROR_IS_SET (error);
1567       
1568       _dbus_hash_table_remove_string (activation->pending_activations,
1569                                       pending_activation->service_name);
1570
1571       return FALSE;
1572     }
1573
1574   _dbus_verbose ("Spawning %s ...\n", argv[0]);
1575   if (!_dbus_spawn_async_with_babysitter (&pending_activation->babysitter, argv,
1576                                           envp,
1577                                           child_setup, activation, 
1578                                           error))
1579     {
1580       _dbus_verbose ("Failed to spawn child\n");
1581       _DBUS_ASSERT_ERROR_IS_SET (error);
1582       dbus_free_string_array (argv);
1583
1584       return FALSE;
1585     }
1586
1587   dbus_free_string_array (argv);
1588
1589   _dbus_assert (pending_activation->babysitter != NULL);
1590   
1591   if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
1592                                              add_babysitter_watch,
1593                                              remove_babysitter_watch,
1594                                              NULL,
1595                                              pending_activation,
1596                                              NULL))
1597     {
1598       BUS_SET_OOM (error);
1599       _dbus_verbose ("Failed to set babysitter watch functions\n");
1600       return FALSE;
1601     }
1602   
1603   return TRUE;
1604 }
1605
1606 dbus_bool_t
1607 bus_activation_list_services (BusActivation *activation,
1608                               char        ***listp,
1609                               int           *array_len)
1610 {
1611   int i, j, len;
1612   char **retval;
1613   DBusHashIter iter;
1614
1615   len = _dbus_hash_table_get_n_entries (activation->entries);
1616   retval = dbus_new (char *, len + 1);
1617
1618   if (retval == NULL)
1619     return FALSE;
1620
1621   _dbus_hash_iter_init (activation->entries, &iter);
1622   i = 0;
1623   while (_dbus_hash_iter_next (&iter))
1624     {
1625       BusActivationEntry *entry = _dbus_hash_iter_get_value (&iter);
1626
1627       retval[i] = _dbus_strdup (entry->name);
1628       if (retval[i] == NULL)
1629         goto error;
1630
1631       i++;
1632     }
1633
1634   retval[i] = NULL;
1635
1636   if (array_len)
1637     *array_len = len;
1638
1639   *listp = retval;
1640   return TRUE;
1641
1642  error:
1643   for (j = 0; j < i; j++)
1644     dbus_free (retval[i]);
1645   dbus_free (retval);
1646
1647   return FALSE;
1648 }
1649   
1650
1651 #ifdef DBUS_BUILD_TESTS
1652
1653 #include <stdio.h>
1654
1655 #define SERVICE_NAME_1 "MyService1"
1656 #define SERVICE_NAME_2 "MyService2"
1657 #define SERVICE_NAME_3 "MyService3"
1658
1659 #define SERVICE_FILE_1 "service-1.service"
1660 #define SERVICE_FILE_2 "service-2.service"
1661 #define SERVICE_FILE_3 "service-3.service"
1662
1663 static dbus_bool_t
1664 test_create_service_file (DBusString *dir,
1665                           const char *filename, 
1666                           const char *name, 
1667                           const char *exec)
1668 {
1669   DBusString  file_name, full_path;
1670   FILE        *file;
1671   dbus_bool_t  ret_val;
1672
1673   ret_val = TRUE;
1674   _dbus_string_init_const (&file_name, filename);
1675
1676   if (!_dbus_string_init (&full_path))
1677     return FALSE;
1678
1679   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
1680       !_dbus_concat_dir_and_file (&full_path, &file_name))
1681     {
1682       ret_val = FALSE;
1683       goto out;
1684     }
1685   
1686   file = fopen (_dbus_string_get_const_data (&full_path), "w");
1687   if (!file)
1688     {
1689       ret_val = FALSE;
1690       goto out;
1691     }
1692
1693   fprintf (file, "[D-BUS Service]\nName=%s\nExec=%s\n", name, exec);
1694   fclose (file);
1695
1696 out:
1697   _dbus_string_free (&full_path);
1698   return ret_val;
1699 }
1700
1701 static dbus_bool_t
1702 test_remove_service_file (DBusString *dir, const char *filename)
1703 {
1704   DBusString  file_name, full_path;
1705   dbus_bool_t ret_val;
1706   
1707   ret_val = TRUE;
1708  
1709   _dbus_string_init_const (&file_name, filename);
1710
1711   if (!_dbus_string_init (&full_path))
1712     return FALSE;
1713
1714   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
1715       !_dbus_concat_dir_and_file (&full_path, &file_name))
1716     {
1717       ret_val = FALSE;
1718       goto out;
1719     }
1720
1721   if (!_dbus_delete_file (&full_path, NULL))
1722     {
1723       ret_val = FALSE;
1724       goto out;
1725     }
1726
1727 out:
1728   _dbus_string_free (&full_path);
1729   return ret_val;
1730 }
1731
1732 static dbus_bool_t
1733 test_remove_directory (DBusString *dir)
1734 {
1735   DBusDirIter *iter;
1736   DBusString   filename, full_path;
1737   dbus_bool_t  ret_val;
1738   
1739   ret_val = TRUE;
1740   
1741   if (!_dbus_string_init (&filename))
1742     return FALSE;
1743
1744   if (!_dbus_string_init (&full_path))
1745     {
1746       _dbus_string_free (&filename);
1747       return FALSE;
1748     }
1749     
1750   iter = _dbus_directory_open (dir, NULL);
1751   if (iter == NULL)
1752     {
1753       ret_val = FALSE;
1754       goto out;
1755     }
1756   
1757   while (_dbus_directory_get_next_file (iter, &filename, NULL)) 
1758     {
1759       if (!test_remove_service_file (dir, _dbus_string_get_const_data (&filename)))
1760         {
1761           ret_val = FALSE;
1762           goto out;
1763         }
1764     }
1765   _dbus_directory_close (iter);
1766
1767   if (!_dbus_delete_directory (dir, NULL))
1768     {
1769       ret_val = FALSE;
1770       goto out;
1771     }
1772
1773 out:
1774   _dbus_string_free (&filename);
1775   _dbus_string_free (&full_path);
1776
1777   return ret_val;
1778 }
1779
1780 static dbus_bool_t
1781 init_service_reload_test (DBusString *dir)
1782 {
1783   DBusStat stat_buf;
1784  
1785   if (!_dbus_stat (dir, &stat_buf, NULL))
1786     {
1787       if (!_dbus_create_directory (dir, NULL))
1788         return FALSE;
1789     }
1790   else 
1791     {
1792       if (!test_remove_directory (dir))
1793         return FALSE;
1794
1795       if (!_dbus_create_directory (dir, NULL))
1796         return FALSE;
1797     }
1798
1799   /* Create one initial file */
1800   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_1, "exec-1"))
1801     return FALSE;
1802
1803   return TRUE;
1804 }
1805
1806 static dbus_bool_t
1807 cleanup_service_reload_test (DBusString *dir)
1808 {
1809   if (!test_remove_directory (dir))
1810     return FALSE;
1811
1812   return TRUE;
1813 }
1814
1815 typedef struct 
1816 {
1817   BusActivation *activation;
1818   const char    *service_name;
1819   dbus_bool_t    expecting_find;
1820 } CheckData;
1821
1822 static dbus_bool_t
1823 check_func (void *data)
1824 {
1825   CheckData          *d;
1826   BusActivationEntry *entry;
1827   DBusError           error;
1828   dbus_bool_t         ret_val;
1829   
1830   ret_val = TRUE;
1831   d = data;
1832   
1833   dbus_error_init (&error);
1834  
1835   entry = activation_find_entry (d->activation, d->service_name, &error);
1836   if (entry == NULL)
1837     {
1838       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY)) 
1839         {
1840           ret_val = TRUE;
1841         }
1842       else
1843         {
1844           if (d->expecting_find)
1845             ret_val = FALSE;
1846         }
1847       
1848       dbus_error_free (&error);
1849     }
1850   else 
1851     {
1852       if (!d->expecting_find)
1853         ret_val = FALSE;
1854     }
1855
1856   return ret_val;
1857 }
1858
1859 static dbus_bool_t
1860 do_test (const char *description, dbus_bool_t oom_test, CheckData *data)
1861 {
1862   dbus_bool_t err;
1863
1864   if (oom_test)
1865     err = !_dbus_test_oom_handling (description, check_func, data);
1866   else
1867     err = !check_func (data);
1868
1869   if (err) 
1870     _dbus_assert_not_reached ("Test failed");
1871
1872   return TRUE;
1873 }
1874
1875 static dbus_bool_t
1876 do_service_reload_test (DBusString *dir, dbus_bool_t oom_test)
1877 {
1878   BusActivation *activation;
1879   DBusString     address;
1880   DBusList      *directories;
1881   CheckData      d;
1882   
1883   directories = NULL;
1884   _dbus_string_init_const (&address, "");
1885  
1886   if (!_dbus_list_append (&directories, _dbus_string_get_data (dir)))
1887     return FALSE; 
1888
1889   activation = bus_activation_new (NULL, &address, &directories, NULL);
1890   if (!activation)
1891     return FALSE;
1892
1893   d.activation = activation;
1894   
1895   /* Check for existing service file */
1896   d.expecting_find = TRUE;
1897   d.service_name = SERVICE_NAME_1;
1898
1899   if (!do_test ("Existing service file", oom_test, &d))
1900     return FALSE;
1901
1902   /* Check for non-existing service file */
1903   d.expecting_find = FALSE;
1904   d.service_name = SERVICE_NAME_3;
1905
1906   if (!do_test ("Nonexisting service file", oom_test, &d))
1907     return FALSE;
1908
1909   /* Check for added service file */
1910   if (!test_create_service_file (dir, SERVICE_FILE_2, SERVICE_NAME_2, "exec-2"))
1911     return FALSE;
1912
1913   d.expecting_find = TRUE;
1914   d.service_name = SERVICE_NAME_2;
1915   
1916   if (!do_test ("Added service file", oom_test, &d))
1917     return FALSE;
1918   
1919   /* Check for removed service file */
1920   if (!test_remove_service_file (dir, SERVICE_FILE_2))
1921     return FALSE;
1922
1923   d.expecting_find = FALSE;
1924   d.service_name = SERVICE_FILE_2;
1925
1926   if (!do_test ("Removed service file", oom_test, &d))
1927     return FALSE;
1928   
1929   /* Check for updated service file */
1930   
1931   _dbus_sleep_milliseconds (1000); /* Sleep a second to make sure the mtime is updated */
1932
1933   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_3, "exec-3"))
1934     return FALSE;
1935
1936   d.expecting_find = TRUE;
1937   d.service_name = SERVICE_NAME_3;
1938
1939   if (!do_test ("Updated service file, part 1", oom_test, &d))
1940     return FALSE;
1941
1942   d.expecting_find = FALSE;
1943   d.service_name = SERVICE_NAME_1;
1944
1945   if (!do_test ("Updated service file, part 2", oom_test, &d))
1946     return FALSE; 
1947
1948   bus_activation_unref (activation);
1949   _dbus_list_clear (&directories);
1950
1951   return TRUE;
1952 }
1953
1954 dbus_bool_t
1955 bus_activation_service_reload_test (const DBusString *test_data_dir)
1956 {
1957   DBusString directory;
1958
1959   if (!_dbus_string_init (&directory))
1960     return FALSE;
1961   
1962   if (!_dbus_string_append (&directory, _dbus_get_tmpdir()))
1963     return FALSE;
1964   
1965   if (!_dbus_string_append (&directory, "/dbus-reload-test-") ||
1966       !_dbus_generate_random_ascii (&directory, 6))
1967      {
1968        return FALSE;
1969      }
1970    
1971   /* Do normal tests */
1972   if (!init_service_reload_test (&directory))
1973     _dbus_assert_not_reached ("could not initiate service reload test");
1974  
1975   if (!do_service_reload_test (&directory, FALSE))
1976     ; /* Do nothing? */
1977   
1978   /* Do OOM tests */
1979   if (!init_service_reload_test (&directory))
1980     _dbus_assert_not_reached ("could not initiate service reload test");
1981  
1982   if (!do_service_reload_test (&directory, TRUE))
1983     ; /* Do nothing? */
1984  
1985   /* Cleanup test directory */
1986   if (!cleanup_service_reload_test (&directory))
1987     return FALSE;
1988   
1989   _dbus_string_free (&directory);
1990   
1991   return TRUE;
1992 }
1993
1994 #endif /* DBUS_BUILD_TESTS */