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