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