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