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