c30fc57c78b8d509201c316cb8479b1f2fa59536
[oweals/gnunet.git] / src / arm / gnunet-service-arm.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file arm/gnunet-service-arm.c
23  * @brief the automated restart manager service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_arm_service.h"
29 #include "gnunet_protocols.h"
30 #include "arm.h"
31
32 /**
33  * List of our services.
34  */
35 struct ServiceList;
36
37
38 /**
39  * Record with information about a listen socket we have open.
40  */
41 struct ServiceListeningInfo
42 {
43   /**
44    * This is a linked list.
45    */
46   struct ServiceListeningInfo *next;
47
48   /**
49    * This is a linked list.
50    */
51   struct ServiceListeningInfo *prev;
52
53   /**
54    * Address this socket is listening on.
55    */
56   struct sockaddr *service_addr;
57
58   /**
59    * Service this listen socket is for.
60    */
61   struct ServiceList *sl;
62
63   /**
64    * Number of bytes in 'service_addr'
65    */
66   socklen_t service_addr_len;
67
68   /**
69    * Our listening socket.
70    */
71   struct GNUNET_NETWORK_Handle *listen_socket;
72
73   /**
74    * Task doing the accepting.
75    */
76   GNUNET_SCHEDULER_TaskIdentifier accept_task;
77
78 };
79
80
81 /**
82  * List of our services.
83  */
84 struct ServiceList
85 {
86   /**
87    * This is a doubly-linked list.
88    */
89   struct ServiceList *next;
90
91   /**
92    * This is a doubly-linked list.
93    */
94   struct ServiceList *prev;
95
96   /**
97    * Linked list of listen sockets associated with this service.
98    */
99   struct ServiceListeningInfo *listen_head;
100
101   /**
102    * Linked list of listen sockets associated with this service.
103    */
104   struct ServiceListeningInfo *listen_tail;
105
106   /**
107    * Name of the service.
108    */
109   char *name;
110
111   /**
112    * Name of the binary used.
113    */
114   char *binary;
115
116   /**
117    * Name of the configuration file used.
118    */
119   char *config;
120
121   /**
122    * Client to notify upon kill completion (waitpid), NULL
123    * if we should simply restart the process.
124    */
125   struct GNUNET_SERVER_Client *killing_client;
126
127   /**
128    * Process structure pointer of the child.
129    */
130   struct GNUNET_OS_Process *proc;
131
132   /**
133    * Process exponential backoff time
134    */
135   struct GNUNET_TIME_Relative backoff;
136
137   /**
138    * Absolute time at which the process is scheduled to restart in case of death
139    */
140   struct GNUNET_TIME_Absolute restart_at;
141
142   /**
143    * Time we asked the service to shut down (used to calculate time it took
144    * the service to terminate).
145    */
146   struct GNUNET_TIME_Absolute killed_at;
147
148   /**
149    * Is this service to be started by default (or did a client tell us explicitly
150    * to start it)?  GNUNET_NO if the service is started only upon 'accept' on a
151    * listen socket or possibly explicitly by a client changing the value.
152    */
153   int is_default;
154
155   /**
156    * Should we use pipes to signal this process? (YES for Java binaries and if we
157    * are on Windoze).
158    */
159   int pipe_control;
160 };
161
162 /**
163  * List of running services.
164  */
165 static struct ServiceList *running_head;
166
167 /**
168  * List of running services.
169  */
170 static struct ServiceList *running_tail;
171
172 /**
173  * Our configuration
174  */
175 static const struct GNUNET_CONFIGURATION_Handle *cfg;
176
177 /**
178  * Command to prepend to each actual command.
179  */
180 static char *prefix_command;
181
182 /**
183  * Option to append to each actual command.
184  */
185 static char *final_option;
186
187 /**
188  * ID of task called whenever we get a SIGCHILD.
189  */
190 static GNUNET_SCHEDULER_TaskIdentifier child_death_task;
191
192 /**
193  * ID of task called whenever the timeout for restarting a child
194  * expires.
195  */
196 static GNUNET_SCHEDULER_TaskIdentifier child_restart_task;
197
198 /**
199  * Pipe used to communicate shutdown via signal.
200  */
201 static struct GNUNET_DISK_PipeHandle *sigpipe;
202
203 /**
204  * Are we in shutdown mode?
205  */
206 static int in_shutdown;
207
208 /**
209  * Handle to our server instance.  Our server is a bit special in that
210  * its service is not immediately stopped once we get a shutdown
211  * request (since we need to continue service until all of our child
212  * processes are dead).  This handle is used to shut down the server
213  * (and thus trigger process termination) once all child processes are
214  * also dead.  A special option in the ARM configuration modifies the
215  * behaviour of the service implementation to not do the shutdown
216  * immediately.
217  */
218 static struct GNUNET_SERVER_Handle *server;
219
220
221 #include "do_start_process.c"
222
223
224 /**
225  * Actually start the process for the given service.
226  *
227  * @param sl identifies service to start
228  */
229 static void
230 start_process (struct ServiceList *sl)
231 {
232   char *loprefix;
233   char *options;
234   char *optpos;
235   char *optend;
236   const char *next;
237   int use_debug;
238   char b;
239   char *val;
240   struct ServiceListeningInfo *sli;
241   SOCKTYPE *lsocks;
242   unsigned int ls;
243   char *binary;
244
245   /* calculate listen socket list */
246   lsocks = NULL;
247   ls = 0;
248   for (sli = sl->listen_head; NULL != sli; sli = sli->next)
249     {
250       GNUNET_array_append (lsocks, ls,
251                            GNUNET_NETWORK_get_fd (sli->listen_socket));
252       if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
253         {
254           GNUNET_SCHEDULER_cancel (sli->accept_task);
255           sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
256         }
257     }
258 #if WINDOWS
259   GNUNET_array_append (lsocks, ls, INVALID_SOCKET);
260 #else
261   GNUNET_array_append (lsocks, ls, -1);
262 #endif
263
264   /* obtain configuration */
265   if (GNUNET_OK !=
266       GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "PREFIX",
267                                              &loprefix))
268     loprefix = GNUNET_strdup (prefix_command);
269   if (GNUNET_OK !=
270       GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "OPTIONS",
271                                              &options))
272     {
273       options = GNUNET_strdup (final_option);
274       if (NULL == strstr (options, "%"))
275         {
276           /* replace '{}' with service name */
277           while (NULL != (optpos = strstr (options, "{}")))
278             {
279               optpos[0] = '%';
280               optpos[1] = 's';
281               GNUNET_asprintf (&optpos, options, sl->name);
282               GNUNET_free (options);
283               options = optpos;
284             }
285           /* replace '$PATH' with value associated with "PATH" */
286           while (NULL != (optpos = strstr (options, "$")))
287             {
288               optend = optpos + 1;
289               while (isupper ((unsigned char) *optend))
290                 optend++;
291               b = *optend;
292               if ('\0' == b)
293                 next = "";
294               else
295                 next = optend + 1;
296               *optend = '\0';
297               if (GNUNET_OK !=
298                   GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
299                                                          optpos + 1, &val))
300                 val = GNUNET_strdup ("");
301               *optpos = '\0';
302               GNUNET_asprintf (&optpos, "%s%s%c%s", options, val, b, next);
303               GNUNET_free (options);
304               GNUNET_free (val);
305               options = optpos;
306             }
307         }
308     }
309   use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG");
310
311   /* actually start process */
312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
313               "Starting service `%s' using binary `%s' and configuration `%s'\n",
314               sl->name, sl->binary, sl->config);
315   binary = GNUNET_OS_get_libexec_binary_path (sl->binary);
316   GNUNET_assert (NULL == sl->proc);
317   if (GNUNET_YES == use_debug)
318     sl->proc =
319       do_start_process (sl->pipe_control, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
320                         lsocks, loprefix, binary, "-c", sl->config, "-L",
321                         "DEBUG", options, NULL);
322   else
323     sl->proc =
324       do_start_process (sl->pipe_control, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
325                         lsocks, loprefix, binary, "-c", sl->config,
326                         options, NULL);
327   GNUNET_free (binary);
328   if (sl->proc == NULL)
329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to start service `%s'\n"),
330                 sl->name);
331   else
332     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting service `%s'\n"),
333                 sl->name);
334   /* clean up */
335   GNUNET_free (loprefix);
336   GNUNET_free (options);
337   GNUNET_array_grow (lsocks, ls, 0);
338 }
339
340
341 /**
342  * Transmit a status result message.
343  *
344  * @param cls pointer to "unit16_t*" with message type
345  * @param size number of bytes available in buf
346  * @param buf where to copy the message, NULL on error
347  * @return number of bytes copied to buf
348  */
349 static size_t
350 write_result (void *cls, size_t size, void *buf)
351 {
352   enum GNUNET_ARM_ProcessStatus *res = cls;
353   struct GNUNET_ARM_ResultMessage *msg;
354
355   if (buf == NULL)
356   {
357     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
358                 _("Could not send status result to client\n"));
359     return 0;                   /* error, not much we can do */
360   }
361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362               "Sending status response %u to client\n", (unsigned int) *res);
363   GNUNET_assert (size >= sizeof (struct GNUNET_ARM_ResultMessage));
364   msg = buf;
365   msg->header.size = htons (sizeof (struct GNUNET_ARM_ResultMessage));
366   msg->header.type = htons (GNUNET_MESSAGE_TYPE_ARM_RESULT);
367   msg->status = htonl ((uint32_t) (*res));
368   GNUNET_free (res);
369   return sizeof (struct GNUNET_ARM_ResultMessage);
370 }
371
372 /**
373  * Transmit the list of running services.
374  * 
375  * @param cls pointer to struct GNUNET_ARM_ListResultMessage with the message
376  * @param size number of bytes available in buf
377  * @param buf where to copy the message, NULL on error
378  * @return number of bytes copied to buf
379  */
380 static size_t
381 write_list_result (void *cls, size_t size, void *buf)
382 {
383   struct GNUNET_ARM_ListResultMessage *msg = cls;
384   struct GNUNET_ARM_ListResultMessage *rslt;
385   size_t rslt_size;
386   
387   if (buf == NULL)
388   {
389     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
390                 _("Could not send list result to client\n"));
391     return 0;                   /* error, not much we can do */
392   }
393   
394   GNUNET_assert (size >= msg->header.size);
395   rslt = buf;
396   rslt->header.size = htons (msg->header.size);
397   rslt->header.type = htons (msg->header.type);
398   rslt->count = htons (msg->count);
399   
400   size_t list_size = msg->header.size 
401                      - sizeof (struct GNUNET_ARM_ListResultMessage);  
402   memcpy (&rslt[1], &msg[1], list_size);
403
404   rslt_size = msg->header.size;
405   GNUNET_free (msg);
406   return rslt_size;
407 }
408
409
410 /**
411  * Signal our client that we will start or stop the
412  * service.
413  *
414  * @param client who is being signalled
415  * @param name name of the service
416  * @param result message type to send
417  * @return NULL if it was not found
418  */
419 static void
420 signal_result (struct GNUNET_SERVER_Client *client, const char *name,
421                enum GNUNET_ARM_ProcessStatus result)
422 {
423   enum GNUNET_ARM_ProcessStatus *res;
424
425   if (NULL == client)
426     return;
427   /* FIXME: this is not super-clean yet... */
428   res = GNUNET_malloc (sizeof (enum GNUNET_ARM_ProcessStatus));
429   *res = result;
430   GNUNET_SERVER_notify_transmit_ready (client,
431                                        sizeof (struct
432                                                GNUNET_ARM_ResultMessage),
433                                        GNUNET_TIME_UNIT_FOREVER_REL,
434                                        &write_result, res);
435   GNUNET_SERVER_receive_done (client, GNUNET_OK);
436 }
437
438
439 /**
440  * Find the process with the given service
441  * name in the given list and return it.
442  *
443  * @param name which service entry to look up
444  * @return NULL if it was not found
445  */
446 static struct ServiceList *
447 find_service (const char *name)
448 {
449   struct ServiceList *sl;
450
451   sl = running_head;
452   while (sl != NULL)
453     {
454       if (0 == strcasecmp (sl->name, name))
455         return sl;
456       sl = sl->next;
457     }
458   return NULL;
459 }
460
461
462 /**
463  * First connection has come to the listening socket associated with the service,
464  * create the service in order to relay the incoming connection to it
465  *
466  * @param cls callback data, struct ServiceListeningInfo describing a listen socket
467  * @param tc context
468  */
469 static void
470 accept_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
471 {
472   struct ServiceListeningInfo *sli = cls;
473   struct ServiceList *sl = sli->sl;
474
475   sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
476   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
477     return;
478   start_process (sl);
479 }
480
481
482 /**
483  * Creating a listening socket for each of the service's addresses and
484  * wait for the first incoming connection to it
485  *
486  * @param sa address associated with the service
487  * @param addr_len length of sa
488  * @param sl service entry for the service in question
489  */
490 static void
491 create_listen_socket (struct sockaddr *sa, socklen_t addr_len,
492                       struct ServiceList *sl)
493 {
494   static int on = 1;
495   struct GNUNET_NETWORK_Handle *sock;
496   struct ServiceListeningInfo *sli;
497
498   switch (sa->sa_family)
499     {
500     case AF_INET:
501       sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0);
502       break;
503     case AF_INET6:
504       sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
505       break;
506     case AF_UNIX:
507       if (strcmp (GNUNET_a2s (sa, addr_len), "@") == 0) /* Do not bind to blank UNIX path! */
508         return;
509       sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
510       break;
511     default:
512       GNUNET_break (0);
513       sock = NULL;
514       errno = EAFNOSUPPORT;
515       break;
516     }
517   if (NULL == sock)
518     {
519       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
520                   _("Unable to create socket for service `%s': %s\n"),
521                   sl->name, STRERROR (errno));
522       GNUNET_free (sa);
523       return;
524     }
525   if (GNUNET_NETWORK_socket_setsockopt
526       (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
527     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
528                          "setsockopt");
529 #ifdef IPV6_V6ONLY
530   if ((sa->sa_family == AF_INET6) &&
531       (GNUNET_NETWORK_socket_setsockopt
532        (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
533     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
534                          "setsockopt");
535 #endif
536
537   if (GNUNET_NETWORK_socket_bind
538       (sock, (const struct sockaddr *) sa, addr_len) != GNUNET_OK)
539     {
540       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
541                   _
542                   ("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
543                   sl->name, GNUNET_a2s (sa, addr_len), STRERROR (errno));
544       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
545       GNUNET_free (sa);
546       return;
547     }
548   if (GNUNET_NETWORK_socket_listen (sock, 5) != GNUNET_OK)
549     {
550       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
551       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
552       GNUNET_free (sa);
553       return;
554     }
555   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
556               _("ARM now monitors connections to service `%s' at `%s'\n"),
557               sl->name, GNUNET_a2s (sa, addr_len));
558   sli = GNUNET_malloc (sizeof (struct ServiceListeningInfo));
559   sli->service_addr = sa;
560   sli->service_addr_len = addr_len;
561   sli->listen_socket = sock;
562   sli->sl = sl;
563   sli->accept_task =
564     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
565                                    &accept_connection, sli);
566   GNUNET_CONTAINER_DLL_insert (sl->listen_head, sl->listen_tail, sli);
567 }
568
569
570 /**
571  * Remove and free an entry in the service list.  Listen sockets
572  * must have already been cleaned up.  Only to be called during shutdown.
573  *
574  * @param sl entry to free
575  */
576 static void
577 free_service (struct ServiceList *sl)
578 {
579   GNUNET_assert (GNUNET_YES == in_shutdown);
580   GNUNET_CONTAINER_DLL_remove (running_head, running_tail, sl);
581   GNUNET_assert (NULL == sl->listen_head);
582   GNUNET_free_non_null (sl->config);
583   GNUNET_free_non_null (sl->binary);
584   GNUNET_free (sl->name);
585   GNUNET_free (sl);
586 }
587
588
589 /**
590  * Handle START-message.
591  *
592  * @param cls closure (always NULL)
593  * @param client identification of the client
594  * @param message the actual message
595  * @return GNUNET_OK to keep the connection open,
596  *         GNUNET_SYSERR to close it (signal serious error)
597  */
598 static void
599 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
600               const struct GNUNET_MessageHeader *message)
601 {
602   const char *servicename;
603   struct ServiceList *sl;
604   uint16_t size;
605   
606   size = ntohs (message->size);
607   size -= sizeof (struct GNUNET_MessageHeader);
608   servicename = (const char *) &message[1];
609   if ((size == 0) || (servicename[size - 1] != '\0'))
610     {
611       GNUNET_break (0);
612       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
613       return;
614     }
615   if (GNUNET_YES == in_shutdown)
616     {
617       signal_result (client, servicename, GNUNET_ARM_PROCESS_SHUTDOWN);
618       return;
619     }
620   sl = find_service (servicename);
621   if (NULL == sl)
622     {
623       signal_result (client, servicename, GNUNET_ARM_PROCESS_UNKNOWN);
624       return;
625     }
626   sl->is_default = GNUNET_YES;
627   if (sl->proc != NULL)
628     {
629       signal_result (client, servicename, GNUNET_ARM_PROCESS_ALREADY_RUNNING);
630       return;
631     }
632   start_process (sl);
633   signal_result (client, servicename, GNUNET_ARM_PROCESS_STARTING);
634 }
635
636
637 /**
638  * Handle STOP-message.
639  *
640  * @param cls closure (always NULL)
641  * @param client identification of the client
642  * @param message the actual message
643  * @return GNUNET_OK to keep the connection open,
644  *         GNUNET_SYSERR to close it (signal serious error)
645  */
646 static void
647 handle_stop (void *cls, struct GNUNET_SERVER_Client *client,
648              const struct GNUNET_MessageHeader *message)
649 {
650   struct ServiceList *sl;
651   const char *servicename;
652   uint16_t size;
653
654   size = ntohs (message->size);
655   size -= sizeof (struct GNUNET_MessageHeader);
656   servicename = (const char *) &message[1];
657   if ((size == 0) || (servicename[size - 1] != '\0'))
658     {
659       GNUNET_break (0);
660       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
661       return;
662     }
663   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
664               _("Preparing to stop `%s'\n"), servicename);
665   sl = find_service (servicename);
666   if (sl == NULL)
667     {
668       signal_result (client, servicename, GNUNET_ARM_PROCESS_UNKNOWN);
669       return;
670     }
671   sl->is_default = GNUNET_NO;
672   if (GNUNET_YES == in_shutdown)
673     {
674       /* shutdown in progress */
675       signal_result (client, servicename, GNUNET_ARM_PROCESS_SHUTDOWN);
676       return;
677     }
678   if (sl->killing_client != NULL)
679     {
680       /* killing already in progress */
681       signal_result (client, servicename,
682                      GNUNET_ARM_PROCESS_ALREADY_STOPPING);
683       return;
684     }
685   if (sl->proc == NULL)
686     {
687       /* process is down */
688       signal_result (client, servicename, GNUNET_ARM_PROCESS_ALREADY_DOWN);
689       return;
690     }
691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
692               "Sending kill signal to service `%s', waiting for process to die.\n",
693               servicename);
694   sl->killed_at = GNUNET_TIME_absolute_get ();
695   if (0 != GNUNET_OS_process_kill (sl->proc, SIGTERM))
696     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
697   sl->killing_client = client;
698   GNUNET_SERVER_client_keep (client);
699 }
700
701 /**
702  * Handle LIST-message.
703  *
704  * @param cls closure (always NULL)
705  * @param client identification of the client
706  * @param message the actual message
707  */
708 static void
709 handle_list (void *cls, struct GNUNET_SERVER_Client *client,
710              const struct GNUNET_MessageHeader *message)
711 {
712   struct GNUNET_ARM_ListResultMessage *msg;
713   size_t string_list_size;
714   size_t total_size;
715   struct ServiceList *sl;
716   uint16_t count;
717   
718   if (NULL == client)
719     return;
720   
721   count = 0;
722   string_list_size = 0;
723   /* first count the running processes get their name's size */
724   for (sl = running_head; sl != NULL; sl = sl->next)
725   {
726     if (sl->proc != NULL)
727     {
728       string_list_size += strlen (sl->name);
729       string_list_size += strlen (sl->binary);
730       string_list_size += 4;
731       count++;
732     }
733   }
734   total_size = sizeof (struct GNUNET_ARM_ListResultMessage) 
735                + string_list_size;
736   msg = GNUNET_malloc (total_size);
737   msg->header.size = total_size;
738   msg->header.type = GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT;
739   msg->count = count;
740   
741   char *pos = (char *)&msg[1];
742   for (sl = running_head; sl != NULL; sl = sl->next) 
743   {
744     if (sl->proc != NULL)
745     {
746       size_t s = strlen (sl->name) + strlen (sl->binary) + 4;
747       GNUNET_snprintf(pos, s, "%s (%s)", sl->name, sl->binary);
748       pos += s;
749     }
750   }
751   
752   GNUNET_SERVER_notify_transmit_ready (client,
753                                        msg->header.size,
754                                        GNUNET_TIME_UNIT_FOREVER_REL,
755                                        &write_list_result, msg);
756   GNUNET_SERVER_receive_done (client, GNUNET_OK);
757 }
758
759 /**
760  * We are done with everything.  Stop remaining
761  * tasks, signal handler and the server.
762  */
763 static void
764 do_shutdown ()
765 {
766   if (NULL != server)
767     {
768       GNUNET_SERVER_destroy (server);
769       server = NULL;
770     }
771   if (GNUNET_SCHEDULER_NO_TASK != child_death_task)
772     {
773       GNUNET_SCHEDULER_cancel (child_death_task);
774       child_death_task = GNUNET_SCHEDULER_NO_TASK;
775     }
776 }
777
778
779 /**
780  * Task run for shutdown.
781  *
782  * @param cls closure, NULL if we need to self-restart
783  * @param tc context
784  */
785 static void
786 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
787 {
788   struct ServiceList *pos;
789   struct ServiceList *nxt;
790   struct ServiceListeningInfo *sli;
791
792   if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
793   {
794     GNUNET_SCHEDULER_cancel (child_restart_task);
795     child_restart_task = GNUNET_SCHEDULER_NO_TASK;
796   }
797   in_shutdown = GNUNET_YES;
798   /* first, stop listening */
799   for (pos = running_head; NULL != pos; pos = pos->next)
800   {
801     while (NULL != (sli = pos->listen_head))
802       {
803         GNUNET_CONTAINER_DLL_remove (pos->listen_head,
804                                      pos->listen_tail, sli);
805         if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
806           {
807             GNUNET_SCHEDULER_cancel (sli->accept_task);
808             sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
809           }
810         GNUNET_break (GNUNET_OK ==
811                       GNUNET_NETWORK_socket_close (sli->listen_socket));
812         GNUNET_free (sli->service_addr);
813         GNUNET_free (sli);
814       }
815   }
816   /* then, shutdown all existing service processes */
817   nxt = running_head;
818   while (NULL != (pos = nxt))
819   {
820     nxt = pos->next;
821     if (pos->proc != NULL)
822     {
823       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stopping service `%s'\n",
824                   pos->name);
825       pos->killed_at = GNUNET_TIME_absolute_get ();
826       if (0 != GNUNET_OS_process_kill (pos->proc, SIGTERM))
827         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
828     }
829     else
830     {
831       free_service (pos);
832     }
833   }
834   /* finally, should all service processes be already gone, terminate for real */
835   if (running_head == NULL)
836     do_shutdown ();
837 }
838
839
840 /**
841  * Task run whenever it is time to restart a child that died.
842  *
843  * @param cls closure, always NULL
844  * @param tc context
845  */
846 static void
847 delayed_restart_task (void *cls,
848                       const struct GNUNET_SCHEDULER_TaskContext *tc)
849 {
850   struct ServiceList *sl;
851   struct GNUNET_TIME_Relative lowestRestartDelay;
852   struct ServiceListeningInfo *sli;
853
854   child_restart_task = GNUNET_SCHEDULER_NO_TASK;
855   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
856     return;
857   GNUNET_assert (GNUNET_NO == in_shutdown);
858   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
859
860   /* check for services that need to be restarted due to
861    * configuration changes or because the last restart failed */
862   for (sl = running_head; NULL != sl; sl = sl->next)
863   {
864     if (NULL != sl->proc)
865       continue;
866     /* service is currently not running */
867     if (GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value ==
868         0)
869     {
870       /* restart is now allowed */
871       if (sl->is_default)
872       {
873         /* process should run by default, start immediately */
874         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
875                     _("Restarting service `%s'.\n"), sl->name);
876         start_process (sl);
877       }
878       else
879       {
880         /* process is run on-demand, ensure it is re-started if there is demand */
881         for (sli = sl->listen_head; NULL != sli; sli = sli->next)
882           if (GNUNET_SCHEDULER_NO_TASK == sli->accept_task)
883           {
884             /* accept was actually paused, so start it again */
885             sli->accept_task =
886               GNUNET_SCHEDULER_add_read_net
887               (GNUNET_TIME_UNIT_FOREVER_REL, sli->listen_socket,
888                &accept_connection, sli);
889           }
890       }
891     }
892     else
893     {
894       /* update calculation for earliest time to reactivate a service */
895       lowestRestartDelay =
896         GNUNET_TIME_relative_min (lowestRestartDelay,
897                                   GNUNET_TIME_absolute_get_remaining
898                                   (sl->restart_at));
899     }
900   }
901   if (lowestRestartDelay.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
902   {
903     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
904                 "Will restart process in %s\n",
905                 GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay, GNUNET_YES));
906     child_restart_task =
907       GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay,
908                                                   GNUNET_SCHEDULER_PRIORITY_IDLE, 
909                                                   &delayed_restart_task, NULL);
910   }
911 }
912
913
914 /**
915  * Task triggered whenever we receive a SIGCHLD (child
916  * process died).
917  *
918  * @param cls closure, NULL if we need to self-restart
919  * @param tc context
920  */
921 static void
922 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
923 {
924   struct ServiceList *pos;
925   struct ServiceList *next;
926   struct ServiceListeningInfo *sli;
927   const char *statstr;
928   int statcode;
929   int ret;
930   char c[16];
931   enum GNUNET_OS_ProcessStatusType statusType;
932   unsigned long statusCode;
933   const struct GNUNET_DISK_FileHandle *pr;
934
935   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
936   child_death_task = GNUNET_SCHEDULER_NO_TASK;
937   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
938     {
939       /* shutdown scheduled us, ignore! */
940       child_death_task =
941         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
942                                         pr, &maint_child_death, NULL);
943       return;
944     }
945   /* consume the signal */
946   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
947
948   /* check for services that died (WAITPID) */
949   next = running_head;
950   while (NULL != (pos = next))
951     {
952       next = pos->next;
953
954       if (pos->proc == NULL)
955       {
956         if (GNUNET_YES == in_shutdown)
957           free_service (pos);
958         continue;
959       }
960       if ((GNUNET_SYSERR ==
961            (ret =
962             GNUNET_OS_process_status (pos->proc, &statusType, &statusCode)))
963           || ((ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED)
964               || (statusType == GNUNET_OS_PROCESS_RUNNING)))
965         continue;
966       if (statusType == GNUNET_OS_PROCESS_EXITED)
967       {
968         statstr = _( /* process termination method */ "exit");
969         statcode = statusCode;
970       }
971       else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
972       {
973         statstr = _( /* process termination method */ "signal");
974         statcode = statusCode;
975       }
976       else
977       {
978         statstr = _( /* process termination method */ "unknown");
979         statcode = 0;
980       }
981       if (0 != pos->killed_at.abs_value)
982       {
983         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
984                     _("Service `%s' took %s to terminate\n"),
985                     pos->name,
986                     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->killed_at), GNUNET_YES));
987       }
988       GNUNET_OS_process_destroy (pos->proc);
989       pos->proc = NULL;
990       if (NULL != pos->killing_client)
991         {
992           signal_result (pos->killing_client, pos->name,
993                          GNUNET_ARM_PROCESS_DOWN);
994           GNUNET_SERVER_client_drop (pos->killing_client);
995           pos->killing_client = NULL;
996           /* process can still be re-started on-demand, ensure it is re-started if there is demand */
997           for (sli = pos->listen_head; NULL != sli; sli = sli->next)
998             {
999               GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sli->accept_task);
1000               sli->accept_task =
1001                 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1002                                                sli->listen_socket,
1003                                                &accept_connection, sli);
1004             }
1005           continue;
1006         }
1007       if (GNUNET_YES != in_shutdown)
1008         {
1009           if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0))
1010             {
1011               /* process terminated normally, allow restart at any time */
1012               pos->restart_at.abs_value = 0;
1013             }
1014           else
1015             {
1016               if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1017                 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1018                             _
1019                             ("Service `%s' terminated with status %s/%d, will restart in %llu ms\n"),
1020                             pos->name, statstr, statcode, pos->backoff.rel_value);
1021               /* schedule restart */
1022               pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff);
1023               pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff);
1024             }
1025           if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1026             GNUNET_SCHEDULER_cancel (child_restart_task);
1027           child_restart_task =
1028             GNUNET_SCHEDULER_add_with_priority
1029             (GNUNET_SCHEDULER_PRIORITY_IDLE, 
1030              &delayed_restart_task, NULL);
1031         }
1032       else
1033         {
1034           free_service (pos);
1035         }
1036     }
1037   child_death_task =
1038     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1039                                     pr, &maint_child_death, NULL);
1040   if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1041     do_shutdown ();
1042 }
1043
1044
1045 /**
1046  * Handler for SHUTDOWN message.
1047  *
1048  * @param cls closure (refers to service)
1049  * @param client identification of the client
1050  * @param message the actual message
1051  */
1052 static void
1053 handle_shutdown (void *cls, struct GNUNET_SERVER_Client *client,
1054                  const struct GNUNET_MessageHeader *message)
1055 {
1056   GNUNET_SCHEDULER_shutdown ();
1057   GNUNET_SERVER_client_persist_ (client);
1058 }
1059
1060
1061 /**
1062  * Signal handler called for SIGCHLD.  Triggers the
1063  * respective handler by writing to the trigger pipe.
1064  */
1065 static void
1066 sighandler_child_death ()
1067 {
1068   static char c;
1069   int old_errno = errno;        /* back-up errno */
1070
1071   GNUNET_break (1 ==
1072                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
1073                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
1074                                         &c, sizeof (c)));
1075   errno = old_errno;            /* restore errno */
1076 }
1077
1078
1079 /**
1080  * Setup our service record for the given section in the configuration file
1081  * (assuming the section is for a service).
1082  *
1083  * @param cls unused
1084  * @param section a section in the configuration file
1085  * @return GNUNET_OK (continue)
1086  */
1087 static void
1088 setup_service (void *cls, const char *section)
1089 {
1090   struct ServiceList *sl;
1091   char *binary;
1092   char *config;
1093   struct stat sbuf;
1094   struct sockaddr **addrs;
1095   socklen_t *addr_lens;
1096   int ret;
1097   unsigned int i;
1098
1099   if (strcasecmp (section, "arm") == 0)
1100     return;
1101   if (GNUNET_OK !=
1102       GNUNET_CONFIGURATION_get_value_string (cfg, section, "BINARY", &binary))
1103     {
1104       /* not a service section */
1105       return;
1106     }
1107   sl = find_service (section);
1108   if (NULL != sl)
1109   {
1110     /* got the same section twice!? */
1111     GNUNET_break (0);
1112     return;
1113   }
1114   config = NULL;
1115   if (( (GNUNET_OK !=
1116          GNUNET_CONFIGURATION_get_value_filename (cfg, section, "CONFIG",
1117                                                   &config)) &&
1118         (GNUNET_OK !=
1119          GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS", "DEFAULTCONFIG",
1120                                                   &config)) ) ||
1121
1122       (0 != STAT (config, &sbuf)))
1123   {
1124     if (NULL == config)
1125       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, section, "CONFIG");
1126     else
1127       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, 
1128                                  section, "CONFIG",
1129                                  STRERROR (errno));
1130     GNUNET_free (binary);
1131     GNUNET_free_non_null (config);
1132     return;
1133   }
1134   sl = GNUNET_malloc (sizeof (struct ServiceList));
1135   sl->name = GNUNET_strdup (section);
1136   sl->binary = binary;
1137   sl->config = config;
1138   sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1139   sl->restart_at = GNUNET_TIME_UNIT_FOREVER_ABS;
1140 #if WINDOWS
1141   sl->pipe_control = GNUNET_YES;
1142 #else
1143   if (GNUNET_CONFIGURATION_have_value (cfg, section, "PIPECONTROL"))
1144     sl->pipe_control = GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "PIPECONTROL");
1145 #endif  
1146   GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl);
1147   if (GNUNET_YES !=
1148       GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "AUTOSTART"))
1149     return;
1150   if (0 >= (ret = GNUNET_SERVICE_get_server_addresses (section, cfg,
1151                                                        &addrs, &addr_lens)))
1152     return;
1153   /* this will free (or capture) addrs[i] */
1154   for (i = 0; i < ret; i++)
1155     create_listen_socket (addrs[i], addr_lens[i], sl);
1156   GNUNET_free (addrs);
1157   GNUNET_free (addr_lens);
1158 }
1159
1160
1161 /**
1162  * Process arm requests.
1163  *
1164  * @param cls closure
1165  * @param serv the initialized server
1166  * @param c configuration to use
1167  */
1168 static void
1169 run (void *cls, struct GNUNET_SERVER_Handle *serv,
1170      const struct GNUNET_CONFIGURATION_Handle *c)
1171 {
1172   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1173     {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
1174     {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
1175     {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN,
1176      sizeof (struct GNUNET_MessageHeader)},
1177     {&handle_list, NULL, GNUNET_MESSAGE_TYPE_ARM_LIST, 
1178      sizeof (struct GNUNET_MessageHeader)},
1179     {NULL, NULL, 0, 0}
1180   };
1181   char *defaultservices;
1182   const char *pos;
1183   struct ServiceList *sl;
1184
1185   cfg = c;
1186   server = serv;
1187   GNUNET_assert (serv != NULL);
1188   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1189                                 NULL);
1190   child_death_task =
1191     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1192                                     GNUNET_DISK_pipe_handle (sigpipe,
1193                                                              GNUNET_DISK_PIPE_END_READ),
1194                                     &maint_child_death, NULL);
1195
1196   if (GNUNET_OK !=
1197       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX",
1198                                              &prefix_command))
1199     prefix_command = GNUNET_strdup ("");
1200   if (GNUNET_OK !=
1201       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX",
1202                                              &final_option))
1203     final_option = GNUNET_strdup ("");
1204
1205   GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL);
1206
1207   /* start default services... */
1208   if (GNUNET_OK ==
1209       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "DEFAULTSERVICES",
1210                                              &defaultservices))
1211     {
1212       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1213                   _("Starting default services `%s'\n"), defaultservices);
1214       if (0 < strlen (defaultservices))
1215         {
1216           for (pos = strtok (defaultservices, " "); NULL != pos;
1217                pos = strtok (NULL, " "))
1218             {
1219               sl = find_service (pos);
1220               if (NULL == sl)
1221                 {
1222                   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1223                               _
1224                               ("Default service `%s' not configured correctly!\n"),
1225                               pos);
1226                   continue;
1227                 }
1228               sl->is_default = GNUNET_YES;
1229               start_process (sl);
1230             }
1231         }
1232       GNUNET_free (defaultservices);
1233     }
1234   else
1235     {
1236       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1237                   _
1238                   ("No default services configured, GNUnet will not really start right now.\n"));
1239     }
1240
1241   /* process client requests */
1242   GNUNET_SERVER_add_handlers (server, handlers);
1243 }
1244
1245
1246 /**
1247  * The main function for the arm service.
1248  *
1249  * @param argc number of arguments from the command line
1250  * @param argv command line arguments
1251  * @return 0 ok, 1 on error
1252  */
1253 int
1254 main (int argc, char *const *argv)
1255 {
1256   int ret;
1257   struct GNUNET_SIGNAL_Context *shc_chld;
1258
1259   sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
1260   GNUNET_assert (sigpipe != NULL);
1261   shc_chld =
1262     GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
1263   ret =
1264     (GNUNET_OK ==
1265      GNUNET_SERVICE_run (argc, argv, "arm", 
1266                          GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN, &run, NULL)) ? 0 : 1;
1267   GNUNET_SIGNAL_handler_uninstall (shc_chld);
1268   shc_chld = NULL;
1269   GNUNET_DISK_pipe_close (sigpipe);
1270   sigpipe = NULL;
1271   return ret;
1272 }
1273
1274
1275 #ifdef LINUX
1276 #include <malloc.h>
1277
1278 /**
1279  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1280  */
1281 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1282 {
1283   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1284   mallopt (M_TOP_PAD, 1 * 1024);
1285   malloc_trim (0);
1286 }
1287 #endif
1288
1289
1290 /* end of gnunet-service-arm.c */