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