moving away from DEFAULTSERVICES to per-section FORCESTART, thus addressing #3565...
[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 force_start;
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 (NULL == buf)
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 (NULL == buf)
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,
529                 _("Failed to start service `%s'\n"),
530                 sl->name);
531     if (client)
532       signal_result (client,
533                      sl->name,
534                      request_id,
535                      GNUNET_ARM_RESULT_START_FAILED);
536   }
537   else
538   {
539     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
540                 _("Starting service `%s'\n"),
541                 sl->name);
542     broadcast_status (sl->name, GNUNET_ARM_SERVICE_STARTING, NULL);
543     if (client)
544       signal_result (client, sl->name, request_id, GNUNET_ARM_RESULT_STARTING);
545   }
546   /* clean up */
547   GNUNET_free (loprefix);
548   GNUNET_free (options);
549   GNUNET_array_grow (lsocks, ls, 0);
550 }
551
552
553 /**
554  * Find the process with the given service
555  * name in the given list and return it.
556  *
557  * @param name which service entry to look up
558  * @return NULL if it was not found
559  */
560 static struct ServiceList *
561 find_service (const char *name)
562 {
563   struct ServiceList *sl;
564
565   sl = running_head;
566   while (sl != NULL)
567     {
568       if (0 == strcasecmp (sl->name, name))
569         return sl;
570       sl = sl->next;
571     }
572   return NULL;
573 }
574
575
576 /**
577  * First connection has come to the listening socket associated with the service,
578  * create the service in order to relay the incoming connection to it
579  *
580  * @param cls callback data, `struct ServiceListeningInfo` describing a listen socket
581  * @param tc context
582  */
583 static void
584 accept_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
585 {
586   struct ServiceListeningInfo *sli = cls;
587   struct ServiceList *sl = sli->sl;
588
589   sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
590   GNUNET_assert (GNUNET_NO == in_shutdown);
591   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
592     return;
593   start_process (sl, NULL, 0);
594 }
595
596
597 /**
598  * Creating a listening socket for each of the service's addresses and
599  * wait for the first incoming connection to it
600  *
601  * @param sa address associated with the service
602  * @param addr_len length of @a sa
603  * @param sl service entry for the service in question
604  */
605 static void
606 create_listen_socket (struct sockaddr *sa, socklen_t addr_len,
607                       struct ServiceList *sl)
608 {
609   static int on = 1;
610   struct GNUNET_NETWORK_Handle *sock;
611   struct ServiceListeningInfo *sli;
612 #ifndef WINDOWS
613   int match_uid;
614   int match_gid;
615 #endif
616
617   switch (sa->sa_family)
618   {
619   case AF_INET:
620     sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0);
621     break;
622   case AF_INET6:
623     sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
624     break;
625   case AF_UNIX:
626     if (strcmp (GNUNET_a2s (sa, addr_len), "@") == 0)   /* Do not bind to blank UNIX path! */
627       return;
628     sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
629     break;
630   default:
631     GNUNET_break (0);
632     sock = NULL;
633     errno = EAFNOSUPPORT;
634     break;
635   }
636   if (NULL == sock)
637   {
638     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
639                 _("Unable to create socket for service `%s': %s\n"),
640                 sl->name, STRERROR (errno));
641     GNUNET_free (sa);
642     return;
643   }
644   if (GNUNET_NETWORK_socket_setsockopt
645       (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
646     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
647                          "setsockopt");
648 #ifdef IPV6_V6ONLY
649   if ((sa->sa_family == AF_INET6) &&
650       (GNUNET_NETWORK_socket_setsockopt
651        (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
652     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
653                          "setsockopt");
654 #endif
655
656   if (GNUNET_OK !=
657       GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) sa, addr_len))
658   {
659     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
660                 _
661                 ("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
662                 sl->name, GNUNET_a2s (sa, addr_len), STRERROR (errno));
663     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
664     GNUNET_free (sa);
665     return;
666   }
667 #ifndef WINDOWS
668   if ((AF_UNIX == sa->sa_family)
669 #ifdef LINUX
670       /* Permission settings are not required when abstract sockets are used */
671       && ('\0' != ((const struct sockaddr_un *)sa)->sun_path[0])
672 #endif
673       )
674   {
675     match_uid =
676       GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
677                                             "UNIX_MATCH_UID");
678     match_gid =
679       GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name,
680                                             "UNIX_MATCH_GID");
681     GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sa)->sun_path,
682                                  match_uid,
683                                  match_gid);
684
685   }
686 #endif
687   if (GNUNET_NETWORK_socket_listen (sock, 5) != GNUNET_OK)
688   {
689     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
690     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
691     GNUNET_free (sa);
692     return;
693   }
694   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
695               _("ARM now monitors connections to service `%s' at `%s'\n"),
696               sl->name, GNUNET_a2s (sa, addr_len));
697   sli = GNUNET_new (struct ServiceListeningInfo);
698   sli->service_addr = sa;
699   sli->service_addr_len = addr_len;
700   sli->listen_socket = sock;
701   sli->sl = sl;
702   sli->accept_task =
703     GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
704                                    &accept_connection, sli);
705   GNUNET_CONTAINER_DLL_insert (sl->listen_head, sl->listen_tail, sli);
706 }
707
708
709 /**
710  * Remove and free an entry in the service list.  Listen sockets
711  * must have already been cleaned up.  Only to be called during shutdown.
712  *
713  * @param sl entry to free
714  */
715 static void
716 free_service (struct ServiceList *sl)
717 {
718   GNUNET_assert (GNUNET_YES == in_shutdown);
719   GNUNET_CONTAINER_DLL_remove (running_head, running_tail, sl);
720   GNUNET_assert (NULL == sl->listen_head);
721   GNUNET_free_non_null (sl->config);
722   GNUNET_free_non_null (sl->binary);
723   GNUNET_free (sl->name);
724   GNUNET_free (sl);
725 }
726
727
728 /**
729  * Handle START-message.
730  *
731  * @param cls closure (always NULL)
732  * @param client identification of the client
733  * @param message the actual message
734  * @return #GNUNET_OK to keep the connection open,
735  *         #GNUNET_SYSERR to close it (signal serious error)
736  */
737 static void
738 handle_start (void *cls,
739               struct GNUNET_SERVER_Client *client,
740               const struct GNUNET_MessageHeader *message)
741 {
742   const char *servicename;
743   struct ServiceList *sl;
744   uint16_t size;
745   uint64_t request_id;
746   struct GNUNET_ARM_Message *amsg;
747
748   amsg = (struct GNUNET_ARM_Message *) message;
749   request_id = GNUNET_ntohll (amsg->request_id);
750   size = ntohs (amsg->header.size);
751   size -= sizeof (struct GNUNET_ARM_Message);
752   servicename = (const char *) &amsg[1];
753   if ((size == 0) || (servicename[size - 1] != '\0'))
754   {
755     GNUNET_break (0);
756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
757     return;
758   }
759   if (GNUNET_YES == in_shutdown)
760   {
761     signal_result (client, servicename, request_id,
762                    GNUNET_ARM_RESULT_IN_SHUTDOWN);
763     GNUNET_SERVER_receive_done (client, GNUNET_OK);
764     return;
765   }
766   sl = find_service (servicename);
767   if (NULL == sl)
768   {
769     signal_result (client, servicename, request_id,
770                    GNUNET_ARM_RESULT_IS_NOT_KNOWN);
771     GNUNET_SERVER_receive_done (client, GNUNET_OK);
772     return;
773   }
774   sl->force_start = GNUNET_YES;
775   if (NULL != sl->proc)
776   {
777     signal_result (client, servicename, request_id,
778                    GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
779     GNUNET_SERVER_receive_done (client, GNUNET_OK);
780     return;
781   }
782   start_process (sl, client, request_id);
783   GNUNET_SERVER_receive_done (client, GNUNET_OK);
784 }
785
786
787 /**
788  * Start a shutdown sequence.
789  *
790  * @param cls closure (refers to service)
791  * @param tc task context
792  */
793 static void
794 trigger_shutdown (void *cls,
795                   const struct GNUNET_SCHEDULER_TaskContext *tc)
796 {
797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
798               "Triggering shutdown\n");
799   GNUNET_SCHEDULER_shutdown ();
800 }
801
802
803 /**
804  * Handle STOP-message.
805  *
806  * @param cls closure (always NULL)
807  * @param client identification of the client
808  * @param message the actual message
809  * @return #GNUNET_OK to keep the connection open,
810  *         #GNUNET_SYSERR to close it (signal serious error)
811  */
812 static void
813 handle_stop (void *cls,
814              struct GNUNET_SERVER_Client *client,
815              const struct GNUNET_MessageHeader *message)
816 {
817   struct ServiceList *sl;
818   const char *servicename;
819   uint16_t size;
820   uint64_t request_id;
821   struct GNUNET_ARM_Message *amsg;
822
823   amsg = (struct GNUNET_ARM_Message *) message;
824   request_id = GNUNET_ntohll (amsg->request_id);
825   size = ntohs (amsg->header.size);
826   size -= sizeof (struct GNUNET_ARM_Message);
827   servicename = (const char *) &amsg[1];
828   if ((size == 0) || (servicename[size - 1] != '\0'))
829     {
830       GNUNET_break (0);
831       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
832       return;
833     }
834   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
835               _("Preparing to stop `%s'\n"),
836               servicename);
837   if (0 == strcasecmp (servicename, "arm"))
838   {
839     broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
840     signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_STOPPING);
841     GNUNET_SERVER_client_persist_ (client);
842     GNUNET_SCHEDULER_add_now (trigger_shutdown, NULL);
843     GNUNET_SERVER_receive_done (client, GNUNET_OK);
844     return;
845   }
846   sl = find_service (servicename);
847   if (sl == NULL)
848     {
849       signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IS_NOT_KNOWN);
850       GNUNET_SERVER_receive_done (client, GNUNET_OK);
851       return;
852     }
853   sl->force_start = GNUNET_NO;
854   if (GNUNET_YES == in_shutdown)
855     {
856       /* shutdown in progress */
857       signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_IN_SHUTDOWN);
858       GNUNET_SERVER_receive_done (client, GNUNET_OK);
859       return;
860     }
861   if (NULL != sl->killing_client)
862   {
863     /* killing already in progress */
864     signal_result (client, servicename, request_id,
865                    GNUNET_ARM_RESULT_IS_STOPPING_ALREADY);
866     GNUNET_SERVER_receive_done (client, GNUNET_OK);
867     return;
868   }
869   if (NULL == sl->proc)
870   {
871     /* process is down */
872     signal_result (client, servicename, request_id,
873                    GNUNET_ARM_RESULT_IS_STOPPED_ALREADY);
874     GNUNET_SERVER_receive_done (client, GNUNET_OK);
875     return;
876   }
877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
878               "Sending kill signal to service `%s', waiting for process to die.\n",
879               servicename);
880   broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL);
881   /* no signal_start - only when it's STOPPED */
882   sl->killed_at = GNUNET_TIME_absolute_get ();
883   if (0 != GNUNET_OS_process_kill (sl->proc, GNUNET_TERM_SIG))
884     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
885   sl->killing_client = client;
886   sl->killing_client_request_id = request_id;
887   GNUNET_SERVER_client_keep (client);
888   GNUNET_SERVER_receive_done (client, GNUNET_OK);
889 }
890
891
892 /**
893  * Handle LIST-message.
894  *
895  * @param cls closure (always NULL)
896  * @param client identification of the client
897  * @param message the actual message
898  */
899 static void
900 handle_list (void *cls, struct GNUNET_SERVER_Client *client,
901              const struct GNUNET_MessageHeader *message)
902 {
903   struct GNUNET_ARM_ListResultMessage *msg;
904   struct GNUNET_ARM_Message *request;
905   size_t string_list_size;
906   size_t total_size;
907   struct ServiceList *sl;
908   uint16_t count;
909
910   if (NULL == client)
911     return;
912
913   request = (struct GNUNET_ARM_Message *) message;
914   GNUNET_break (0 == ntohl (request->reserved));
915   count = 0;
916   string_list_size = 0;
917   /* first count the running processes get their name's size */
918   for (sl = running_head; NULL != sl; sl = sl->next)
919   {
920     if (NULL != sl->proc)
921     {
922       string_list_size += strlen (sl->name);
923       string_list_size += strlen (sl->binary);
924       string_list_size += 4;
925       count++;
926     }
927   }
928
929   total_size = sizeof (struct GNUNET_ARM_ListResultMessage)
930                + string_list_size;
931   msg = GNUNET_malloc (total_size);
932   msg->arm_msg.header.size = total_size;
933   msg->arm_msg.header.type = GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT;
934   msg->arm_msg.reserved = htonl (0);
935   msg->arm_msg.request_id = GNUNET_ntohll (request->request_id);
936   msg->count = count;
937
938   char *pos = (char *)&msg[1];
939   for (sl = running_head; NULL != sl; sl = sl->next)
940   {
941     if (NULL != sl->proc)
942     {
943       size_t s = strlen (sl->name) + strlen (sl->binary) + 4;
944       GNUNET_snprintf (pos, s, "%s (%s)", sl->name, sl->binary);
945       pos += s;
946     }
947   }
948   GNUNET_SERVER_notify_transmit_ready (client,
949                                        total_size,
950                                        GNUNET_TIME_UNIT_FOREVER_REL,
951                                        &write_list_result, msg);
952   GNUNET_SERVER_receive_done (client, GNUNET_OK);
953 }
954
955
956 /**
957  * We are done with everything.  Stop remaining
958  * tasks, signal handler and the server.
959  */
960 static void
961 do_shutdown ()
962 {
963   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last shutdown phase\n");
964   if (NULL != notifier)
965   {
966     GNUNET_SERVER_notification_context_destroy (notifier);
967     notifier = NULL;
968   }
969   if (NULL != server)
970     {
971       GNUNET_SERVER_destroy (server);
972       server = NULL;
973     }
974   if (GNUNET_SCHEDULER_NO_TASK != child_death_task)
975     {
976       GNUNET_SCHEDULER_cancel (child_death_task);
977       child_death_task = GNUNET_SCHEDULER_NO_TASK;
978     }
979 }
980
981
982 /**
983  * Count how many services are still active.
984  *
985  * @param running_head list of services
986  * @return number of active services found
987  */
988 static unsigned int
989 list_count (struct ServiceList *running_head)
990 {
991   struct ServiceList *i;
992   unsigned int res = 0;
993
994   for (res = 0, i = running_head; i; i = i->next, res++)
995     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
996                 "%s\n",
997                 i->name);
998   return res;
999 }
1000
1001
1002 /**
1003  * Task run for shutdown.
1004  *
1005  * @param cls closure, NULL if we need to self-restart
1006  * @param tc context
1007  */
1008 static void
1009 shutdown_task (void *cls,
1010                const struct GNUNET_SCHEDULER_TaskContext *tc)
1011 {
1012   struct ServiceList *pos;
1013   struct ServiceList *nxt;
1014   struct ServiceListeningInfo *sli;
1015
1016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1017               "First shutdown phase\n");
1018   if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1019   {
1020     GNUNET_SCHEDULER_cancel (child_restart_task);
1021     child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1022   }
1023   in_shutdown = GNUNET_YES;
1024   /* first, stop listening */
1025   for (pos = running_head; NULL != pos; pos = pos->next)
1026   {
1027     while (NULL != (sli = pos->listen_head))
1028       {
1029         GNUNET_CONTAINER_DLL_remove (pos->listen_head,
1030                                      pos->listen_tail, sli);
1031         if (sli->accept_task != GNUNET_SCHEDULER_NO_TASK)
1032           {
1033             GNUNET_SCHEDULER_cancel (sli->accept_task);
1034             sli->accept_task = GNUNET_SCHEDULER_NO_TASK;
1035           }
1036         GNUNET_break (GNUNET_OK ==
1037                       GNUNET_NETWORK_socket_close (sli->listen_socket));
1038         GNUNET_free (sli->service_addr);
1039         GNUNET_free (sli);
1040       }
1041   }
1042   /* then, shutdown all existing service processes */
1043   nxt = running_head;
1044   while (NULL != (pos = nxt))
1045   {
1046     nxt = pos->next;
1047     if (pos->proc != NULL)
1048     {
1049       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1050                   "Stopping service `%s'\n",
1051                   pos->name);
1052       pos->killed_at = GNUNET_TIME_absolute_get ();
1053       if (0 != GNUNET_OS_process_kill (pos->proc, GNUNET_TERM_SIG))
1054         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
1055     }
1056     else
1057     {
1058       free_service (pos);
1059     }
1060   }
1061   /* finally, should all service processes be already gone, terminate for real */
1062   if (running_head == NULL)
1063     do_shutdown ();
1064   else
1065     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066                 "Delaying shutdown, have %u childs still running\n",
1067                 list_count (running_head));
1068 }
1069
1070
1071 /**
1072  * Task run whenever it is time to restart a child that died.
1073  *
1074  * @param cls closure, always NULL
1075  * @param tc context
1076  */
1077 static void
1078 delayed_restart_task (void *cls,
1079                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1080 {
1081   struct ServiceList *sl;
1082   struct GNUNET_TIME_Relative lowestRestartDelay;
1083   struct ServiceListeningInfo *sli;
1084
1085   child_restart_task = GNUNET_SCHEDULER_NO_TASK;
1086   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1087     return;
1088   GNUNET_assert (GNUNET_NO == in_shutdown);
1089   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
1090
1091   /* check for services that need to be restarted due to
1092    * configuration changes or because the last restart failed */
1093   for (sl = running_head; NULL != sl; sl = sl->next)
1094   {
1095     if (NULL != sl->proc)
1096       continue;
1097     /* service is currently not running */
1098     if (0 == GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value_us)
1099     {
1100       /* restart is now allowed */
1101       if (sl->force_start)
1102       {
1103         /* process should run by default, start immediately */
1104         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1105                     _("Restarting service `%s'.\n"),
1106                     sl->name);
1107         start_process (sl, NULL, 0);
1108       }
1109       else
1110       {
1111         /* process is run on-demand, ensure it is re-started if there is demand */
1112         for (sli = sl->listen_head; NULL != sli; sli = sli->next)
1113           if (GNUNET_SCHEDULER_NO_TASK == sli->accept_task)
1114           {
1115             /* accept was actually paused, so start it again */
1116             sli->accept_task =
1117               GNUNET_SCHEDULER_add_read_net
1118               (GNUNET_TIME_UNIT_FOREVER_REL, sli->listen_socket,
1119                &accept_connection, sli);
1120           }
1121       }
1122     }
1123     else
1124     {
1125       /* update calculation for earliest time to reactivate a service */
1126       lowestRestartDelay =
1127         GNUNET_TIME_relative_min (lowestRestartDelay,
1128                                   GNUNET_TIME_absolute_get_remaining
1129                                   (sl->restart_at));
1130     }
1131   }
1132   if (lowestRestartDelay.rel_value_us != GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1133   {
1134     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1135                 "Will restart process in %s\n",
1136                 GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay, GNUNET_YES));
1137     child_restart_task =
1138       GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay,
1139                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1140                                                   &delayed_restart_task, NULL);
1141   }
1142 }
1143
1144
1145 /**
1146  * Task triggered whenever we receive a SIGCHLD (child
1147  * process died).
1148  *
1149  * @param cls closure, NULL if we need to self-restart
1150  * @param tc context
1151  */
1152 static void
1153 maint_child_death (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1154 {
1155   struct ServiceList *pos;
1156   struct ServiceList *next;
1157   struct ServiceListeningInfo *sli;
1158   const char *statstr;
1159   int statcode;
1160   int ret;
1161   char c[16];
1162   enum GNUNET_OS_ProcessStatusType statusType;
1163   unsigned long statusCode;
1164   const struct GNUNET_DISK_FileHandle *pr;
1165
1166   pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ);
1167   child_death_task = GNUNET_SCHEDULER_NO_TASK;
1168   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
1169     {
1170       /* shutdown scheduled us, ignore! */
1171       child_death_task =
1172         GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1173                                         pr, &maint_child_death, NULL);
1174       return;
1175     }
1176   /* consume the signal */
1177   GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c)));
1178
1179   /* check for services that died (WAITPID) */
1180   next = running_head;
1181   while (NULL != (pos = next))
1182     {
1183       next = pos->next;
1184
1185       if (pos->proc == NULL)
1186       {
1187         if (GNUNET_YES == in_shutdown)
1188           free_service (pos);
1189         continue;
1190       }
1191       if ((GNUNET_SYSERR ==
1192            (ret =
1193             GNUNET_OS_process_status (pos->proc, &statusType, &statusCode)))
1194           || ((ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED)
1195               || (statusType == GNUNET_OS_PROCESS_RUNNING)))
1196         continue;
1197       if (statusType == GNUNET_OS_PROCESS_EXITED)
1198       {
1199         statstr = _( /* process termination method */ "exit");
1200         statcode = statusCode;
1201       }
1202       else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
1203       {
1204         statstr = _( /* process termination method */ "signal");
1205         statcode = statusCode;
1206       }
1207       else
1208       {
1209         statstr = _( /* process termination method */ "unknown");
1210         statcode = 0;
1211       }
1212       if (0 != pos->killed_at.abs_value_us)
1213       {
1214         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1215                     _("Service `%s' took %s to terminate\n"),
1216                     pos->name,
1217                     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->killed_at), GNUNET_YES));
1218       }
1219       GNUNET_OS_process_destroy (pos->proc);
1220       pos->proc = NULL;
1221       broadcast_status (pos->name, GNUNET_ARM_SERVICE_STOPPED, NULL);
1222       if (NULL != pos->killing_client)
1223       {
1224         signal_result (pos->killing_client, pos->name,
1225             pos->killing_client_request_id, GNUNET_ARM_RESULT_STOPPED);
1226         GNUNET_SERVER_client_drop (pos->killing_client);
1227         pos->killing_client = NULL;
1228         pos->killing_client_request_id = 0;
1229       }
1230       if (GNUNET_YES != in_shutdown)
1231       {
1232         if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0))
1233         {
1234           /* process terminated normally, allow restart at any time */
1235           pos->restart_at.abs_value_us = 0;
1236           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1237               _("Service `%s' terminated normally, will restart at any time\n"),
1238               pos->name);
1239           /* process can still be re-started on-demand, ensure it is re-started if there is demand */
1240           for (sli = pos->listen_head; NULL != sli; sli = sli->next)
1241           {
1242             GNUNET_break (GNUNET_SCHEDULER_NO_TASK == sli->accept_task);
1243             sli->accept_task =
1244                 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1245                     sli->listen_socket, &accept_connection, sli);
1246           }
1247         }
1248         else
1249         {
1250           if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1251             GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1252                 _("Service `%s' terminated with status %s/%d, will restart in %s\n"),
1253                 pos->name, statstr, statcode,
1254                 GNUNET_STRINGS_relative_time_to_string (pos->backoff, GNUNET_YES));
1255           /* schedule restart */
1256           pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff);
1257           pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff);
1258           if (GNUNET_SCHEDULER_NO_TASK != child_restart_task)
1259             GNUNET_SCHEDULER_cancel (child_restart_task);
1260           child_restart_task = GNUNET_SCHEDULER_add_with_priority (
1261             GNUNET_SCHEDULER_PRIORITY_IDLE, &delayed_restart_task, NULL);
1262         }
1263       }
1264       else
1265       {
1266         free_service (pos);
1267       }
1268     }
1269   child_death_task = GNUNET_SCHEDULER_add_read_file (
1270       GNUNET_TIME_UNIT_FOREVER_REL, pr, &maint_child_death, NULL);
1271   if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1272     do_shutdown ();
1273   else if (GNUNET_YES == in_shutdown)
1274     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1275         "Delaying shutdown after child's death, still have %u children\n",
1276         list_count (running_head));
1277
1278 }
1279
1280
1281 /**
1282  * Signal handler called for SIGCHLD.  Triggers the
1283  * respective handler by writing to the trigger pipe.
1284  */
1285 static void
1286 sighandler_child_death ()
1287 {
1288   static char c;
1289   int old_errno = errno;        /* back-up errno */
1290
1291   GNUNET_break (1 ==
1292                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
1293                                         (sigpipe, GNUNET_DISK_PIPE_END_WRITE),
1294                                         &c, sizeof (c)));
1295   errno = old_errno;            /* restore errno */
1296 }
1297
1298
1299 /**
1300  * Setup our service record for the given section in the configuration file
1301  * (assuming the section is for a service).
1302  *
1303  * @param cls unused
1304  * @param section a section in the configuration file
1305  * @return #GNUNET_OK (continue)
1306  */
1307 static void
1308 setup_service (void *cls, const char *section)
1309 {
1310   struct ServiceList *sl;
1311   char *binary;
1312   char *config;
1313   struct stat sbuf;
1314   struct sockaddr **addrs;
1315   socklen_t *addr_lens;
1316   int ret;
1317   unsigned int i;
1318
1319   if (strcasecmp (section, "arm") == 0)
1320     return;
1321   if (GNUNET_OK !=
1322       GNUNET_CONFIGURATION_get_value_string (cfg, section, "BINARY", &binary))
1323   {
1324     /* not a service section */
1325     return;
1326   }
1327   if ((GNUNET_YES ==
1328        GNUNET_CONFIGURATION_have_value (cfg, section, "USER_SERVICE")) &&
1329       (GNUNET_YES ==
1330        GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "USER_SERVICE")))
1331   {
1332     if (GNUNET_NO == start_user)
1333     {
1334       GNUNET_free (binary);
1335       return; /* user service, and we don't deal with those */
1336     }
1337   }
1338   else
1339   {
1340     if (GNUNET_NO == start_system)
1341     {
1342       GNUNET_free (binary);
1343       return; /* system service, and we don't deal with those */
1344     }
1345   }
1346   sl = find_service (section);
1347   if (NULL != sl)
1348   {
1349     /* got the same section twice!? */
1350     GNUNET_break (0);
1351     GNUNET_free (binary);
1352     return;
1353   }
1354   config = NULL;
1355   if (( (GNUNET_OK !=
1356          GNUNET_CONFIGURATION_get_value_filename (cfg, section, "CONFIG",
1357                                                   &config)) &&
1358         (GNUNET_OK !=
1359          GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS", "DEFAULTCONFIG",
1360                                                   &config)) ) ||
1361       (0 != STAT (config, &sbuf)))
1362   {
1363     if (NULL != config)
1364     {
1365       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1366                                  section, "CONFIG",
1367                                  STRERROR (errno));
1368       GNUNET_free (config);
1369       config = NULL;
1370     }
1371   }
1372   sl = GNUNET_new (struct ServiceList);
1373   sl->name = GNUNET_strdup (section);
1374   sl->binary = binary;
1375   sl->config = config;
1376   sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1377   sl->restart_at = GNUNET_TIME_UNIT_FOREVER_ABS;
1378 #if WINDOWS
1379   sl->pipe_control = GNUNET_YES;
1380 #else
1381   if (GNUNET_CONFIGURATION_have_value (cfg, section, "PIPECONTROL"))
1382     sl->pipe_control = GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "PIPECONTROL");
1383 #endif
1384   GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl);
1385
1386   if (GNUNET_YES ==
1387       GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "FORCESTART"))
1388   {
1389     sl->force_start = GNUNET_YES;
1390     return;
1391   }
1392   else
1393   {
1394     if (GNUNET_YES !=
1395         GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "AUTOSTART"))
1396       return;
1397   }
1398   if (0 >= (ret = GNUNET_SERVICE_get_server_addresses (section, cfg,
1399                                                        &addrs, &addr_lens)))
1400     return;
1401   /* this will free (or capture) addrs[i] */
1402   for (i = 0; i < ret; i++)
1403     create_listen_socket (addrs[i], addr_lens[i], sl);
1404   GNUNET_free (addrs);
1405   GNUNET_free (addr_lens);
1406 }
1407
1408
1409 /**
1410  * A client connected, add it to the notification context.
1411  *
1412  * @param cls closure
1413  * @param client identification of the client
1414  */
1415 static void
1416 handle_client_connecting (void *cls, struct GNUNET_SERVER_Client *client)
1417 {
1418   /* All clients are considered to be of the "monitor" kind
1419    * (that is, they don't affect ARM shutdown).
1420    */
1421   if (NULL != client)
1422     GNUNET_SERVER_client_mark_monitor (client);
1423 }
1424
1425
1426 /**
1427  * Handle MONITOR-message.
1428  *
1429  * @param cls closure (always NULL)
1430  * @param client identification of the client
1431  * @param message the actual message
1432  * @return #GNUNET_OK to keep the connection open,
1433  *         #GNUNET_SYSERR to close it (signal serious error)
1434  */
1435 static void
1436 handle_monitor (void *cls, struct GNUNET_SERVER_Client *client,
1437              const struct GNUNET_MessageHeader *message)
1438 {
1439   /* Removal is handled by the server implementation, internally. */
1440   if ((NULL != client) && (NULL != notifier))
1441   {
1442     GNUNET_SERVER_notification_context_add (notifier, client);
1443     broadcast_status ("arm", GNUNET_ARM_SERVICE_MONITORING_STARTED, client);
1444     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1445   }
1446 }
1447
1448
1449 /**
1450  * Process arm requests.
1451  *
1452  * @param cls closure
1453  * @param serv the initialized server
1454  * @param c configuration to use
1455  */
1456 static void
1457 run (void *cls, struct GNUNET_SERVER_Handle *serv,
1458      const struct GNUNET_CONFIGURATION_Handle *c)
1459 {
1460   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1461     {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0},
1462     {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0},
1463     {&handle_monitor, NULL, GNUNET_MESSAGE_TYPE_ARM_MONITOR,
1464      sizeof (struct GNUNET_MessageHeader)},
1465     {&handle_list, NULL, GNUNET_MESSAGE_TYPE_ARM_LIST,
1466      sizeof (struct GNUNET_ARM_Message)},
1467     {NULL, NULL, 0, 0}
1468   };
1469   struct ServiceList *sl;
1470
1471   cfg = c;
1472   server = serv;
1473   GNUNET_assert (NULL != serv);
1474   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1475                                 &shutdown_task,
1476                                 NULL);
1477   child_death_task =
1478     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1479                                     GNUNET_DISK_pipe_handle (sigpipe,
1480                                                              GNUNET_DISK_PIPE_END_READ),
1481                                     &maint_child_death, NULL);
1482
1483   if (GNUNET_OK !=
1484       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX",
1485                                              &prefix_command))
1486     prefix_command = GNUNET_strdup ("");
1487   if (GNUNET_OK !=
1488       GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX",
1489                                              &final_option))
1490     final_option = GNUNET_strdup ("");
1491   if (GNUNET_YES ==
1492       GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "USER_ONLY"))
1493   {
1494     GNUNET_break (GNUNET_YES == start_user);
1495     start_system = GNUNET_NO;
1496   }
1497   if (GNUNET_YES ==
1498       GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "SYSTEM_ONLY"))
1499   {
1500     GNUNET_break (GNUNET_YES == start_system);
1501     start_user = GNUNET_NO;
1502   }
1503   GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL);
1504
1505   /* start default services... */
1506   for (sl = running_head; NULL != sl; sl = sl->next)
1507     if (GNUNET_YES == sl->force_start)
1508       start_process (sl, NULL, 0);
1509   notifier
1510     = GNUNET_SERVER_notification_context_create (server,
1511                                                  MAX_NOTIFY_QUEUE);
1512   GNUNET_SERVER_connect_notify (server,
1513                                 &handle_client_connecting, NULL);
1514   /* process client requests */
1515   GNUNET_SERVER_add_handlers (server,
1516                               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 */