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