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