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 /**
1122  * Depending on the exit code of the helper, set the error accordingly
1123  */
1124 static void
1125 handle_activation_exit_error (int exit_code, DBusError *error)
1126 {
1127   switch (exit_code)
1128     {
1129     case BUS_SPAWN_EXIT_CODE_NO_MEMORY:
1130       dbus_set_error (error, DBUS_ERROR_SPAWN_SETUP_FAILED,
1131                       "Launcher could not run as out of memory");
1132       break;
1133     case BUS_SPAWN_EXIT_CODE_SETUP_FAILED:
1134       dbus_set_error (error, DBUS_ERROR_SPAWN_SETUP_FAILED,
1135                       "Failed to setup environment correctly");
1136       break;
1137     case BUS_SPAWN_EXIT_CODE_NAME_INVALID:
1138       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_INVALID,
1139                       "Bus name is not valid or missing");
1140       break;
1141     case BUS_SPAWN_EXIT_CODE_SERVICE_NOT_FOUND:
1142       dbus_set_error (error, DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND,
1143                       "Bus name not found in system service directory");
1144       break;
1145     case BUS_SPAWN_EXIT_CODE_PERMISSIONS_INVALID:
1146       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1147                       "The permission of the setuid helper is not correct");
1148       break;
1149     case BUS_SPAWN_EXIT_CODE_FILE_INVALID:
1150       dbus_set_error (error, DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,
1151                       "The service file is incorrect or does not have all required attributes");
1152       break;
1153     case BUS_SPAWN_EXIT_CODE_EXEC_FAILED:
1154       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
1155                       "Cannot launch daemon, file not found or permissions invalid");
1156       break;
1157     default:
1158       dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
1159                       "Launch helper exited with unknown return code %i", exit_code);
1160       break;
1161     }
1162 }
1163
1164 static dbus_bool_t
1165 babysitter_watch_callback (DBusWatch     *watch,
1166                            unsigned int   condition,
1167                            void          *data)
1168 {
1169   BusPendingActivation *pending_activation = data;
1170   dbus_bool_t retval;
1171   DBusBabysitter *babysitter;
1172
1173   babysitter = pending_activation->babysitter;
1174   
1175   _dbus_babysitter_ref (babysitter);
1176   
1177   retval = dbus_watch_handle (watch, condition);
1178
1179   /* FIXME this is broken in the same way that
1180    * connection watches used to be; there should be
1181    * a separate callback for status change, instead
1182    * of doing "if we handled a watch status might
1183    * have changed"
1184    *
1185    * Fixing this lets us move dbus_watch_handle
1186    * calls into dbus-mainloop.c
1187    */
1188   
1189   if (_dbus_babysitter_get_child_exited (babysitter))
1190     {
1191       DBusError error;
1192       DBusHashIter iter;
1193       
1194       dbus_error_init (&error);
1195       _dbus_babysitter_set_child_exit_error (babysitter, &error);
1196
1197       /* refine the error code if we got an exit code */
1198       if (dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED))
1199         {
1200           int exit_code = 0;
1201           if (_dbus_babysitter_get_child_exit_status (babysitter, &exit_code))
1202             {
1203               dbus_error_free (&error);
1204               handle_activation_exit_error (exit_code, &error);
1205             }
1206         }
1207
1208       /* Destroy all pending activations with the same exec */
1209       _dbus_hash_iter_init (pending_activation->activation->pending_activations,
1210                             &iter);
1211       while (_dbus_hash_iter_next (&iter))
1212         {
1213           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1214          
1215           if (p != pending_activation && strcmp (p->exec, pending_activation->exec) == 0)
1216             pending_activation_failed (p, &error);
1217         }
1218       
1219       /* Destroys the pending activation */
1220       pending_activation_failed (pending_activation, &error);
1221
1222       dbus_error_free (&error);
1223     }
1224   
1225   _dbus_babysitter_unref (babysitter);
1226
1227   return retval;
1228 }
1229
1230 static dbus_bool_t
1231 add_babysitter_watch (DBusWatch      *watch,
1232                       void           *data)
1233 {
1234   BusPendingActivation *pending_activation = data;
1235
1236   return _dbus_loop_add_watch (bus_context_get_loop (pending_activation->activation->context),
1237                                watch, babysitter_watch_callback, pending_activation,
1238                                NULL);
1239 }
1240
1241 static void
1242 remove_babysitter_watch (DBusWatch      *watch,
1243                          void           *data)
1244 {
1245   BusPendingActivation *pending_activation = data;
1246   
1247   _dbus_loop_remove_watch (bus_context_get_loop (pending_activation->activation->context),
1248                            watch, babysitter_watch_callback, pending_activation);
1249 }
1250
1251 static dbus_bool_t
1252 pending_activation_timed_out (void *data)
1253 {
1254   BusPendingActivation *pending_activation = data;
1255   DBusError error;
1256   
1257   /* Kill the spawned process, since it sucks
1258    * (not sure this is what we want to do, but
1259    * may as well try it for now)
1260    */
1261   if (pending_activation->babysitter) 
1262     _dbus_babysitter_kill_child (pending_activation->babysitter);
1263
1264   dbus_error_init (&error);
1265
1266   dbus_set_error (&error, DBUS_ERROR_TIMED_OUT,
1267                   "Activation of %s timed out",
1268                   pending_activation->service_name);
1269
1270   pending_activation_failed (pending_activation, &error);
1271
1272   dbus_error_free (&error);
1273
1274   return TRUE;
1275 }
1276
1277 static void
1278 cancel_pending (void *data)
1279 {
1280   BusPendingActivation *pending_activation = data;
1281
1282   _dbus_verbose ("Canceling pending activation of %s\n",
1283                  pending_activation->service_name);
1284
1285   if (pending_activation->babysitter)
1286     _dbus_babysitter_kill_child (pending_activation->babysitter);
1287   
1288   _dbus_hash_table_remove_string (pending_activation->activation->pending_activations,
1289                                   pending_activation->service_name);
1290 }
1291
1292 static void
1293 free_pending_cancel_data (void *data)
1294 {
1295   BusPendingActivation *pending_activation = data;
1296   
1297   bus_pending_activation_unref (pending_activation);
1298 }
1299
1300 static dbus_bool_t
1301 add_cancel_pending_to_transaction (BusTransaction       *transaction,
1302                                    BusPendingActivation *pending_activation)
1303 {  
1304   if (!bus_transaction_add_cancel_hook (transaction, cancel_pending,
1305                                         pending_activation,
1306                                         free_pending_cancel_data))
1307     return FALSE;
1308
1309   bus_pending_activation_ref (pending_activation); 
1310   
1311   _dbus_verbose ("Saved pending activation to be canceled if the transaction fails\n");
1312   
1313   return TRUE;
1314 }
1315
1316 static dbus_bool_t 
1317 update_service_cache (BusActivation *activation, DBusError *error)
1318 {
1319   DBusHashIter iter;
1320  
1321   _dbus_hash_iter_init (activation->directories, &iter);
1322   while (_dbus_hash_iter_next (&iter))
1323     {
1324       DBusError tmp_error;
1325       BusServiceDirectory *s_dir;
1326
1327       s_dir = _dbus_hash_iter_get_value (&iter);
1328
1329       dbus_error_init (&tmp_error);
1330       if (!update_directory (activation, s_dir, &tmp_error))
1331         {
1332           if (dbus_error_has_name (&tmp_error, DBUS_ERROR_NO_MEMORY))
1333             {
1334               dbus_move_error (&tmp_error, error);
1335               return FALSE;
1336             }
1337
1338           dbus_error_free (&tmp_error);
1339           continue;
1340         }
1341     }
1342   
1343   return TRUE;
1344 }
1345
1346 static BusActivationEntry *
1347 activation_find_entry (BusActivation *activation, 
1348                        const char    *service_name,
1349                        DBusError     *error)
1350 {
1351   BusActivationEntry *entry;
1352   
1353   entry = _dbus_hash_table_lookup_string (activation->entries, service_name);
1354   if (!entry)
1355     { 
1356       if (!update_service_cache (activation, error)) 
1357         return NULL;
1358
1359       entry = _dbus_hash_table_lookup_string (activation->entries,
1360                                               service_name);
1361     }
1362   else 
1363     {
1364       BusActivationEntry *updated_entry;
1365
1366       if (!check_service_file (activation, entry, &updated_entry, error)) 
1367         return NULL;
1368
1369       entry = updated_entry;
1370     }
1371
1372   if (!entry) 
1373     {
1374       dbus_set_error (error, DBUS_ERROR_SERVICE_UNKNOWN,
1375                       "The name %s was not provided by any .service files",
1376                       service_name);
1377       return NULL;
1378     }
1379
1380   return entry;
1381 }
1382
1383 dbus_bool_t
1384 bus_activation_activate_service (BusActivation  *activation,
1385                                  DBusConnection *connection,
1386                                  BusTransaction *transaction,
1387                                  dbus_bool_t     auto_activation,
1388                                  DBusMessage    *activation_message,
1389                                  const char     *service_name,
1390                                  DBusError      *error)
1391 {
1392   BusActivationEntry *entry;
1393   BusPendingActivation *pending_activation;
1394   BusPendingActivationEntry *pending_activation_entry;
1395   DBusMessage *message;
1396   DBusString service_str;
1397   const char *servicehelper;
1398   char **argv;
1399   char **envp = NULL;
1400   int argc;
1401   dbus_bool_t retval;
1402   DBusHashIter iter;
1403   dbus_bool_t activated;
1404   DBusString command;
1405   
1406   activated = TRUE;
1407
1408   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1409
1410   if (activation->n_pending_activations >=
1411       bus_context_get_max_pending_activations (activation->context))
1412     {
1413       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1414                       "The maximum number of pending activations has been reached, activation of %s failed",
1415                       service_name);
1416       return FALSE;
1417     }
1418
1419   entry = activation_find_entry (activation, service_name, error);
1420   if (!entry) 
1421     return FALSE;
1422
1423   /* Bypass the registry lookup if we're auto-activating, bus_dispatch would not
1424    * call us if the service is already active.
1425    */
1426   if (!auto_activation)
1427     {
1428       /* Check if the service is active */
1429       _dbus_string_init_const (&service_str, service_name);
1430       if (bus_registry_lookup (bus_context_get_registry (activation->context), &service_str) != NULL)
1431         {
1432           dbus_uint32_t result;
1433           
1434           _dbus_verbose ("Service \"%s\" is already active\n", service_name);
1435       
1436           message = dbus_message_new_method_return (activation_message);
1437
1438           if (!message)
1439             {
1440               _dbus_verbose ("No memory to create reply to activate message\n");
1441               BUS_SET_OOM (error);
1442               return FALSE;
1443             }
1444
1445           result = DBUS_START_REPLY_ALREADY_RUNNING;
1446           
1447           if (!dbus_message_append_args (message,
1448                                          DBUS_TYPE_UINT32, &result,
1449                                          DBUS_TYPE_INVALID))
1450             {
1451               _dbus_verbose ("No memory to set args of reply to activate message\n");
1452               BUS_SET_OOM (error);
1453               dbus_message_unref (message);
1454               return FALSE;
1455             }
1456
1457           retval = bus_transaction_send_from_driver (transaction, connection, message);
1458           dbus_message_unref (message);
1459           if (!retval)
1460             {
1461               _dbus_verbose ("Failed to send reply\n");
1462               BUS_SET_OOM (error);
1463             }
1464
1465           return retval;
1466         }
1467     }
1468   
1469   pending_activation_entry = dbus_new0 (BusPendingActivationEntry, 1);
1470   if (!pending_activation_entry)
1471     {
1472       _dbus_verbose ("Failed to create pending activation entry\n");
1473       BUS_SET_OOM (error);
1474       return FALSE;
1475     }
1476
1477   pending_activation_entry->auto_activation = auto_activation;
1478
1479   pending_activation_entry->activation_message = activation_message;
1480   dbus_message_ref (activation_message);
1481   pending_activation_entry->connection = connection;
1482   dbus_connection_ref (connection);
1483   
1484   /* Check if the service is being activated */
1485   pending_activation = _dbus_hash_table_lookup_string (activation->pending_activations, service_name);
1486   if (pending_activation)
1487     {
1488       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1489         {
1490           _dbus_verbose ("Failed to append a new entry to pending activation\n");
1491           
1492           BUS_SET_OOM (error);
1493           bus_pending_activation_entry_free (pending_activation_entry);
1494           return FALSE;
1495         }
1496
1497       pending_activation->n_entries += 1;
1498       pending_activation->activation->n_pending_activations += 1;
1499     }
1500   else
1501     {
1502       pending_activation = dbus_new0 (BusPendingActivation, 1);
1503       if (!pending_activation)
1504         {
1505           _dbus_verbose ("Failed to create pending activation\n");
1506           
1507           BUS_SET_OOM (error);
1508           bus_pending_activation_entry_free (pending_activation_entry);          
1509           return FALSE;
1510         }
1511
1512       pending_activation->activation = activation;
1513       pending_activation->refcount = 1;
1514       
1515       pending_activation->service_name = _dbus_strdup (service_name);
1516       if (!pending_activation->service_name)
1517         {
1518           _dbus_verbose ("Failed to copy service name for pending activation\n");
1519           
1520           BUS_SET_OOM (error);
1521           bus_pending_activation_unref (pending_activation);
1522           bus_pending_activation_entry_free (pending_activation_entry);          
1523           return FALSE;
1524         }
1525
1526       pending_activation->exec = _dbus_strdup (entry->exec);
1527       if (!pending_activation->exec)
1528         {
1529           _dbus_verbose ("Failed to copy service exec for pending activation\n");
1530           BUS_SET_OOM (error);
1531           bus_pending_activation_unref (pending_activation);
1532           bus_pending_activation_entry_free (pending_activation_entry);
1533           return FALSE;
1534         }
1535
1536       pending_activation->timeout =
1537         _dbus_timeout_new (bus_context_get_activation_timeout (activation->context),
1538                            pending_activation_timed_out,
1539                            pending_activation,
1540                            NULL);
1541       if (!pending_activation->timeout)
1542         {
1543           _dbus_verbose ("Failed to create timeout for pending activation\n");
1544           
1545           BUS_SET_OOM (error);
1546           bus_pending_activation_unref (pending_activation);
1547           bus_pending_activation_entry_free (pending_activation_entry);
1548           return FALSE;
1549         }
1550
1551       if (!_dbus_loop_add_timeout (bus_context_get_loop (activation->context),
1552                                    pending_activation->timeout,
1553                                    handle_timeout_callback,
1554                                    pending_activation,
1555                                    NULL))
1556         {
1557           _dbus_verbose ("Failed to add timeout for pending activation\n");
1558           
1559           BUS_SET_OOM (error);
1560           bus_pending_activation_unref (pending_activation);
1561           bus_pending_activation_entry_free (pending_activation_entry);          
1562           return FALSE;
1563         }
1564
1565       pending_activation->timeout_added = TRUE;
1566       
1567       if (!_dbus_list_append (&pending_activation->entries, pending_activation_entry))
1568         {
1569           _dbus_verbose ("Failed to add entry to just-created pending activation\n");
1570           
1571           BUS_SET_OOM (error);
1572           bus_pending_activation_unref (pending_activation);
1573           bus_pending_activation_entry_free (pending_activation_entry);          
1574           return FALSE;
1575         }
1576
1577       pending_activation->n_entries += 1;
1578       pending_activation->activation->n_pending_activations += 1;
1579     
1580       activated = FALSE;
1581       _dbus_hash_iter_init (activation->pending_activations, &iter);
1582       while (_dbus_hash_iter_next (&iter))
1583         {
1584           BusPendingActivation *p = _dbus_hash_iter_get_value (&iter);
1585           
1586           if (strcmp (p->exec, entry->exec) == 0) 
1587             {
1588               activated = TRUE;
1589               break;
1590             }
1591         }
1592      
1593       if (!_dbus_hash_table_insert_string (activation->pending_activations,
1594                                            pending_activation->service_name,
1595                                            pending_activation))
1596         {
1597           _dbus_verbose ("Failed to put pending activation in hash table\n");
1598           
1599           BUS_SET_OOM (error);
1600           bus_pending_activation_unref (pending_activation);
1601           return FALSE;
1602         }
1603     }
1604   
1605   if (!add_cancel_pending_to_transaction (transaction, pending_activation))
1606     {
1607       _dbus_verbose ("Failed to add pending activation cancel hook to transaction\n");
1608       BUS_SET_OOM (error);
1609       _dbus_hash_table_remove_string (activation->pending_activations,
1610                                       pending_activation->service_name);
1611
1612       return FALSE;
1613     }
1614   
1615   if (activated)
1616     return TRUE;
1617
1618   /* use command as system and session different */
1619   if (!_dbus_string_init (&command))
1620     {
1621       BUS_SET_OOM (error);
1622       return FALSE;
1623     }
1624
1625   /* does the bus use a helper? */
1626   servicehelper = bus_context_get_servicehelper (activation->context);
1627   if (servicehelper != NULL)
1628     {
1629       if (entry->user == NULL)
1630         {
1631           _dbus_string_free (&command);
1632           dbus_set_error (error, DBUS_ERROR_SPAWN_FILE_INVALID,
1633                           "Cannot do system-bus activation with no user\n");
1634           return FALSE;
1635         }
1636
1637       /* join the helper path and the service name */
1638       if (!_dbus_string_append (&command, servicehelper))
1639         {
1640           _dbus_string_free (&command);
1641           BUS_SET_OOM (error);
1642           return FALSE;
1643         }
1644       if (!_dbus_string_append (&command, " "))
1645         {
1646           _dbus_string_free (&command);
1647           BUS_SET_OOM (error);
1648           return FALSE;
1649         }
1650       if (!_dbus_string_append (&command, service_name))
1651         {
1652           _dbus_string_free (&command);
1653           BUS_SET_OOM (error);
1654           return FALSE;
1655         }
1656     }
1657   else
1658     {
1659       /* the bus does not use a helper, so we can append arguments with the exec line */
1660       if (!_dbus_string_append (&command, entry->exec))
1661         {
1662           _dbus_string_free (&command);
1663           BUS_SET_OOM (error);
1664           return FALSE;
1665         }
1666     }
1667
1668   /* convert command into arguments */
1669   if (!_dbus_shell_parse_argv (_dbus_string_get_const_data (&command), &argc, &argv, error))
1670     {
1671       _dbus_verbose ("Failed to parse command line: %s\n", entry->exec);
1672       _DBUS_ASSERT_ERROR_IS_SET (error);
1673       
1674       _dbus_hash_table_remove_string (activation->pending_activations,
1675                                       pending_activation->service_name);
1676
1677       _dbus_string_free (&command);
1678       return FALSE;
1679     }
1680   _dbus_string_free (&command);
1681
1682   _dbus_verbose ("Spawning %s ...\n", argv[0]);
1683   if (!_dbus_spawn_async_with_babysitter (&pending_activation->babysitter, argv,
1684                                           envp,
1685                                           child_setup, activation, 
1686                                           error))
1687     {
1688       _dbus_verbose ("Failed to spawn child\n");
1689       _DBUS_ASSERT_ERROR_IS_SET (error);
1690       dbus_free_string_array (argv);
1691
1692       return FALSE;
1693     }
1694
1695   dbus_free_string_array (argv);
1696
1697   _dbus_assert (pending_activation->babysitter != NULL);
1698   
1699   if (!_dbus_babysitter_set_watch_functions (pending_activation->babysitter,
1700                                              add_babysitter_watch,
1701                                              remove_babysitter_watch,
1702                                              NULL,
1703                                              pending_activation,
1704                                              NULL))
1705     {
1706       BUS_SET_OOM (error);
1707       _dbus_verbose ("Failed to set babysitter watch functions\n");
1708       return FALSE;
1709     }
1710   
1711   return TRUE;
1712 }
1713
1714 dbus_bool_t
1715 bus_activation_list_services (BusActivation *activation,
1716                               char        ***listp,
1717                               int           *array_len)
1718 {
1719   int i, j, len;
1720   char **retval;
1721   DBusHashIter iter;
1722
1723   len = _dbus_hash_table_get_n_entries (activation->entries);
1724   retval = dbus_new (char *, len + 1);
1725
1726   if (retval == NULL)
1727     return FALSE;
1728
1729   _dbus_hash_iter_init (activation->entries, &iter);
1730   i = 0;
1731   while (_dbus_hash_iter_next (&iter))
1732     {
1733       BusActivationEntry *entry = _dbus_hash_iter_get_value (&iter);
1734
1735       retval[i] = _dbus_strdup (entry->name);
1736       if (retval[i] == NULL)
1737         goto error;
1738
1739       i++;
1740     }
1741
1742   retval[i] = NULL;
1743
1744   if (array_len)
1745     *array_len = len;
1746
1747   *listp = retval;
1748   return TRUE;
1749
1750  error:
1751   for (j = 0; j < i; j++)
1752     dbus_free (retval[i]);
1753   dbus_free (retval);
1754
1755   return FALSE;
1756 }
1757   
1758
1759 #ifdef DBUS_BUILD_TESTS
1760
1761 #include <stdio.h>
1762
1763 #define SERVICE_NAME_1 "MyService1"
1764 #define SERVICE_NAME_2 "MyService2"
1765 #define SERVICE_NAME_3 "MyService3"
1766
1767 #define SERVICE_FILE_1 "service-1.service"
1768 #define SERVICE_FILE_2 "service-2.service"
1769 #define SERVICE_FILE_3 "service-3.service"
1770
1771 static dbus_bool_t
1772 test_create_service_file (DBusString *dir,
1773                           const char *filename, 
1774                           const char *name, 
1775                           const char *exec)
1776 {
1777   DBusString  file_name, full_path;
1778   FILE        *file;
1779   dbus_bool_t  ret_val;
1780
1781   ret_val = TRUE;
1782   _dbus_string_init_const (&file_name, filename);
1783
1784   if (!_dbus_string_init (&full_path))
1785     return FALSE;
1786
1787   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
1788       !_dbus_concat_dir_and_file (&full_path, &file_name))
1789     {
1790       ret_val = FALSE;
1791       goto out;
1792     }
1793   
1794   file = fopen (_dbus_string_get_const_data (&full_path), "w");
1795   if (!file)
1796     {
1797       ret_val = FALSE;
1798       goto out;
1799     }
1800
1801   fprintf (file, "[D-BUS Service]\nName=%s\nExec=%s\n", name, exec);
1802   fclose (file);
1803
1804 out:
1805   _dbus_string_free (&full_path);
1806   return ret_val;
1807 }
1808
1809 static dbus_bool_t
1810 test_remove_service_file (DBusString *dir, const char *filename)
1811 {
1812   DBusString  file_name, full_path;
1813   dbus_bool_t ret_val;
1814   
1815   ret_val = TRUE;
1816  
1817   _dbus_string_init_const (&file_name, filename);
1818
1819   if (!_dbus_string_init (&full_path))
1820     return FALSE;
1821
1822   if (!_dbus_string_append (&full_path, _dbus_string_get_const_data (dir)) ||
1823       !_dbus_concat_dir_and_file (&full_path, &file_name))
1824     {
1825       ret_val = FALSE;
1826       goto out;
1827     }
1828
1829   if (!_dbus_delete_file (&full_path, NULL))
1830     {
1831       ret_val = FALSE;
1832       goto out;
1833     }
1834
1835 out:
1836   _dbus_string_free (&full_path);
1837   return ret_val;
1838 }
1839
1840 static dbus_bool_t
1841 test_remove_directory (DBusString *dir)
1842 {
1843   DBusDirIter *iter;
1844   DBusString   filename, full_path;
1845   dbus_bool_t  ret_val;
1846   
1847   ret_val = TRUE;
1848   
1849   if (!_dbus_string_init (&filename))
1850     return FALSE;
1851
1852   if (!_dbus_string_init (&full_path))
1853     {
1854       _dbus_string_free (&filename);
1855       return FALSE;
1856     }
1857     
1858   iter = _dbus_directory_open (dir, NULL);
1859   if (iter == NULL)
1860     {
1861       ret_val = FALSE;
1862       goto out;
1863     }
1864   
1865   while (_dbus_directory_get_next_file (iter, &filename, NULL)) 
1866     {
1867       if (!test_remove_service_file (dir, _dbus_string_get_const_data (&filename)))
1868         {
1869           ret_val = FALSE;
1870           goto out;
1871         }
1872     }
1873   _dbus_directory_close (iter);
1874
1875   if (!_dbus_delete_directory (dir, NULL))
1876     {
1877       ret_val = FALSE;
1878       goto out;
1879     }
1880
1881 out:
1882   _dbus_string_free (&filename);
1883   _dbus_string_free (&full_path);
1884
1885   return ret_val;
1886 }
1887
1888 static dbus_bool_t
1889 init_service_reload_test (DBusString *dir)
1890 {
1891   DBusStat stat_buf;
1892  
1893   if (!_dbus_stat (dir, &stat_buf, NULL))
1894     {
1895       if (!_dbus_create_directory (dir, NULL))
1896         return FALSE;
1897     }
1898   else 
1899     {
1900       if (!test_remove_directory (dir))
1901         return FALSE;
1902
1903       if (!_dbus_create_directory (dir, NULL))
1904         return FALSE;
1905     }
1906
1907   /* Create one initial file */
1908   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_1, "exec-1"))
1909     return FALSE;
1910
1911   return TRUE;
1912 }
1913
1914 static dbus_bool_t
1915 cleanup_service_reload_test (DBusString *dir)
1916 {
1917   if (!test_remove_directory (dir))
1918     return FALSE;
1919
1920   return TRUE;
1921 }
1922
1923 typedef struct 
1924 {
1925   BusActivation *activation;
1926   const char    *service_name;
1927   dbus_bool_t    expecting_find;
1928 } CheckData;
1929
1930 static dbus_bool_t
1931 check_func (void *data)
1932 {
1933   CheckData          *d;
1934   BusActivationEntry *entry;
1935   DBusError           error;
1936   dbus_bool_t         ret_val;
1937   
1938   ret_val = TRUE;
1939   d = data;
1940   
1941   dbus_error_init (&error);
1942  
1943   entry = activation_find_entry (d->activation, d->service_name, &error);
1944   if (entry == NULL)
1945     {
1946       if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY)) 
1947         {
1948           ret_val = TRUE;
1949         }
1950       else
1951         {
1952           if (d->expecting_find)
1953             ret_val = FALSE;
1954         }
1955       
1956       dbus_error_free (&error);
1957     }
1958   else 
1959     {
1960       if (!d->expecting_find)
1961         ret_val = FALSE;
1962     }
1963
1964   return ret_val;
1965 }
1966
1967 static dbus_bool_t
1968 do_test (const char *description, dbus_bool_t oom_test, CheckData *data)
1969 {
1970   dbus_bool_t err;
1971
1972   if (oom_test)
1973     err = !_dbus_test_oom_handling (description, check_func, data);
1974   else
1975     err = !check_func (data);
1976
1977   if (err) 
1978     _dbus_assert_not_reached ("Test failed");
1979
1980   return TRUE;
1981 }
1982
1983 static dbus_bool_t
1984 do_service_reload_test (DBusString *dir, dbus_bool_t oom_test)
1985 {
1986   BusActivation *activation;
1987   DBusString     address;
1988   DBusList      *directories;
1989   CheckData      d;
1990   
1991   directories = NULL;
1992   _dbus_string_init_const (&address, "");
1993  
1994   if (!_dbus_list_append (&directories, _dbus_string_get_data (dir)))
1995     return FALSE; 
1996
1997   activation = bus_activation_new (NULL, &address, &directories, NULL);
1998   if (!activation)
1999     return FALSE;
2000
2001   d.activation = activation;
2002   
2003   /* Check for existing service file */
2004   d.expecting_find = TRUE;
2005   d.service_name = SERVICE_NAME_1;
2006
2007   if (!do_test ("Existing service file", oom_test, &d))
2008     return FALSE;
2009
2010   /* Check for non-existing service file */
2011   d.expecting_find = FALSE;
2012   d.service_name = SERVICE_NAME_3;
2013
2014   if (!do_test ("Nonexisting service file", oom_test, &d))
2015     return FALSE;
2016
2017   /* Check for added service file */
2018   if (!test_create_service_file (dir, SERVICE_FILE_2, SERVICE_NAME_2, "exec-2"))
2019     return FALSE;
2020
2021   d.expecting_find = TRUE;
2022   d.service_name = SERVICE_NAME_2;
2023   
2024   if (!do_test ("Added service file", oom_test, &d))
2025     return FALSE;
2026   
2027   /* Check for removed service file */
2028   if (!test_remove_service_file (dir, SERVICE_FILE_2))
2029     return FALSE;
2030
2031   d.expecting_find = FALSE;
2032   d.service_name = SERVICE_FILE_2;
2033
2034   if (!do_test ("Removed service file", oom_test, &d))
2035     return FALSE;
2036   
2037   /* Check for updated service file */
2038   
2039   _dbus_sleep_milliseconds (1000); /* Sleep a second to make sure the mtime is updated */
2040
2041   if (!test_create_service_file (dir, SERVICE_FILE_1, SERVICE_NAME_3, "exec-3"))
2042     return FALSE;
2043
2044   d.expecting_find = TRUE;
2045   d.service_name = SERVICE_NAME_3;
2046
2047   if (!do_test ("Updated service file, part 1", oom_test, &d))
2048     return FALSE;
2049
2050   d.expecting_find = FALSE;
2051   d.service_name = SERVICE_NAME_1;
2052
2053   if (!do_test ("Updated service file, part 2", oom_test, &d))
2054     return FALSE; 
2055
2056   bus_activation_unref (activation);
2057   _dbus_list_clear (&directories);
2058
2059   return TRUE;
2060 }
2061
2062 dbus_bool_t
2063 bus_activation_service_reload_test (const DBusString *test_data_dir)
2064 {
2065   DBusString directory;
2066
2067   if (!_dbus_string_init (&directory))
2068     return FALSE;
2069   
2070   if (!_dbus_string_append (&directory, _dbus_get_tmpdir()))
2071     return FALSE;
2072   
2073   if (!_dbus_string_append (&directory, "/dbus-reload-test-") ||
2074       !_dbus_generate_random_ascii (&directory, 6))
2075      {
2076        return FALSE;
2077      }
2078    
2079   /* Do normal tests */
2080   if (!init_service_reload_test (&directory))
2081     _dbus_assert_not_reached ("could not initiate service reload test");
2082  
2083   if (!do_service_reload_test (&directory, FALSE))
2084     ; /* Do nothing? */
2085   
2086   /* Do OOM tests */
2087   if (!init_service_reload_test (&directory))
2088     _dbus_assert_not_reached ("could not initiate service reload test");
2089  
2090   if (!do_service_reload_test (&directory, TRUE))
2091     ; /* Do nothing? */
2092  
2093   /* Cleanup test directory */
2094   if (!cleanup_service_reload_test (&directory))
2095     return FALSE;
2096   
2097   _dbus_string_free (&directory);
2098   
2099   return TRUE;
2100 }
2101
2102 #endif /* DBUS_BUILD_TESTS */