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