clean up for configs
[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  * How many messages do we queue up at most for optional
34  * notifications to a client?  (this can cause notifications
35  * about outgoing messages to be dropped).
36  */
37 #define MAX_NOTIFY_QUEUE 1024
38
39
40 /**
41  * List of our services.
42  */
43 struct ServiceList;
44
45
46 /**
47  * Record with information about a listen socket we have open.
48  */
49 struct ServiceListeningInfo
50 {
51   /**
52    * This is a linked list.
53    */
54   struct ServiceListeningInfo *next;
55
56   /**
57    * This is a linked list.
58    */
59   struct ServiceListeningInfo *prev;
60
61   /**
62    * Address this socket is listening on.
63    */
64   struct sockaddr *service_addr;
65
66   /**
67    * Service this listen socket is for.
68    */
69   struct ServiceList *sl;
70
71   /**
72    * Number of bytes in 'service_addr'
73    */
74   socklen_t service_addr_len;
75
76   /**
77    * Our listening socket.
78    */
79   struct GNUNET_NETWORK_Handle *listen_socket;
80
81   /**
82    * Task doing the accepting.
83    */
84   GNUNET_SCHEDULER_TaskIdentifier accept_task;
85
86 };
87
88
89 /**
90  * List of our services.
91  */
92 struct ServiceList
93 {
94   /**
95    * This is a doubly-linked list.
96    */
97   struct ServiceList *next;
98
99   /**
100    * This is a doubly-linked list.
101    */
102   struct ServiceList *prev;
103
104   /**
105    * Linked list of listen sockets associated with this service.
106    */
107   struct ServiceListeningInfo *listen_head;
108
109   /**
110    * Linked list of listen sockets associated with this service.
111    */
112   struct ServiceListeningInfo *listen_tail;
113
114   /**
115    * Name of the service.
116    */
117   char *name;
118
119   /**
120    * Name of the binary used.
121    */
122   char *binary;
123
124   /**
125    * Name of the configuration file used.
126    */
127   char *config;
128
129   /**
130    * Client to notify upon kill completion (waitpid), NULL
131    * if we should simply restart the process.
132    */
133   struct GNUNET_SERVER_Client *killing_client;
134
135   /**
136    * ID of the request that killed the service (for reporting back).
137    */
138   uint64_t killing_client_request_id;
139
140   /**
141    * Process structure pointer of the child.
142    */
143   struct GNUNET_OS_Process *proc;
144
145   /**
146    * Process exponential backoff time
147    */
148   struct GNUNET_TIME_Relative backoff;
149
150   /**
151    * Absolute time at which the process is scheduled to restart in case of death
152    */
153   struct GNUNET_TIME_Absolute restart_at;
154
155   /**
156    * Time we asked the service to shut down (used to calculate time it took
157    * the service to terminate).
158    */
159   struct GNUNET_TIME_Absolute killed_at;
160
161   /**
162    * Is this service to be started by default (or did a client tell us explicitly
163    * to start it)?  #GNUNET_NO if the service is started only upon 'accept' on a
164    * listen socket or possibly explicitly by a client changing the value.
165    */
166   int is_default;
167
168   /**
169    * Should we use pipes to signal this process? (YES for Java binaries and if we
170    * are on Windoze).
171    */
172   int pipe_control;
173 };
174
175 /**
176  * List of running services.
177  */
178 static struct ServiceList *running_head;
179
180 /**
181  * List of running services.
182  */
183 static struct ServiceList *running_tail;
184
185 /**
186  * Our configuration
187  */
188 static const struct GNUNET_CONFIGURATION_Handle *cfg;
189
190 /**
191  * Command to prepend to each actual command.
192  */
193 static char *prefix_command;
194
195 /**
196  * Option to append to each actual command.
197  */
198 static char *final_option;
199
200 /**
201  * ID of task called whenever we get a SIGCHILD.
202  */
203 static GNUNET_SCHEDULER_TaskIdentifier child_death_task;
204
205 /**
206  * ID of task called whenever the timeout for restarting a child
207  * expires.
208  */
209 static GNUNET_SCHEDULER_TaskIdentifier child_restart_task;
210
211 /**
212  * Pipe used to communicate shutdown via signal.
213  */
214 static struct GNUNET_DISK_PipeHandle *sigpipe;
215
216 /**
217  * Are we in shutdown mode?
218  */
219 static int in_shutdown;
220
221 /**
222  * Are we starting user services?
223  */
224 static int start_user = GNUNET_YES;
225
226 /**
227  * Are we starting system services?
228  */
229 static int start_system = GNUNET_YES;
230
231 /**
232  * Handle to our server instance.  Our server is a bit special in that
233  * its service is not immediately stopped once we get a shutdown
234  * request (since we need to continue service until all of our child
235  * processes are dead).  This handle is used to shut down the server
236  * (and thus trigger process termination) once all child processes are
237  * also dead.  A special option in the ARM configuration modifies the
238  * behaviour of the service implementation to not do the shutdown
239  * immediately.
240  */
241 static struct GNUNET_SERVER_Handle *server;
242
243 /**
244  * Context for notifications we need to send to our clients.
245  */
246 static struct GNUNET_SERVER_NotificationContext *notifier;
247
248
249 /**
250  * Transmit a status result message.
251  *
252  * @param cls a `unit16_t *` with message type
253  * @param size number of bytes available in @a buf
254  * @param buf where to copy the message, NULL on error
255  * @return number of bytes copied to @a buf
256  */
257 static size_t
258 write_result (void *cls, size_t size, void *buf)
259 {
260   struct GNUNET_ARM_ResultMessage *msg = cls;
261   size_t msize;
262
263   if (buf == NULL)
264   {
265     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
266                 _("Could not send status result to client\n"));
267     GNUNET_free (msg);
268     return 0;                   /* error, not much we can do */
269   }
270   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
271               "Sending status response %u to client\n",
272               (unsigned int) msg->result);
273   msize = msg->arm_msg.header.size;
274   GNUNET_assert (size >= msize);
275   msg->arm_msg.header.size = htons (msg->arm_msg.header.size);
276   msg->arm_msg.header.type = htons (msg->arm_msg.header.type);
277   msg->result = htonl (msg->result);
278   msg->arm_msg.request_id = GNUNET_htonll (msg->arm_msg.request_id);
279   memcpy (buf, msg, msize);
280   GNUNET_free (msg);
281   return msize;
282 }
283
284
285 /**
286  * Transmit the list of running services.
287  *
288  * @param cls pointer to `struct GNUNET_ARM_ListResultMessage` with the message
289  * @param size number of bytes available in @a buf
290  * @param buf where to copy the message, NULL on error
291  * @return number of bytes copied to @a buf
292  */
293 static size_t
294 write_list_result (void *cls, size_t size, void *buf)
295 {
296   struct GNUNET_ARM_ListResultMessage *msg = cls;
297   size_t rslt_size;
298
299   if (buf == NULL)
300   {
301     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
302                 _("Could not send list result to client\n"));
303     GNUNET_free (msg);
304     return 0;                   /* error, not much we can do */
305   }
306
307   rslt_size = msg->arm_msg.header.size;
308   GNUNET_assert (size >= rslt_size);
309   msg->arm_msg.header.size = htons (msg->arm_msg.header.size);
310   msg->arm_msg.header.type = htons (msg->arm_msg.header.type);
311   msg->arm_msg.request_id = GNUNET_htonll (msg->arm_msg.request_id);
312   msg->count = htons (msg->count);
313
314   memcpy (buf, msg, rslt_size);
315   GNUNET_free (msg);
316   return rslt_size;
317 }
318
319
320 /**
321  * Signal our client that we will start or stop the
322  * service.
323  *
324  * @param client who is being signalled
325  * @param name name of the service
326  * @param request_id id of the request that is being responded to.
327  * @param result message type to send
328  * @return NULL if it was not found
329  */
330 static void
331 signal_result (struct GNUNET_SERVER_Client *client,
332                const char *name,
333                uint64_t request_id,
334                enum GNUNET_ARM_Result result)
335 {
336   struct GNUNET_ARM_ResultMessage *msg;
337   size_t msize;
338
339   msize = sizeof (struct GNUNET_ARM_ResultMessage);
340   msg = GNUNET_malloc (msize);
341   msg->arm_msg.header.size = msize;
342   msg->arm_msg.header.type = GNUNET_MESSAGE_TYPE_ARM_RESULT;
343   msg->result = result;
344   msg->arm_msg.request_id = request_id;
345
346   GNUNET_SERVER_notify_transmit_ready (client, msize,
347                                        GNUNET_TIME_UNIT_FOREVER_REL,
348                                        write_result, msg);
349 }
350
351
352 /**
353  * Tell all clients about status change of a service.
354  *
355  * @param name name of the service
356  * @param status message type to send
357  * @param unicast if not NULL, send to this client only.
358  *                otherwise, send to all clients in the notifier
359  */
360 static void
361 broadcast_status (const char *name,
362                   enum GNUNET_ARM_ServiceStatus status,
363                   struct GNUNET_SERVER_Client *unicast)
364 {
365   struct GNUNET_ARM_StatusMessage *msg;
366   size_t namelen;
367
368   if (NULL == notifier)
369     return;
370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
371       "Sending status %u of service `%s' to client\n",
372       (unsigned int) status, name);
373   namelen = strlen (name);
374   msg = GNUNET_malloc (sizeof (struct GNUNET_ARM_StatusMessage) + namelen + 1);
375   msg->header.size = htons (sizeof (struct GNUNET_ARM_StatusMessage) + namelen + 1);
376   msg->header.type = htons (GNUNET_MESSAGE_TYPE_ARM_STATUS);
377   msg->status = htonl ((uint32_t) (status));
378   memcpy ((char *) &msg[1], name, namelen + 1);
379
380   if (NULL == unicast)
381     GNUNET_SERVER_notification_context_broadcast (notifier,
382         (struct GNUNET_MessageHeader *) msg, GNUNET_YES);
383   else
384     GNUNET_SERVER_notification_context_unicast (notifier, unicast,
385         (const struct GNUNET_MessageHeader *) msg, GNUNET_NO);
386   GNUNET_free (msg);
387 }
388
389
390 /**
391  * Actually start the process for the given service.
392  *
393  * @param sl identifies service to start
394  * @param client that asked to start the service (may be NULL)
395  * @param request_id id of the request in response to which the process is
396  *                   being started. 0 if starting was not requested.
397  */
398 static void
399 start_process (struct ServiceList *sl,
400                struct GNUNET_SERVER_Client *client,
401                uint64_t request_id)
402 {
403   char *loprefix;
404   char *options;
405   char *optpos;
406   char *optend;
407   const char *next;
408   int use_debug;
409   char b;
410   char *val;
411   struct ServiceListeningInfo *sli;
412   SOCKTYPE *lsocks;
413   unsigned int ls;
414   char *binary;
415   char *quotedbinary;
416
417   /* calculate listen socket list */
418   lsocks = NULL;
419   ls = 0;
420   for (sli = sl->listen_head; NULL != sli; sli = sli->next)
421     {
422       GNUNET_array_append (lsocks, ls,
423                            GNUNET_NETWORK_get_fd (sli->listen_socket));
424       if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
425         {
426           GNUNET_SCHEDULER_cancel (sli->accept_task);
427           sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
428         }
429     }
430 #if WINDOWS
431   GNUNET_array_append (lsocks, ls, INVALID_SOCKET);
432 #else
433   GNUNET_array_append (lsocks, ls, -1);
434 #endif
435
436   /* obtain configuration */
437   if (GNUNET_OK !=
438       GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "PREFIX",
439                                              &loprefix))
440     loprefix = GNUNET_strdup (prefix_command);
441   if (GNUNET_OK !=
442       GNUNET_CONFIGURATION_get_value_string (cfg, sl->name, "OPTIONS",
443                                              &options))
444     {
445       options = GNUNET_strdup (final_option);
446       if (NULL == strstr (options, "%"))
447         {
448           /* replace '{}' with service name */
449           while (NULL != (optpos = strstr (options, "{}")))
450             {
451               optpos[0] = '%';
452               optpos[1] = 's';
453               GNUNET_asprintf (&optpos, options, sl->name);
454               GNUNET_free (options);
455               options = optpos;
456             }
457           /* replace '$PATH' with value associated with "PATH" */
458           while (NULL != (optpos = strstr (options, "$")))
459             {
460               optend = optpos + 1;
461               while (isupper ((unsigned char) *optend))
462                 optend++;
463               b = *optend;
464               if ('\0' == b)
465                 next = "";
466               else
467                 next = optend + 1;
468               *optend = '\0';
469               if (GNUNET_OK !=
470                   GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS",
471                                                          optpos + 1, &val))
472                 val = GNUNET_strdup ("");
473               *optpos = '\0';
474               GNUNET_asprintf (&optpos, "%s%s%c%s", options, val, b, next);
475               GNUNET_free (options);
476               GNUNET_free (val);
477               options = optpos;
478             }
479         }
480     }
481   use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG");
482
483   /* actually start process */
484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485               "Starting service `%s' using binary `%s' and configuration `%s'\n",
486               sl->name, sl->binary, sl->config);
487   binary = GNUNET_OS_get_libexec_binary_path (sl->binary);
488   GNUNET_asprintf (&quotedbinary,
489                    "\"%s\"",
490                    binary);
491
492   GNUNET_assert (NULL == sl->proc);
493   if (GNUNET_YES == use_debug)
494   {
495     if (NULL == sl->config)
496       sl->proc =
497         GNUNET_OS_start_process_s (sl->pipe_control,
498                                    GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
499                                    lsocks, loprefix, quotedbinary, "-L",
500                                    "DEBUG", options, NULL);
501     else
502       sl->proc =
503           GNUNET_OS_start_process_s (sl->pipe_control,
504                                      GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
505                                      lsocks, loprefix, quotedbinary, "-c",
506                                      sl->config, "-L",
507                                      "DEBUG", options, NULL);
508   }
509   else
510   {
511     if (NULL == sl->config)
512       sl->proc =
513           GNUNET_OS_start_process_s (sl->pipe_control,
514                                      GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
515                                      lsocks, loprefix, quotedbinary,
516                                      options, NULL);
517     else
518       sl->proc =
519           GNUNET_OS_start_process_s (sl->pipe_control,
520                                      GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
521                                      lsocks, loprefix, quotedbinary, "-c",
522                                      sl->config, options, NULL);
523   }
524   GNUNET_free (binary);
525   GNUNET_free (quotedbinary);
526   if (sl->proc == NULL)
527   {
528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to start service `%s'\n"),
529                 sl->name);
530     if (client)
531       signal_result (client, sl->name, request_id, GNUNET_ARM_RESULT_START_FAILED);
532   }
533   else
534   {
535     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting service `%s'\n"),
536                 sl->name);
537     broadcast_status (sl->name, GNUNET_ARM_SERVICE_STARTING, NULL);
538     if (client)
539       signal_result (client, sl->name, request_id, GNUNET_ARM_RESULT_STARTING);
540   }
541   /* clean up */
542   GNUNET_free (loprefix);
543   GNUNET_free (options);
544   GNUNET_array_grow (lsocks, ls, 0);
545 }
546
547
548 /**
549  * Find the process with the given service
550  * name in the given list and return it.
551  *
552  * @param name which service entry to look up
553  * @return NULL if it was not found
554  */
555 static struct ServiceList *
556 find_service (const char *name)
557 {
558   struct ServiceList *sl;
559
560   sl = running_head;
561   while (sl != NULL)
562     {
563       if (0 == strcasecmp (sl->name, name))
564         return sl;
565       sl = sl->next;
566     }
567   return NULL;
568 }
569
570
571 /**
572  * First connection has come to the listening socket associated with the service,
573  * create the service in order to relay the incoming connection to it
574  *
575  * @param cls callback data, `struct ServiceListeningInfo` describing a listen socket
576  * @param tc context
577  */
578 static void
579 accept_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
580 {
581   struct ServiceListeningInfo *sli = cls;
582   struct ServiceList *sl = sli->sl;
583
584   sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
585   GNUNET_assert (GNUNET_NO == in_shutdown);
586   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
587     return;
588   start_process (sl, NULL, 0);
589 }
590
591
592 /**
593  * Creating a listening socket for each of the service's addresses and
594  * wait for the first incoming connection to it
595  *
596  * @param sa address associated with the service
597  * @param addr_len length of @a sa
598  * @param sl service entry for the service in question
599  */
600 static void
601 create_listen_socket (struct sockaddr *sa, socklen_t addr_len,
602                       struct ServiceList *sl)
603 {
604   static int on = 1;
605   struct GNUNET_NETWORK_Handle *sock;
606   struct ServiceListeningInfo *sli;
607 #ifndef WINDOWS
608   int match_uid;
609   int match_gid;
610 #endif
611
612   switch (sa->sa_family)
613   {
614   case AF_INET:
615     sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0);
616     break;
617   case AF_INET6:
618     sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
619     break;
620   case AF_UNIX:
621     if (strcmp (GNUNET_a2s (sa, addr_len), "@") == 0)   /* Do not bind to blank UNIX path! */
622       return;
623     sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
624     break;
625   default:
626     GNUNET_break (0);
627     sock = NULL;
628     errno = EAFNOSUPPORT;
629     break;
630   }
631   if (NULL == sock)
632   {
633     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
634                 _("Unable to create socket for service `%s': %s\n"),
635                 sl->name, STRERROR (errno));
636     GNUNET_free (sa);
637     return;
638   }
639   if (GNUNET_NETWORK_socket_setsockopt
640       (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
641     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
642                          "setsockopt");
643 #ifdef IPV6_V6ONLY
644   if ((sa->sa_family == AF_INET6) &&
645       (GNUNET_NETWORK_socket_setsockopt
646        (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
647     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
648                          "setsockopt");
649 #endif
650
651   if (GNUNET_OK !=
652       GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) sa, addr_len))
653   {
654     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
655                 _
656                 ("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
657                 sl->name, GNUNET_a2s (sa, addr_len), STRERROR (errno));
658     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
659     GNUNET_free (sa);
660     return;
661   }
662 #ifndef WINDOWS
663   if (AF_UNIX == sa->sa_family)
664   {
665     match_uid =
666       GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
667                                             "UNIX_MATCH_UID");
668     match_gid =
669       GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
670                                             "UNIX_MATCH_GID");
671     GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sa)->sun_path,
672                                  match_uid,
673                                  match_gid);
674
675   }
676 #endif
677   if (GNUNET_NETWORK_socket_listen (sock, 5) != GNUNET_OK)
678   {
679     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
680     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
681     GNUNET_free (sa);
682     return;
683   }
684   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
685               _("ARM now monitors connections to service `%s' at `%s'\n"),
686               sl->name, GNUNET_a2s (sa, addr_len));
687   sli = GNUNET_new (struct ServiceListeningInfo);
688   sli->service_addr = sa;
689   sli->service_addr_len = addr_len;
690   sli->listen_socket = sock;
691   sli->sl = sl;
692   sli->accept_task =
693     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
694                                    &accept_connection, sli);
695   GNUNET_CONTAINER_DLL_insert (sl->listen_head, sl->listen_tail, sli);
696 }
697
698
699 /**
700  * Remove and free an entry in the service list.  Listen sockets
701  * must have already been cleaned up.  Only to be called during shutdown.
702  *
703  * @param sl entry to free
704  */
705 static void
706 free_service (struct ServiceList *sl)
707 {
708   GNUNET_assert (GNUNET_YES == in_shutdown);
709   GNUNET_CONTAINER_DLL_remove (running_head, running_tail, sl);
710   GNUNET_assert (NULL == sl->listen_head);
711   GNUNET_free_non_null (sl->config);
712   GNUNET_free_non_null (sl->binary);
713   GNUNET_free (sl->name);
714   GNUNET_free (sl);
715 }
716
717
718 /**
719  * Handle START-message.
720  *
721  * @param cls closure (always NULL)
722  * @param client identification of the client
723  * @param message the actual message
724  * @return #GNUNET_OK to keep the connection open,
725  *         #GNUNET_SYSERR to close it (signal serious error)
726  */
727 static void
728 handle_start (void *cls, struct GNUNET_SERVER_Client *client,
729               const struct GNUNET_MessageHeader *message)
730 {
731   const char *servicename;
732   struct ServiceList *sl;
733   uint16_t size;
734   uint64_t request_id;
735   struct GNUNET_ARM_Message *amsg;
736
737   amsg = (struct GNUNET_ARM_Message *) message;
738   request_id = GNUNET_ntohll (amsg->request_id);
739   size = ntohs (amsg->header.size);
740   size -= sizeof (struct GNUNET_ARM_Message);
741   servicename = (const char *) &amsg[1];
742   if ((size == 0) || (servicename[size - 1] != '\0'))
743   {
744     GNUNET_break (0);
745     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
746     return;
747   }
748   if (GNUNET_YES == in_shutdown)
749   {
750     signal_result (client, servicename, request_id,
751                    GNUNET_ARM_RESULT_IN_SHUTDOWN);
752     GNUNET_SERVER_receive_done (client, GNUNET_OK);
753     return;
754   }
755   sl = find_service (servicename);
756   if (NULL == sl)
757   {
758     signal_result (client, servicename, request_id,
759                    GNUNET_ARM_RESULT_IS_NOT_KNOWN);
760     GNUNET_SERVER_receive_done (client, GNUNET_OK);
761     return;
762   }
763   sl->is_default = GNUNET_YES;
764   if (NULL != sl->proc)
765   {
766     signal_result (client, servicename, request_id,
767                    GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
768     GNUNET_SERVER_receive_done (client, GNUNET_OK);
769     return;
770   }
771   start_process (sl, client, request_id);
772   GNUNET_SERVER_receive_done (client, GNUNET_OK);
773 }
774
775
776 /**
777  * Start a shutdown sequence.
778  *
779  * @param cls closure (refers to service)
780  * @param tc task context
781  */
782 static void
783 trigger_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
784 {
785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Triggering shutdown\n");
786   GNUNET_SCHEDULER_shutdown ();
787 }
788
789
790 /**
791  * Handle STOP-message.
792  *
793  * @param cls closure (always NULL)
794  * @param client identification of the client
795  * @param message the actual message
796  * @return #GNUNET_OK to keep the connection open,
797  *         #GNUNET_SYSERR to close it (signal serious error)
798  */
799 static void
800 handle_stop (void *cls, struct GNUNET_SERVER_Client *client,
801              const struct GNUNET_MessageHeader *message)
802 {
803   struct ServiceList *sl;
804   const char *servicename;
805   uint16_t size;
806   uint64_t request_id;
807   struct GNUNET_ARM_Message *amsg;
808
809   amsg = (struct GNUNET_ARM_Message *) message;
810   request_id = GNUNET_ntohll (amsg->request_id);
811   size = ntohs (amsg->header.size);
812   size -= sizeof (struct GNUNET_ARM_Message);
813   servicename = (const char *) &amsg[1];
814   if ((size == 0) || (servicename[size - 1] != '\0'))
815     {
816       GNUNET_break (0);
817       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
818       return;
819     }
820   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
821               _("Preparing to stop `%s'\n"),
822               servicename);
823   if (0 == strcasecmp (servicename, "arm"))
824   {
825     broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
826     signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_STOPPING);
827     GNUNET_SERVER_client_persist_ (client);
828     GNUNET_SCHEDULER_add_now (trigger_shutdown, NULL);
829     GNUNET_SERVER_receive_done (client, GNUNET_OK);
830     return;
831   }
832   sl = find_service (servicename);
833   if (sl == NULL)
834     {
835       signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IS_NOT_KNOWN);
836       GNUNET_SERVER_receive_done (client, GNUNET_OK);
837       return;
838     }
839   sl->is_default = GNUNET_NO;
840   if (GNUNET_YES == in_shutdown)
841     {
842       /* shutdown in progress */
843       signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IN_SHUTDOWN);
844       GNUNET_SERVER_receive_done (client, GNUNET_OK);
845       return;
846     }
847   if (NULL != sl->killing_client)
848   {
849     /* killing already in progress */
850     signal_result (client, servicename, request_id,
851                    GNUNET_ARM_RESULT_IS_STOPPING_ALREADY);
852     GNUNET_SERVER_receive_done (client, GNUNET_OK);
853     return;
854   }
855   if (NULL == sl->proc)
856   {
857     /* process is down */
858     signal_result (client, servicename, request_id,
859                    GNUNET_ARM_RESULT_IS_STOPPED_ALREADY);
860     GNUNET_SERVER_receive_done (client, GNUNET_OK);
861     return;
862   }
863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864               "Sending kill signal to service `%s', waiting for process to die.\n",
865               servicename);
866   broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
867   /* no signal_start - only when it's STOPPED */
868   sl->killed_at = GNUNET_TIME_absolute_get ();
869   if (0 != GNUNET_OS_process_kill (sl->proc, GNUNET_TERM_SIG))
870     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
871   sl->killing_client = client;
872   sl->killing_client_request_id = request_id;
873   GNUNET_SERVER_client_keep (client);
874   GNUNET_SERVER_receive_done (client, GNUNET_OK);
875 }
876
877
878 /**
879  * Handle LIST-message.
880  *
881  * @param cls closure (always NULL)
882  * @param client identification of the client
883  * @param message the actual message
884  */
885 static void
886 handle_list (void *cls, struct GNUNET_SERVER_Client *client,
887              const struct GNUNET_MessageHeader *message)
888 {
889   struct GNUNET_ARM_ListResultMessage *msg;
890   struct GNUNET_ARM_Message *request;
891   size_t string_list_size;
892   size_t total_size;
893   struct ServiceList *sl;
894   uint16_t count;
895
896   if (NULL == client)
897     return;
898
899   request = (struct GNUNET_ARM_Message *) message;
900   GNUNET_break (0 == ntohl (request->reserved));
901   count = 0;
902   string_list_size = 0;
903   /* first count the running processes get their name's size */
904   for (sl = running_head; NULL != sl; sl = sl->next)
905   {
906     if (sl->proc != NULL)
907     {
908       string_list_size += strlen (sl->name);
909       string_list_size += strlen (sl->binary);
910       string_list_size += 4;
911       count++;
912     }
913   }
914
915   total_size = sizeof (struct GNUNET_ARM_ListResultMessage)
916                + string_list_size;
917   msg = GNUNET_malloc (total_size);
918   msg->arm_msg.header.size = total_size;
919   msg->arm_msg.header.type = GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT;
920   msg->arm_msg.reserved = htonl (0);
921   msg->arm_msg.request_id = GNUNET_ntohll (request->request_id);
922   msg->count = count;
923
924   char *pos = (char *)&msg[1];
925   for (sl = running_head; sl != NULL; sl = sl->next)
926   {
927     if (sl->proc != NULL)
928     {
929       size_t s = strlen (sl->name) + strlen (sl->binary) + 4;
930       GNUNET_snprintf(pos, s, "%s (%s)", sl->name, sl->binary);
931       pos += s;
932     }
933   }
934
935   GNUNET_SERVER_notify_transmit_ready (client,
936                                        total_size,
937                                        GNUNET_TIME_UNIT_FOREVER_REL,
938                                        write_list_result, msg);
939   GNUNET_SERVER_receive_done (client, GNUNET_OK);
940 }
941
942
943 /**
944  * We are done with everything.  Stop remaining
945  * tasks, signal handler and the server.
946  */
947 static void
948 do_shutdown ()
949 {
950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last shutdown phase\n");
951   if (NULL != notifier)
952   {
953     GNUNET_SERVER_notification_context_destroy (notifier);
954     notifier = NULL;
955   }
956   if (NULL != server)
957     {
958       GNUNET_SERVER_destroy (server);
959       server = NULL;
960     }
961   if (GNUNET_SCHEDULER_NO_TASK != child_death_task)
962     {
963       GNUNET_SCHEDULER_cancel (child_death_task);
964       child_death_task = GNUNET_SCHEDULER_NO_TASK;
965     }
966 }
967
968
969 static unsigned int
970 list_count (struct ServiceList *running_head)
971 {
972   struct ServiceList *i;
973   unsigned int res = 0;
974
975   for (res = 0, i = running_head; i; i = i->next, res++)
976     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
977                 "%s\n",
978                 i->name);
979   return res;
980 }
981
982
983 /**
984  * Task run for shutdown.
985  *
986  * @param cls closure, NULL if we need to self-restart
987  * @param tc context
988  */
989 static void
990 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
991 {
992   struct ServiceList *pos;
993   struct ServiceList *nxt;
994   struct ServiceListeningInfo *sli;
995
996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
997               "First shutdown phase\n");
998   if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
999   {
1000     GNUNET_SCHEDULER_cancel (child_restart_task);
1001     child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1002   }
1003   in_shutdown = GNUNET_YES;
1004   /* first, stop listening */
1005   for (pos = running_head; NULL != pos; pos = pos->next)
1006   {
1007     while (NULL != (sli = pos->listen_head))
1008       {
1009         GNUNET_CONTAINER_DLL_remove (pos->listen_head,
1010                                      pos->listen_tail, sli);
1011         if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
1012           {
1013             GNUNET_SCHEDULER_cancel (sli->accept_task);
1014             sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
1015           }
1016         GNUNET_break (GNUNET_OK ==
1017                       GNUNET_NETWORK_socket_close (sli->listen_socket));
1018         GNUNET_free (sli->service_addr);
1019         GNUNET_free (sli);
1020       }
1021   }
1022   /* then, shutdown all existing service processes */
1023   nxt = running_head;
1024   while (NULL != (pos = nxt))
1025   {
1026     nxt = pos->next;
1027     if (pos->proc != NULL)
1028     {
1029       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1030                   "Stopping service `%s'\n",
1031                   pos->name);
1032       pos->killed_at = GNUNET_TIME_absolute_get ();
1033       if (0 != GNUNET_OS_process_kill (pos->proc, GNUNET_TERM_SIG))
1034         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
1035     }
1036     else
1037     {
1038       free_service (pos);
1039     }
1040   }
1041   /* finally, should all service processes be already gone, terminate for real */
1042   if (running_head == NULL)
1043     do_shutdown ();
1044   else
1045     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046                 "Delaying shutdown, have %u childs still running\n",
1047                 list_count (running_head));
1048 }
1049
1050
1051 /**
1052  * Task run whenever it is time to restart a child that died.
1053  *
1054  * @param cls closure, always NULL
1055  * @param tc context
1056  */
1057 static void
1058 delayed_restart_task (void *cls,
1059                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1060 {
1061   struct ServiceList *sl;
1062   struct GNUNET_TIME_Relative lowestRestartDelay;
1063   struct ServiceListeningInfo *sli;
1064
1065   child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1066   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1067     return;
1068   GNUNET_assert (GNUNET_NO == in_shutdown);
1069   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
1070
1071   /* check for services that need to be restarted due to
1072    * configuration changes or because the last restart failed */
1073   for (sl = running_head; NULL != sl; sl = sl->next)
1074   {
1075     if (NULL != sl->proc)
1076       continue;
1077     /* service is currently not running */
1078     if (0 == GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value_us)
1079     {
1080       /* restart is now allowed */
1081       if (sl->is_default)
1082       {
1083         /* process should run by default, start immediately */
1084         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1085                     _("Restarting service `%s'.\n"), sl->name);
1086         start_process (sl, NULL, 0);
1087       }
1088       else
1089       {
1090         /* process is run on-demand, ensure it is re-started if there is demand */
1091         for (sli = sl->listen_head; NULL != sli; sli = sli->next)
1092           if (GNUNET_SCHEDULER_NO_TASK == sli->accept_task)
1093           {
1094             /* accept was actually paused, so start it again */
1095             sli->accept_task =
1096               GNUNET_SCHEDULER_add_read_net
1097               (GNUNET_TIME_UNIT_FOREVER_REL, sli->listen_socket,
1098                &accept_connection, sli);
1099           }
1100       }
1101     }
1102     else
1103     {
1104       /* update calculation for earliest time to reactivate a service */
1105       lowestRestartDelay =
1106         GNUNET_TIME_relative_min (lowestRestartDelay,
1107                                   GNUNET_TIME_absolute_get_remaining
1108                                   (sl->restart_at));
1109     }
1110   }
1111   if (lowestRestartDelay.rel_value_us != GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1112   {
1113     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1114                 "Will restart process in %s\n",
1115                 GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay, GNUNET_YES));
1116     child_restart_task =
1117       GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay,
1118                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1119                                                   &delayed_restart_task, NULL);
1120   }
1121 }
1122
1123
1124 /**
1125  * Task triggered whenever we receive a SIGCHLD (child
1126  * process died).
1127  *
1128  * @param cls closure, NULL if we need to self-restart
1129  * @param tc context
1130  */
1131 static void
1132 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1133 {
1134   struct ServiceList *pos;
1135   struct ServiceList *next;
1136   struct ServiceListeningInfo *sli;
1137   const char *statstr;
1138   int statcode;
1139   int ret;
1140   char c[16];
1141   enum GNUNET_OS_ProcessStatusType statusType;
1142   unsigned long statusCode;
1143   const struct GNUNET_DISK_FileHandle *pr;
1144
1145   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
1146   child_death_task = GNUNET_SCHEDULER_NO_TASK;
1147   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1148     {
1149       /* shutdown scheduled us, ignore! */
1150       child_death_task =
1151         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1152                                         pr, &maint_child_death, NULL);
1153       return;
1154     }
1155   /* consume the signal */
1156   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
1157
1158   /* check for services that died (WAITPID) */
1159   next = running_head;
1160   while (NULL != (pos = next))
1161     {
1162       next = pos->next;
1163
1164       if (pos->proc == NULL)
1165       {
1166         if (GNUNET_YES == in_shutdown)
1167           free_service (pos);
1168         continue;
1169       }
1170       if ((GNUNET_SYSERR ==
1171            (ret =
1172             GNUNET_OS_process_status (pos->proc, &statusType, &statusCode)))
1173           || ((ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED)
1174               || (statusType == GNUNET_OS_PROCESS_RUNNING)))
1175         continue;
1176       if (statusType == GNUNET_OS_PROCESS_EXITED)
1177       {
1178         statstr = _( /* process termination method */ "exit");
1179         statcode = statusCode;
1180       }
1181       else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
1182       {
1183         statstr = _( /* process termination method */ "signal");
1184         statcode = statusCode;
1185       }
1186       else
1187       {
1188         statstr = _( /* process termination method */ "unknown");
1189         statcode = 0;
1190       }
1191       if (0 != pos->killed_at.abs_value_us)
1192       {
1193         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1194                     _("Service `%s' took %s to terminate\n"),
1195                     pos->name,
1196                     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->killed_at), GNUNET_YES));
1197       }
1198       GNUNET_OS_process_destroy (pos->proc);
1199       pos->proc = NULL;
1200       broadcast_status (pos->name, GNUNET_ARM_SERVICE_STOPPED, NULL);
1201       if (NULL != pos->killing_client)
1202       {
1203         signal_result (pos->killing_client, pos->name,
1204             pos->killing_client_request_id, GNUNET_ARM_RESULT_STOPPED);
1205         GNUNET_SERVER_client_drop (pos->killing_client);
1206         pos->killing_client = NULL;
1207         pos->killing_client_request_id = 0;
1208       }
1209       if (GNUNET_YES != in_shutdown)
1210       {
1211         if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0))
1212         {
1213           /* process terminated normally, allow restart at any time */
1214           pos->restart_at.abs_value_us = 0;
1215           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1216               _("Service `%s' terminated normally, will restart at any time\n"),
1217               pos->name);
1218           /* process can still be re-started on-demand, ensure it is re-started if there is demand */
1219           for (sli = pos->listen_head; NULL != sli; sli = sli->next)
1220           {
1221             GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sli->accept_task);
1222             sli->accept_task =
1223                 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1224                     sli->listen_socket, &accept_connection, sli);
1225           }
1226         }
1227         else
1228         {
1229           if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1230             GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1231                 _("Service `%s' terminated with status %s/%d, will restart in %s\n"),
1232                 pos->name, statstr, statcode,
1233                 GNUNET_STRINGS_relative_time_to_string (pos->backoff, GNUNET_YES));
1234           /* schedule restart */
1235           pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff);
1236           pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff);
1237           if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1238             GNUNET_SCHEDULER_cancel (child_restart_task);
1239           child_restart_task = GNUNET_SCHEDULER_add_with_priority (
1240             GNUNET_SCHEDULER_PRIORITY_IDLE, &delayed_restart_task, NULL);
1241         }
1242       }
1243       else
1244       {
1245         free_service (pos);
1246       }
1247     }
1248   child_death_task = GNUNET_SCHEDULER_add_read_file (
1249       GNUNET_TIME_UNIT_FOREVER_REL, pr, &maint_child_death, NULL);
1250   if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1251     do_shutdown ();
1252   else if (GNUNET_YES == in_shutdown)
1253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1254         "Delaying shutdown after child's death, still have %u children\n",
1255         list_count (running_head));
1256
1257 }
1258
1259
1260 /**
1261  * Signal handler called for SIGCHLD.  Triggers the
1262  * respective handler by writing to the trigger pipe.
1263  */
1264 static void
1265 sighandler_child_death ()
1266 {
1267   static char c;
1268   int old_errno = errno;        /* back-up errno */
1269
1270   GNUNET_break (1 ==
1271                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
1272                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
1273                                         &c, sizeof (c)));
1274   errno = old_errno;            /* restore errno */
1275 }
1276
1277
1278 /**
1279  * Setup our service record for the given section in the configuration file
1280  * (assuming the section is for a service).
1281  *
1282  * @param cls unused
1283  * @param section a section in the configuration file
1284  * @return #GNUNET_OK (continue)
1285  */
1286 static void
1287 setup_service (void *cls, const char *section)
1288 {
1289   struct ServiceList *sl;
1290   char *binary;
1291   char *config;
1292   struct stat sbuf;
1293   struct sockaddr **addrs;
1294   socklen_t *addr_lens;
1295   int ret;
1296   unsigned int i;
1297
1298   if (strcasecmp (section, "arm") == 0)
1299     return;
1300   if (GNUNET_OK !=
1301       GNUNET_CONFIGURATION_get_value_string (cfg, section, "BINARY", &binary))
1302   {
1303     /* not a service section */
1304     return;
1305   }
1306   if ((GNUNET_YES ==
1307        GNUNET_CONFIGURATION_have_value (cfg, section, "USER_SERVICE")) &&
1308       (GNUNET_YES ==
1309        GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "USER_SERVICE")))
1310   {
1311     if (GNUNET_NO == start_user)
1312     {
1313       GNUNET_free (binary);
1314       return; /* user service, and we don't deal with those */
1315     }
1316   }
1317   else
1318   {
1319     if (GNUNET_NO == start_system)
1320     {
1321       GNUNET_free (binary);
1322       return; /* system service, and we don't deal with those */
1323     }
1324   }
1325   sl = find_service (section);
1326   if (NULL != sl)
1327   {
1328     /* got the same section twice!? */
1329     GNUNET_break (0);
1330     GNUNET_free (binary);
1331     return;
1332   }
1333   config = NULL;
1334   if (( (GNUNET_OK !=
1335          GNUNET_CONFIGURATION_get_value_filename (cfg, section, "CONFIG",
1336                                                   &config)) &&
1337         (GNUNET_OK !=
1338          GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS", "DEFAULTCONFIG",
1339                                                   &config)) ) ||
1340       (0 != STAT (config, &sbuf)))
1341   {
1342     if (NULL != config)
1343     {
1344       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1345                                  section, "CONFIG",
1346                                  STRERROR (errno));
1347       GNUNET_free (config);
1348       config = NULL;
1349     }
1350   }
1351   sl = GNUNET_new (struct ServiceList);
1352   sl->name = GNUNET_strdup (section);
1353   sl->binary = binary;
1354   sl->config = config;
1355   sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1356   sl->restart_at = GNUNET_TIME_UNIT_FOREVER_ABS;
1357 #if WINDOWS
1358   sl->pipe_control = GNUNET_YES;
1359 #else
1360   if (GNUNET_CONFIGURATION_have_value (cfg, section, "PIPECONTROL"))
1361     sl->pipe_control = GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "PIPECONTROL");
1362 #endif
1363   GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl);
1364
1365   if (GNUNET_YES !=
1366       GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "AUTOSTART"))
1367     return;
1368   if (0 >= (ret = GNUNET_SERVICE_get_server_addresses (section, cfg,
1369                                                        &addrs, &addr_lens)))
1370     return;
1371   /* this will free (or capture) addrs[i] */
1372   for (i = 0; i < ret; i++)
1373     create_listen_socket (addrs[i], addr_lens[i], sl);
1374   GNUNET_free (addrs);
1375   GNUNET_free (addr_lens);
1376 }
1377
1378
1379 /**
1380  * A client connected, add it to the notification context.
1381  *
1382  * @param cls closure
1383  * @param client identification of the client
1384  */
1385 static void
1386 handle_client_connecting (void *cls, struct GNUNET_SERVER_Client *client)
1387 {
1388   /* All clients are considered to be of the "monitor" kind
1389    * (that is, they don't affect ARM shutdown).
1390    */
1391   if (NULL != client)
1392     GNUNET_SERVER_client_mark_monitor (client);
1393 }
1394
1395
1396 /**
1397  * Handle MONITOR-message.
1398  *
1399  * @param cls closure (always NULL)
1400  * @param client identification of the client
1401  * @param message the actual message
1402  * @return #GNUNET_OK to keep the connection open,
1403  *         #GNUNET_SYSERR to close it (signal serious error)
1404  */
1405 static void
1406 handle_monitor (void *cls, struct GNUNET_SERVER_Client *client,
1407              const struct GNUNET_MessageHeader *message)
1408 {
1409   /* Removal is handled by the server implementation, internally. */
1410   if ((NULL != client) && (NULL != notifier))
1411   {
1412     GNUNET_SERVER_notification_context_add (notifier, client);
1413     broadcast_status ("arm", GNUNET_ARM_SERVICE_MONITORING_STARTED, client);
1414     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1415   }
1416 }
1417
1418
1419 /**
1420  * Process arm requests.
1421  *
1422  * @param cls closure
1423  * @param serv the initialized server
1424  * @param c configuration to use
1425  */
1426 static void
1427 run (void *cls, struct GNUNET_SERVER_Handle *serv,
1428      const struct GNUNET_CONFIGURATION_Handle *c)
1429 {
1430   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1431     {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
1432     {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
1433     {&handle_monitor, NULL, GNUNET_MESSAGE_TYPE_ARM_MONITOR,
1434      sizeof (struct GNUNET_MessageHeader)},
1435     {&handle_list, NULL, GNUNET_MESSAGE_TYPE_ARM_LIST,
1436      sizeof (struct GNUNET_ARM_Message)},
1437     {NULL, NULL, 0, 0}
1438   };
1439   char *defaultservices;
1440   const char *pos;
1441   struct ServiceList *sl;
1442
1443   cfg = c;
1444   server = serv;
1445   GNUNET_assert (serv != NULL);
1446   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1447                                 NULL);
1448   child_death_task =
1449     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1450                                     GNUNET_DISK_pipe_handle (sigpipe,
1451                                                              GNUNET_DISK_PIPE_END_READ),
1452                                     &maint_child_death, NULL);
1453
1454   if (GNUNET_OK !=
1455       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX",
1456                                              &prefix_command))
1457     prefix_command = GNUNET_strdup ("");
1458   if (GNUNET_OK !=
1459       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX",
1460                                              &final_option))
1461     final_option = GNUNET_strdup ("");
1462   if (GNUNET_YES ==
1463       GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "USER_ONLY"))
1464   {
1465     GNUNET_break (GNUNET_YES == start_user);
1466     start_system = GNUNET_NO;
1467     return;
1468   }
1469   if (GNUNET_YES ==
1470       GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "SYSTEM_ONLY"))
1471   {
1472     GNUNET_break (GNUNET_YES == start_system);
1473     start_user = GNUNET_NO;
1474     return;
1475   }
1476   GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL);
1477
1478   /* start default services... */
1479   if (GNUNET_OK ==
1480       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "DEFAULTSERVICES",
1481                                              &defaultservices))
1482     {
1483       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1484                   _("Starting default services `%s'\n"), defaultservices);
1485       if (0 < strlen (defaultservices))
1486         {
1487           for (pos = strtok (defaultservices, " "); NULL != pos;
1488                pos = strtok (NULL, " "))
1489             {
1490               sl = find_service (pos);
1491               if (NULL == sl)
1492                 {
1493                   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1494                               _
1495                               ("Default service `%s' not configured correctly!\n"),
1496                               pos);
1497                   continue;
1498                 }
1499               sl->is_default = GNUNET_YES;
1500               start_process (sl, NULL, 0);
1501             }
1502         }
1503       GNUNET_free (defaultservices);
1504     }
1505   else
1506     {
1507       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1508                   _
1509                   ("No default services configured, GNUnet will not really start right now.\n"));
1510     }
1511
1512   notifier =
1513       GNUNET_SERVER_notification_context_create (server, MAX_NOTIFY_QUEUE);
1514   GNUNET_SERVER_connect_notify (server, handle_client_connecting, NULL);
1515   /* process client requests */
1516   GNUNET_SERVER_add_handlers (server, handlers);
1517 }
1518
1519
1520 /**
1521  * The main function for the arm service.
1522  *
1523  * @param argc number of arguments from the command line
1524  * @param argv command line arguments
1525  * @return 0 ok, 1 on error
1526  */
1527 int
1528 main (int argc, char *const *argv)
1529 {
1530   int ret;
1531   struct GNUNET_SIGNAL_Context *shc_chld;
1532
1533   sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
1534   GNUNET_assert (sigpipe != NULL);
1535   shc_chld =
1536     GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death);
1537   ret =
1538     (GNUNET_OK ==
1539      GNUNET_SERVICE_run (argc, argv, "arm",
1540                          GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN, &run, NULL)) ? 0 : 1;
1541   GNUNET_SIGNAL_handler_uninstall (shc_chld);
1542   shc_chld = NULL;
1543   GNUNET_DISK_pipe_close (sigpipe);
1544   sigpipe = NULL;
1545   return ret;
1546 }
1547
1548
1549 #ifdef LINUX
1550 #include <malloc.h>
1551
1552 /**
1553  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1554  */
1555 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
1556 {
1557   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1558   mallopt (M_TOP_PAD, 1 * 1024);
1559   malloc_trim (0);
1560 }
1561 #endif
1562
1563
1564 /* end of gnunet-service-arm.c */