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