Merge branch 'master' of gnunet.org:gnunet
[oweals/gnunet.git] / src / arm / gnunet-service-arm.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2011, 2015, 2016 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file arm/gnunet-service-arm.c
21  * @brief the automated restart manager service
22  * @author Christian Grothoff
23  */
24 #include "platform.h"
25 #include "gnunet_util_lib.h"
26 #include "gnunet_arm_service.h"
27 #include "gnunet_protocols.h"
28 #include "arm.h"
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
31
32 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
33
34
35 #if HAVE_WAIT4
36 /**
37  * Name of the file for writing resource utilization summaries to.
38  */
39 static char *wait_filename;
40
41 /**
42  * Handle for the file for writing resource summaries.
43  */
44 static FILE *wait_file;
45 #endif
46
47
48 /**
49  * How many messages do we queue up at most for optional
50  * notifications to a client?  (this can cause notifications
51  * about outgoing messages to be dropped).
52  */
53 #define MAX_NOTIFY_QUEUE 1024
54
55
56 /**
57  * List of our services.
58  */
59 struct ServiceList;
60
61
62 /**
63  * Record with information about a listen socket we have open.
64  */
65 struct ServiceListeningInfo
66 {
67   /**
68    * This is a linked list.
69    */
70   struct ServiceListeningInfo *next;
71
72   /**
73    * This is a linked list.
74    */
75   struct ServiceListeningInfo *prev;
76
77   /**
78    * Address this socket is listening on.
79    */
80   struct sockaddr *service_addr;
81
82   /**
83    * Service this listen socket is for.
84    */
85   struct ServiceList *sl;
86
87   /**
88    * Number of bytes in @e service_addr
89    */
90   socklen_t service_addr_len;
91
92   /**
93    * Our listening socket.
94    */
95   struct GNUNET_NETWORK_Handle *listen_socket;
96
97   /**
98    * Task doing the accepting.
99    */
100   struct GNUNET_SCHEDULER_Task *accept_task;
101
102 };
103
104
105 /**
106  * List of our services.
107  */
108 struct ServiceList
109 {
110   /**
111    * This is a doubly-linked list.
112    */
113   struct ServiceList *next;
114
115   /**
116    * This is a doubly-linked list.
117    */
118   struct ServiceList *prev;
119
120   /**
121    * Linked list of listen sockets associated with this service.
122    */
123   struct ServiceListeningInfo *listen_head;
124
125   /**
126    * Linked list of listen sockets associated with this service.
127    */
128   struct ServiceListeningInfo *listen_tail;
129
130   /**
131    * Name of the service.
132    */
133   char *name;
134
135   /**
136    * Name of the binary used.
137    */
138   char *binary;
139
140   /**
141    * Name of the configuration file used.
142    */
143   char *config;
144
145   /**
146    * Client to notify upon kill completion (waitpid), NULL
147    * if we should simply restart the process.
148    */
149   struct GNUNET_SERVICE_Client *killing_client;
150
151   /**
152    * ID of the request that killed the service (for reporting back).
153    */
154   uint64_t killing_client_request_id;
155
156   /**
157    * Process structure pointer of the child.
158    */
159   struct GNUNET_OS_Process *proc;
160
161   /**
162    * Process exponential backoff time
163    */
164   struct GNUNET_TIME_Relative backoff;
165
166   /**
167    * Absolute time at which the process is scheduled to restart in case of death
168    */
169   struct GNUNET_TIME_Absolute restart_at;
170
171   /**
172    * Time we asked the service to shut down (used to calculate time it took
173    * the service to terminate).
174    */
175   struct GNUNET_TIME_Absolute killed_at;
176
177   /**
178    * Is this service to be started by default (or did a client tell us explicitly
179    * to start it)?  #GNUNET_NO if the service is started only upon 'accept' on a
180    * listen socket or possibly explicitly by a client changing the value.
181    */
182   int force_start;
183
184   /**
185    * Should we use pipes to signal this process? (YES for Java binaries and if we
186    * are on Windoze).
187    */
188   int pipe_control;
189 };
190
191 /**
192  * List of running services.
193  */
194 static struct ServiceList *running_head;
195
196 /**
197  * List of running services.
198  */
199 static struct ServiceList *running_tail;
200
201 /**
202  * Our configuration
203  */
204 static const struct GNUNET_CONFIGURATION_Handle *cfg;
205
206 /**
207  * Command to prepend to each actual command.
208  */
209 static char *prefix_command;
210
211 /**
212  * Option to append to each actual command.
213  */
214 static char *final_option;
215
216 /**
217  * ID of task called whenever we get a SIGCHILD.
218  */
219 static struct GNUNET_SCHEDULER_Task *child_death_task;
220
221 /**
222  * ID of task called whenever the timeout for restarting a child
223  * expires.
224  */
225 static struct GNUNET_SCHEDULER_Task *child_restart_task;
226
227 /**
228  * Pipe used to communicate shutdown via signal.
229  */
230 static struct GNUNET_DISK_PipeHandle *sigpipe;
231
232 /**
233  * Are we in shutdown mode?
234  */
235 static int in_shutdown;
236
237 /**
238  * Are we starting user services?
239  */
240 static int start_user = GNUNET_YES;
241
242 /**
243  * Are we starting system services?
244  */
245 static int start_system = GNUNET_YES;
246
247 /**
248  * Handle to our service instance.  Our service is a bit special in that
249  * its service is not immediately stopped once we get a shutdown
250  * request (since we need to continue service until all of our child
251  * processes are dead).  This handle is used to shut down the service
252  * (and thus trigger process termination) once all child processes are
253  * also dead.  A special option in the ARM configuration modifies the
254  * behaviour of the service implementation to not do the shutdown
255  * immediately.
256  */
257 static struct GNUNET_SERVICE_Handle *service;
258
259 /**
260  * Context for notifications we need to send to our clients.
261  */
262 static struct GNUNET_NotificationContext *notifier;
263
264
265 /**
266  * Add the given UNIX domain path as an address to the
267  * list (as the first entry).
268  *
269  * @param saddrs array to update
270  * @param saddrlens where to store the address length
271  * @param unixpath path to add
272  * @param abstract #GNUNET_YES to add an abstract UNIX domain socket.  This
273  *          parameter is ignore on systems other than LINUX
274  */
275 static void
276 add_unixpath (struct sockaddr **saddrs,
277               socklen_t *saddrlens,
278               const char *unixpath,
279               int abstract)
280 {
281 #ifdef AF_UNIX
282   struct sockaddr_un *un;
283
284   un = GNUNET_new (struct sockaddr_un);
285   un->sun_family = AF_UNIX;
286   strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
287 #ifdef LINUX
288   if (GNUNET_YES == abstract)
289     un->sun_path[0] = '\0';
290 #endif
291 #if HAVE_SOCKADDR_UN_SUN_LEN
292   un->sun_len = (u_char) sizeof (struct sockaddr_un);
293 #endif
294   *saddrs = (struct sockaddr *) un;
295   *saddrlens = sizeof (struct sockaddr_un);
296 #else
297   /* this function should never be called
298    * unless AF_UNIX is defined! */
299   GNUNET_assert (0);
300 #endif
301 }
302
303
304 /**
305  * Get the list of addresses that a server for the given service
306  * should bind to.
307  *
308  * @param service_name name of the service
309  * @param cfg configuration (which specifies the addresses)
310  * @param addrs set (call by reference) to an array of pointers to the
311  *              addresses the server should bind to and listen on; the
312  *              array will be NULL-terminated (on success)
313  * @param addr_lens set (call by reference) to an array of the lengths
314  *              of the respective `struct sockaddr` struct in the @a addrs
315  *              array (on success)
316  * @return number of addresses found on success,
317  *              #GNUNET_SYSERR if the configuration
318  *              did not specify reasonable finding information or
319  *              if it specified a hostname that could not be resolved;
320  *              #GNUNET_NO if the number of addresses configured is
321  *              zero (in this case, `*addrs` and `*addr_lens` will be
322  *              set to NULL).
323  */
324 static int
325 get_server_addresses (const char *service_name,
326                       const struct GNUNET_CONFIGURATION_Handle *cfg,
327                       struct sockaddr ***addrs,
328                       socklen_t ** addr_lens)
329 {
330   int disablev6;
331   struct GNUNET_NETWORK_Handle *desc;
332   unsigned long long port;
333   char *unixpath;
334   struct addrinfo hints;
335   struct addrinfo *res;
336   struct addrinfo *pos;
337   struct addrinfo *next;
338   unsigned int i;
339   int resi;
340   int ret;
341   int abstract;
342   struct sockaddr **saddrs;
343   socklen_t *saddrlens;
344   char *hostname;
345
346   *addrs = NULL;
347   *addr_lens = NULL;
348   desc = NULL;
349   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
350   {
351     if (GNUNET_SYSERR ==
352         (disablev6 =
353          GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
354       return GNUNET_SYSERR;
355   }
356   else
357     disablev6 = GNUNET_NO;
358
359   if (! disablev6)
360   {
361     /* probe IPv6 support */
362     desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
363     if (NULL == desc)
364     {
365       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
366           (EACCES == errno))
367       {
368         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
369         return GNUNET_SYSERR;
370       }
371       LOG (GNUNET_ERROR_TYPE_INFO,
372            _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
373            service_name, STRERROR (errno));
374       disablev6 = GNUNET_YES;
375     }
376     else
377     {
378       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
379       desc = NULL;
380     }
381   }
382
383   port = 0;
384   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
385   {
386     if (GNUNET_OK !=
387         GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
388                                                "PORT", &port))
389     {
390       LOG (GNUNET_ERROR_TYPE_ERROR,
391            _("Require valid port number for service `%s' in configuration!\n"),
392            service_name);
393     }
394     if (port > 65535)
395     {
396       LOG (GNUNET_ERROR_TYPE_ERROR,
397            _("Require valid port number for service `%s' in configuration!\n"),
398            service_name);
399       return GNUNET_SYSERR;
400     }
401   }
402
403   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
404   {
405     GNUNET_break (GNUNET_OK ==
406                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
407                                                          "BINDTO", &hostname));
408   }
409   else
410     hostname = NULL;
411
412   unixpath = NULL;
413   abstract = GNUNET_NO;
414 #ifdef AF_UNIX
415   if ((GNUNET_YES ==
416        GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
417       (GNUNET_OK ==
418        GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
419                                               &unixpath)) &&
420       (0 < strlen (unixpath)))
421   {
422     /* probe UNIX support */
423     struct sockaddr_un s_un;
424
425     if (strlen (unixpath) >= sizeof (s_un.sun_path))
426     {
427       LOG (GNUNET_ERROR_TYPE_WARNING,
428            _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
429            (unsigned long long) sizeof (s_un.sun_path));
430       unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
431       LOG (GNUNET_ERROR_TYPE_INFO,
432            _("Using `%s' instead\n"),
433            unixpath);
434     }
435 #ifdef LINUX
436     abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
437                                                      "TESTING",
438                                                      "USE_ABSTRACT_SOCKETS");
439     if (GNUNET_SYSERR == abstract)
440       abstract = GNUNET_NO;
441 #endif
442     if ((GNUNET_YES != abstract)
443         && (GNUNET_OK !=
444             GNUNET_DISK_directory_create_for_file (unixpath)))
445       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
446                                 "mkdir",
447                                 unixpath);
448   }
449   if (NULL != unixpath)
450   {
451     desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
452     if (NULL == desc)
453     {
454       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
455           (EACCES == errno))
456       {
457         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
458         GNUNET_free_non_null (hostname);
459         GNUNET_free (unixpath);
460         return GNUNET_SYSERR;
461       }
462       LOG (GNUNET_ERROR_TYPE_INFO,
463            _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
464            service_name,
465            STRERROR (errno));
466       GNUNET_free (unixpath);
467       unixpath = NULL;
468     }
469     else
470     {
471       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
472       desc = NULL;
473     }
474   }
475 #endif
476
477   if ((0 == port) && (NULL == unixpath))
478   {
479     LOG (GNUNET_ERROR_TYPE_ERROR,
480          _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
481          service_name);
482     GNUNET_free_non_null (hostname);
483     return GNUNET_SYSERR;
484   }
485   if (0 == port)
486   {
487     saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
488     saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
489     add_unixpath (saddrs, saddrlens, unixpath, abstract);
490     GNUNET_free_non_null (unixpath);
491     GNUNET_free_non_null (hostname);
492     *addrs = saddrs;
493     *addr_lens = saddrlens;
494     return 1;
495   }
496
497   if (NULL != hostname)
498   {
499     LOG (GNUNET_ERROR_TYPE_DEBUG,
500          "Resolving `%s' since that is where `%s' will bind to.\n",
501          hostname,
502          service_name);
503     memset (&hints, 0, sizeof (struct addrinfo));
504     if (disablev6)
505       hints.ai_family = AF_INET;
506     hints.ai_protocol = IPPROTO_TCP;
507     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
508         (NULL == res))
509     {
510       LOG (GNUNET_ERROR_TYPE_ERROR,
511            _("Failed to resolve `%s': %s\n"),
512            hostname,
513            gai_strerror (ret));
514       GNUNET_free (hostname);
515       GNUNET_free_non_null (unixpath);
516       return GNUNET_SYSERR;
517     }
518     next = res;
519     i = 0;
520     while (NULL != (pos = next))
521     {
522       next = pos->ai_next;
523       if ((disablev6) && (pos->ai_family == AF_INET6))
524         continue;
525       i++;
526     }
527     if (0 == i)
528     {
529       LOG (GNUNET_ERROR_TYPE_ERROR,
530            _("Failed to find %saddress for `%s'.\n"),
531            disablev6 ? "IPv4 " : "",
532            hostname);
533       freeaddrinfo (res);
534       GNUNET_free (hostname);
535       GNUNET_free_non_null (unixpath);
536       return GNUNET_SYSERR;
537     }
538     resi = i;
539     if (NULL != unixpath)
540       resi++;
541     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
542     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
543     i = 0;
544     if (NULL != unixpath)
545     {
546       add_unixpath (saddrs, saddrlens, unixpath, abstract);
547       i++;
548     }
549     next = res;
550     while (NULL != (pos = next))
551     {
552       next = pos->ai_next;
553       if ((disablev6) && (AF_INET6 == pos->ai_family))
554         continue;
555       if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
556         continue;               /* not TCP */
557       if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
558         continue;               /* huh? */
559       LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
560            service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
561       if (AF_INET == pos->ai_family)
562       {
563         GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
564         saddrlens[i] = pos->ai_addrlen;
565         saddrs[i] = GNUNET_malloc (saddrlens[i]);
566         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
567         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
568       }
569       else
570       {
571         GNUNET_assert (AF_INET6 == pos->ai_family);
572         GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
573         saddrlens[i] = pos->ai_addrlen;
574         saddrs[i] = GNUNET_malloc (saddrlens[i]);
575         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
576         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
577       }
578       i++;
579     }
580     GNUNET_free (hostname);
581     freeaddrinfo (res);
582     resi = i;
583   }
584   else
585   {
586     /* will bind against everything, just set port */
587     if (disablev6)
588     {
589       /* V4-only */
590       resi = 1;
591       if (NULL != unixpath)
592         resi++;
593       i = 0;
594       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
595       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
596       if (NULL != unixpath)
597       {
598         add_unixpath (saddrs, saddrlens, unixpath, abstract);
599         i++;
600       }
601       saddrlens[i] = sizeof (struct sockaddr_in);
602       saddrs[i] = GNUNET_malloc (saddrlens[i]);
603 #if HAVE_SOCKADDR_IN_SIN_LEN
604       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
605 #endif
606       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
607       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
608     }
609     else
610     {
611       /* dual stack */
612       resi = 2;
613       if (NULL != unixpath)
614         resi++;
615       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
616       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
617       i = 0;
618       if (NULL != unixpath)
619       {
620         add_unixpath (saddrs, saddrlens, unixpath, abstract);
621         i++;
622       }
623       saddrlens[i] = sizeof (struct sockaddr_in6);
624       saddrs[i] = GNUNET_malloc (saddrlens[i]);
625 #if HAVE_SOCKADDR_IN_SIN_LEN
626       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
627 #endif
628       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
629       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
630       i++;
631       saddrlens[i] = sizeof (struct sockaddr_in);
632       saddrs[i] = GNUNET_malloc (saddrlens[i]);
633 #if HAVE_SOCKADDR_IN_SIN_LEN
634       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
635 #endif
636       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
637       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
638     }
639   }
640   GNUNET_free_non_null (unixpath);
641   *addrs = saddrs;
642   *addr_lens = saddrlens;
643   return resi;
644 }
645
646
647 /**
648  * Signal our client that we will start or stop the
649  * service.
650  *
651  * @param client who is being signalled
652  * @param name name of the service
653  * @param request_id id of the request that is being responded to.
654  * @param result message type to send
655  * @return NULL if it was not found
656  */
657 static void
658 signal_result (struct GNUNET_SERVICE_Client *client,
659                const char *name,
660                uint64_t request_id,
661                enum GNUNET_ARM_Result result)
662 {
663   struct GNUNET_MQ_Envelope *env;
664   struct GNUNET_ARM_ResultMessage *msg;
665
666   env = GNUNET_MQ_msg (msg,
667                        GNUNET_MESSAGE_TYPE_ARM_RESULT);
668   msg->result = htonl (result);
669   msg->arm_msg.request_id = GNUNET_htonll (request_id);
670   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
671                   env);
672 }
673
674
675 /**
676  * Tell all clients about status change of a service.
677  *
678  * @param name name of the service
679  * @param status message type to send
680  * @param unicast if not NULL, send to this client only.
681  *                otherwise, send to all clients in the notifier
682  */
683 static void
684 broadcast_status (const char *name,
685                   enum GNUNET_ARM_ServiceStatus status,
686                   struct GNUNET_SERVICE_Client *unicast)
687 {
688   struct GNUNET_MQ_Envelope *env;
689   struct GNUNET_ARM_StatusMessage *msg;
690   size_t namelen;
691
692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
693               "Sending status %u of service `%s' to client\n",
694               (unsigned int) status,
695               name);
696   namelen = strlen (name) + 1;
697   env = GNUNET_MQ_msg_extra (msg,
698                              namelen,
699                              GNUNET_MESSAGE_TYPE_ARM_STATUS);
700   msg->status = htonl ((uint32_t) (status));
701   GNUNET_memcpy ((char *) &msg[1],
702                  name,
703                  namelen);
704   if (NULL == unicast)
705   {
706     if (NULL != notifier)
707       GNUNET_notification_context_broadcast (notifier,
708                                              &msg->header,
709                                              GNUNET_YES);
710     GNUNET_MQ_discard (env);
711   }
712   else
713   {
714     GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (unicast),
715                     env);
716   }
717 }
718
719
720 /**
721  * Actually start the process for the given service.
722  *
723  * @param sl identifies service to start
724  * @param client that asked to start the service (may be NULL)
725  * @param request_id id of the request in response to which the process is
726  *                   being started. 0 if starting was not requested.
727  */
728 static void
729 start_process (struct ServiceList *sl,
730                struct GNUNET_SERVICE_Client *client,
731                uint64_t request_id)
732 {
733   char *loprefix;
734   char *options;
735   int use_debug;
736   int is_simple_service;
737   struct ServiceListeningInfo *sli;
738   SOCKTYPE *lsocks;
739   unsigned int ls;
740   char *binary;
741   char *quotedbinary;
742
743   /* calculate listen socket list */
744   lsocks = NULL;
745   ls = 0;
746   for (sli = sl->listen_head; NULL != sli; sli = sli->next)
747     {
748       GNUNET_array_append (lsocks, ls,
749                            GNUNET_NETWORK_get_fd (sli->listen_socket));
750       if (NULL != sli->accept_task)
751         {
752           GNUNET_SCHEDULER_cancel (sli->accept_task);
753           sli->accept_task = NULL;
754         }
755     }
756 #if WINDOWS
757   GNUNET_array_append (lsocks,
758                        ls,
759                        INVALID_SOCKET);
760 #else
761   GNUNET_array_append (lsocks,
762                        ls,
763                        -1);
764 #endif
765
766   /* obtain configuration */
767   if (GNUNET_OK !=
768       GNUNET_CONFIGURATION_get_value_string (cfg,
769                                              sl->name,
770                                              "PREFIX",
771                                              &loprefix))
772     loprefix = GNUNET_strdup (prefix_command);
773   else
774     loprefix = GNUNET_CONFIGURATION_expand_dollar (cfg,
775                                                    loprefix);
776   if (GNUNET_OK !=
777       GNUNET_CONFIGURATION_get_value_string (cfg,
778                                              sl->name,
779                                              "OPTIONS",
780                                              &options))
781     options = NULL;
782   else
783     options = GNUNET_CONFIGURATION_expand_dollar (cfg,
784                                                   options);
785   {
786     char *new_options;
787     char *optpos;
788     char *fin_options;
789
790     fin_options = GNUNET_strdup (final_option);
791     /* replace '{}' with service name */
792     while (NULL != (optpos = strstr (fin_options,
793                                      "{}")))
794     {
795       /* terminate string at opening parenthesis */
796       *optpos = 0;
797       GNUNET_asprintf (&new_options,
798                        "%s%s%s",
799                        fin_options,
800                        sl->name,
801                        optpos + 2);
802       GNUNET_free (fin_options);
803       fin_options = new_options;
804     }
805     if (NULL != options)
806     {
807       /* combine "fin_options" with "options" */
808       optpos = options;
809       GNUNET_asprintf (&options,
810                        "%s %s",
811                        fin_options,
812                        optpos);
813       GNUNET_free (fin_options);
814       GNUNET_free (optpos);
815     }
816     else
817     {
818       /* only have "fin_options", use that */
819       options = fin_options;
820     }
821   }
822   options = GNUNET_CONFIGURATION_expand_dollar (cfg,
823                                                 options);
824   use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg,
825                                                     sl->name,
826                                                     "DEBUG");
827   {
828     const char *service_type = NULL;
829     const char *choices[] = { "GNUNET", "SIMPLE", NULL };
830
831     is_simple_service = GNUNET_NO;
832     if ( (GNUNET_OK ==
833           GNUNET_CONFIGURATION_get_value_choice (cfg,
834                                                  sl->name,
835                                                  "TYPE",
836                                                  choices,
837                                                  &service_type)) &&
838          (0 == strcasecmp (service_type, "SIMPLE")) )
839       is_simple_service = GNUNET_YES;
840   }
841
842   GNUNET_assert (NULL == sl->proc);
843   if (GNUNET_YES == is_simple_service)
844   {
845     /* A simple service will receive no GNUnet specific
846        command line options. */
847     binary = GNUNET_strdup (sl->binary);
848     binary = GNUNET_CONFIGURATION_expand_dollar (cfg, binary);
849     GNUNET_asprintf (&quotedbinary,
850                      "\"%s\"",
851                      sl->binary);
852     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                 "Starting simple service `%s' using binary `%s'\n",
854                 sl->name, sl->binary);
855     /* FIXME: dollar expansion should only be done outside
856      * of ''-quoted strings, escaping should be considered. */
857     if (NULL != options)
858       options = GNUNET_CONFIGURATION_expand_dollar (cfg, options);
859     sl->proc =
860       GNUNET_OS_start_process_s (sl->pipe_control,
861                                  GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
862                                  lsocks,
863                                  loprefix,
864                                  quotedbinary,
865                                  options,
866                                  NULL);
867   }
868   else
869   {
870     /* actually start process */
871     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
872                 "Starting service `%s' using binary `%s' and configuration `%s'\n",
873                 sl->name, sl->binary, sl->config);
874     binary = GNUNET_OS_get_libexec_binary_path (sl->binary);
875     GNUNET_asprintf (&quotedbinary,
876                      "\"%s\"",
877                      binary);
878
879     if (GNUNET_YES == use_debug)
880     {
881       if (NULL == sl->config)
882         sl->proc =
883           GNUNET_OS_start_process_s (sl->pipe_control,
884                                      GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
885                                      lsocks,
886                                      loprefix,
887                                      quotedbinary,
888                                      "-L", "DEBUG",
889                                      options,
890                                      NULL);
891       else
892         sl->proc =
893             GNUNET_OS_start_process_s (sl->pipe_control,
894                                        GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
895                                        lsocks,
896                                        loprefix,
897                                        quotedbinary,
898                                        "-c", sl->config,
899                                        "-L", "DEBUG",
900                                        options,
901                                        NULL);
902     }
903     else
904     {
905       if (NULL == sl->config)
906         sl->proc =
907             GNUNET_OS_start_process_s (sl->pipe_control,
908                                        GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
909                                        lsocks,
910                                        loprefix,
911                                        quotedbinary,
912                                        options,
913                                        NULL);
914       else
915         sl->proc =
916             GNUNET_OS_start_process_s (sl->pipe_control,
917                                        GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
918                                        lsocks,
919                                        loprefix,
920                                        quotedbinary,
921                                        "-c", sl->config,
922                                        options,
923                                        NULL);
924     }
925   }
926   GNUNET_free (binary);
927   GNUNET_free (quotedbinary);
928   if (NULL == sl->proc)
929   {
930     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
931                 _("Failed to start service `%s'\n"),
932                 sl->name);
933     if (client)
934       signal_result (client,
935                      sl->name,
936                      request_id,
937                      GNUNET_ARM_RESULT_START_FAILED);
938   }
939   else
940   {
941     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
942                 _("Starting service `%s'\n"),
943                 sl->name);
944     broadcast_status (sl->name,
945                       GNUNET_ARM_SERVICE_STARTING,
946                       NULL);
947     if (client)
948       signal_result (client,
949                      sl->name,
950                      request_id,
951                      GNUNET_ARM_RESULT_STARTING);
952   }
953   /* clean up */
954   GNUNET_free (loprefix);
955   GNUNET_free (options);
956   GNUNET_array_grow (lsocks,
957                      ls,
958                      0);
959 }
960
961
962 /**
963  * Find the process with the given service
964  * name in the given list and return it.
965  *
966  * @param name which service entry to look up
967  * @return NULL if it was not found
968  */
969 static struct ServiceList *
970 find_service (const char *name)
971 {
972   struct ServiceList *sl;
973
974   sl = running_head;
975   while (sl != NULL)
976     {
977       if (0 == strcasecmp (sl->name, name))
978         return sl;
979       sl = sl->next;
980     }
981   return NULL;
982 }
983
984
985 /**
986  * First connection has come to the listening socket associated with the service,
987  * create the service in order to relay the incoming connection to it
988  *
989  * @param cls callback data, `struct ServiceListeningInfo` describing a listen socket
990  */
991 static void
992 accept_connection (void *cls)
993 {
994   struct ServiceListeningInfo *sli = cls;
995   struct ServiceList *sl = sli->sl;
996
997   sli->accept_task = NULL;
998   GNUNET_assert (GNUNET_NO == in_shutdown);
999   start_process (sl, NULL, 0);
1000 }
1001
1002
1003 /**
1004  * Creating a listening socket for each of the service's addresses and
1005  * wait for the first incoming connection to it
1006  *
1007  * @param sa address associated with the service
1008  * @param addr_len length of @a sa
1009  * @param sl service entry for the service in question
1010  */
1011 static void
1012 create_listen_socket (struct sockaddr *sa,
1013                       socklen_t addr_len,
1014                       struct ServiceList *sl)
1015 {
1016   static int on = 1;
1017   struct GNUNET_NETWORK_Handle *sock;
1018   struct ServiceListeningInfo *sli;
1019 #ifndef WINDOWS
1020   int match_uid;
1021   int match_gid;
1022 #endif
1023
1024   switch (sa->sa_family)
1025   {
1026   case AF_INET:
1027     sock = GNUNET_NETWORK_socket_create (PF_INET,
1028                                          SOCK_STREAM,
1029                                          0);
1030     break;
1031   case AF_INET6:
1032     sock = GNUNET_NETWORK_socket_create (PF_INET6,
1033                                          SOCK_STREAM,
1034                                          0);
1035     break;
1036   case AF_UNIX:
1037     if (0 == strcmp (GNUNET_a2s (sa,
1038                                  addr_len),
1039                      "@"))      /* Do not bind to blank UNIX path! */
1040       return;
1041     sock = GNUNET_NETWORK_socket_create (PF_UNIX,
1042                                          SOCK_STREAM,
1043                                          0);
1044     break;
1045   default:
1046     GNUNET_break (0);
1047     sock = NULL;
1048     errno = EAFNOSUPPORT;
1049     break;
1050   }
1051   if (NULL == sock)
1052   {
1053     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1054                 _("Unable to create socket for service `%s': %s\n"),
1055                 sl->name,
1056                 STRERROR (errno));
1057     GNUNET_free (sa);
1058     return;
1059   }
1060   if (GNUNET_OK !=
1061       GNUNET_NETWORK_socket_setsockopt (sock,
1062                                         SOL_SOCKET,
1063                                         SO_REUSEADDR,
1064                                         &on,
1065                                         sizeof (on)))
1066     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1067                          "setsockopt");
1068 #ifdef IPV6_V6ONLY
1069   if ( (sa->sa_family == AF_INET6) &&
1070        (GNUNET_OK !=
1071         GNUNET_NETWORK_socket_setsockopt (sock,
1072                                           IPPROTO_IPV6,
1073                                           IPV6_V6ONLY,
1074                                           &on,
1075                                           sizeof (on))) )
1076     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1077                          "setsockopt");
1078 #endif
1079 #ifndef WINDOWS
1080   if (AF_UNIX == sa->sa_family)
1081     GNUNET_NETWORK_unix_precheck ((struct sockaddr_un *) sa);
1082 #endif
1083   if (GNUNET_OK !=
1084       GNUNET_NETWORK_socket_bind (sock,
1085                                   (const struct sockaddr *) sa,
1086                                   addr_len))
1087   {
1088     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1089                 _("Unable to bind listening socket for service `%s' to address `%s': %s\n"),
1090                 sl->name,
1091                 GNUNET_a2s (sa,
1092                             addr_len),
1093                 STRERROR (errno));
1094     GNUNET_break (GNUNET_OK ==
1095                   GNUNET_NETWORK_socket_close (sock));
1096     GNUNET_free (sa);
1097     return;
1098   }
1099 #ifndef WINDOWS
1100   if ((AF_UNIX == sa->sa_family)
1101 #ifdef LINUX
1102       /* Permission settings are not required when abstract sockets are used */
1103       && ('\0' != ((const struct sockaddr_un *)sa)->sun_path[0])
1104 #endif
1105       )
1106   {
1107     match_uid =
1108       GNUNET_CONFIGURATION_get_value_yesno (cfg,
1109                                             sl->name,
1110                                             "UNIX_MATCH_UID");
1111     match_gid =
1112       GNUNET_CONFIGURATION_get_value_yesno (cfg,
1113                                             sl->name,
1114                                             "UNIX_MATCH_GID");
1115     GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sa)->sun_path,
1116                                  match_uid,
1117                                  match_gid);
1118
1119   }
1120 #endif
1121   if (GNUNET_OK !=
1122       GNUNET_NETWORK_socket_listen (sock, 5))
1123   {
1124     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1125                          "listen");
1126     GNUNET_break (GNUNET_OK ==
1127                   GNUNET_NETWORK_socket_close (sock));
1128     GNUNET_free (sa);
1129     return;
1130   }
1131   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1132               _("ARM now monitors connections to service `%s' at `%s'\n"),
1133               sl->name,
1134               GNUNET_a2s (sa,
1135                           addr_len));
1136   sli = GNUNET_new (struct ServiceListeningInfo);
1137   sli->service_addr = sa;
1138   sli->service_addr_len = addr_len;
1139   sli->listen_socket = sock;
1140   sli->sl = sl;
1141   sli->accept_task
1142     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1143                                      sock,
1144                                      &accept_connection, sli);
1145   GNUNET_CONTAINER_DLL_insert (sl->listen_head,
1146                                sl->listen_tail,
1147                                sli);
1148 }
1149
1150
1151 /**
1152  * Remove and free an entry in the service list.  Listen sockets
1153  * must have already been cleaned up.  Only to be called during shutdown.
1154  *
1155  * @param sl entry to free
1156  */
1157 static void
1158 free_service (struct ServiceList *sl)
1159 {
1160   GNUNET_assert (GNUNET_YES == in_shutdown);
1161   GNUNET_CONTAINER_DLL_remove (running_head,
1162                                running_tail,
1163                                sl);
1164   GNUNET_assert (NULL == sl->listen_head);
1165   GNUNET_free_non_null (sl->config);
1166   GNUNET_free_non_null (sl->binary);
1167   GNUNET_free (sl->name);
1168   GNUNET_free (sl);
1169 }
1170
1171
1172 /**
1173  * Check START-message.
1174  *
1175  * @param cls identification of the client
1176  * @param amsg the actual message
1177  * @return #GNUNET_OK to keep the connection open,
1178  *         #GNUNET_SYSERR to close it (signal serious error)
1179  */
1180 static int
1181 check_start (void *cls,
1182              const struct GNUNET_ARM_Message *amsg)
1183 {
1184   uint16_t size;
1185   const char *servicename;
1186
1187   size = ntohs (amsg->header.size) - sizeof (struct GNUNET_ARM_Message);
1188   servicename = (const char *) &amsg[1];
1189   if ( (0 == size) ||
1190        (servicename[size - 1] != '\0') )
1191   {
1192     GNUNET_break (0);
1193     return GNUNET_SYSERR;
1194   }
1195   return GNUNET_OK;
1196 }
1197
1198
1199 /**
1200  * Handle START-message.
1201  *
1202  * @param cls identification of the client
1203  * @param amsg the actual message
1204  */
1205 static void
1206 handle_start (void *cls,
1207               const struct GNUNET_ARM_Message *amsg)
1208 {
1209   struct GNUNET_SERVICE_Client *client = cls;
1210   const char *servicename;
1211   struct ServiceList *sl;
1212   uint64_t request_id;
1213
1214   request_id = GNUNET_ntohll (amsg->request_id);
1215   servicename = (const char *) &amsg[1];
1216   GNUNET_SERVICE_client_continue (client);
1217   if (GNUNET_YES == in_shutdown)
1218   {
1219     signal_result (client,
1220                    servicename,
1221                    request_id,
1222                    GNUNET_ARM_RESULT_IN_SHUTDOWN);
1223     return;
1224   }
1225   sl = find_service (servicename);
1226   if (NULL == sl)
1227   {
1228     signal_result (client,
1229                    servicename,
1230                    request_id,
1231                    GNUNET_ARM_RESULT_IS_NOT_KNOWN);
1232     return;
1233   }
1234   sl->force_start = GNUNET_YES;
1235   if (NULL != sl->proc)
1236   {
1237     signal_result (client,
1238                    servicename,
1239                    request_id,
1240                    GNUNET_ARM_RESULT_IS_STARTED_ALREADY);
1241     return;
1242   }
1243   start_process (sl,
1244                  client,
1245                  request_id);
1246 }
1247
1248
1249 /**
1250  * Start a shutdown sequence.
1251  *
1252  * @param cls closure (refers to service)
1253  */
1254 static void
1255 trigger_shutdown (void *cls)
1256 {
1257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258               "Triggering shutdown\n");
1259   GNUNET_SCHEDULER_shutdown ();
1260 }
1261
1262
1263 /**
1264  * Check STOP-message.
1265  *
1266  * @param cls identification of the client
1267  * @param amsg the actual message
1268  * @return #GNUNET_OK to keep the connection open,
1269  *         #GNUNET_SYSERR to close it (signal serious error)
1270  */
1271 static int
1272 check_stop (void *cls,
1273             const struct GNUNET_ARM_Message *amsg)
1274 {
1275   uint16_t size;
1276   const char *servicename;
1277
1278   size = ntohs (amsg->header.size) - sizeof (struct GNUNET_ARM_Message);
1279   servicename = (const char *) &amsg[1];
1280   if ( (0 == size) ||
1281        (servicename[size - 1] != '\0') )
1282   {
1283     GNUNET_break (0);
1284     return GNUNET_SYSERR;
1285   }
1286   return GNUNET_OK;
1287 }
1288
1289
1290 /**
1291  * Handle STOP-message.
1292  *
1293  * @param cls identification of the client
1294  * @param amsg the actual message
1295  */
1296 static void
1297 handle_stop (void *cls,
1298              const struct GNUNET_ARM_Message *amsg)
1299 {
1300   struct GNUNET_SERVICE_Client *client = cls;
1301   struct ServiceList *sl;
1302   const char *servicename;
1303   uint64_t request_id;
1304
1305   request_id = GNUNET_ntohll (amsg->request_id);
1306   servicename = (const char *) &amsg[1];
1307   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1308               _("Preparing to stop `%s'\n"),
1309               servicename);
1310   GNUNET_SERVICE_client_continue (client);
1311   if (0 == strcasecmp (servicename,
1312                        "arm"))
1313   {
1314     broadcast_status (servicename,
1315                       GNUNET_ARM_SERVICE_STOPPING,
1316                       NULL);
1317     signal_result (client,
1318                    servicename,
1319                    request_id,
1320                    GNUNET_ARM_RESULT_STOPPING);
1321     GNUNET_SERVICE_client_persist (client);
1322     GNUNET_SCHEDULER_add_now (&trigger_shutdown,
1323                               NULL);
1324     return;
1325   }
1326   sl = find_service (servicename);
1327   if (NULL == sl)
1328   {
1329     signal_result (client,
1330                    servicename,
1331                    request_id,
1332                    GNUNET_ARM_RESULT_IS_NOT_KNOWN);
1333     return;
1334   }
1335   sl->force_start = GNUNET_NO;
1336   if (GNUNET_YES == in_shutdown)
1337   {
1338     /* shutdown in progress */
1339     signal_result (client,
1340                    servicename,
1341                    request_id,
1342                    GNUNET_ARM_RESULT_IN_SHUTDOWN);
1343     return;
1344   }
1345   if (NULL != sl->killing_client)
1346   {
1347     /* killing already in progress */
1348     signal_result (client,
1349                    servicename,
1350                    request_id,
1351                    GNUNET_ARM_RESULT_IS_STOPPING_ALREADY);
1352     return;
1353   }
1354   if (NULL == sl->proc)
1355   {
1356     /* process is down */
1357     signal_result (client,
1358                    servicename,
1359                    request_id,
1360                    GNUNET_ARM_RESULT_IS_STOPPED_ALREADY);
1361     return;
1362   }
1363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364               "Sending kill signal to service `%s', waiting for process to die.\n",
1365               servicename);
1366   broadcast_status (servicename,
1367                     GNUNET_ARM_SERVICE_STOPPING,
1368                     NULL);
1369   /* no signal_start - only when it's STOPPED */
1370   sl->killed_at = GNUNET_TIME_absolute_get ();
1371   if (0 != GNUNET_OS_process_kill (sl->proc,
1372                                    GNUNET_TERM_SIG))
1373     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1374                          "kill");
1375   sl->killing_client = client;
1376   sl->killing_client_request_id = request_id;
1377 }
1378
1379
1380 /**
1381  * Handle LIST-message.
1382  *
1383  * @param cls identification of the client
1384  * @param message the actual message
1385  */
1386 static void
1387 handle_list (void *cls,
1388              const struct GNUNET_ARM_Message *request)
1389 {
1390   struct GNUNET_SERVICE_Client *client = cls;
1391   struct GNUNET_MQ_Envelope *env;
1392   struct GNUNET_ARM_ListResultMessage *msg;
1393   size_t string_list_size;
1394   struct ServiceList *sl;
1395   uint16_t count;
1396   char *pos;
1397
1398   GNUNET_break (0 == ntohl (request->reserved));
1399   count = 0;
1400   string_list_size = 0;
1401
1402   /* first count the running processes get their name's size */
1403   for (sl = running_head; NULL != sl; sl = sl->next)
1404   {
1405     if (NULL != sl->proc)
1406     {
1407       string_list_size += strlen (sl->name);
1408       string_list_size += strlen (sl->binary);
1409       string_list_size += 4;
1410       count++;
1411     }
1412   }
1413
1414   env = GNUNET_MQ_msg_extra (msg,
1415                              string_list_size,
1416                              GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT);
1417   msg->arm_msg.request_id = request->request_id;
1418   msg->count = htons (count);
1419
1420   pos = (char *) &msg[1];
1421   for (sl = running_head; NULL != sl; sl = sl->next)
1422   {
1423     if (NULL != sl->proc)
1424     {
1425       size_t s = strlen (sl->name) + strlen (sl->binary) + 4;
1426       GNUNET_snprintf (pos,
1427                        s,
1428                        "%s (%s)",
1429                        sl->name,
1430                        sl->binary);
1431       pos += s;
1432     }
1433   }
1434   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
1435                   env);
1436   GNUNET_SERVICE_client_continue (client);
1437 }
1438
1439
1440 /**
1441  * Handle TEST-message by sending back TEST.
1442  *
1443  * @param cls identification of the client
1444  * @param message the actual message
1445  */
1446 static void
1447 handle_test (void *cls,
1448              const struct GNUNET_MessageHeader *message)
1449 {
1450   struct GNUNET_SERVICE_Client *client = cls;
1451   struct GNUNET_MQ_Envelope *env;
1452   struct GNUNET_MessageHeader *msg;
1453
1454   env = GNUNET_MQ_msg (msg,
1455                        GNUNET_MESSAGE_TYPE_ARM_TEST);
1456   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client),
1457                   env);
1458   GNUNET_SERVICE_client_continue (client);
1459 }
1460
1461
1462 /**
1463  * We are done with everything.  Stop remaining
1464  * tasks, signal handler and the server.
1465  */
1466 static void
1467 do_shutdown ()
1468 {
1469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1470               "Last shutdown phase\n");
1471   if (NULL != notifier)
1472   {
1473     GNUNET_notification_context_destroy (notifier);
1474     notifier = NULL;
1475   }
1476   if (NULL != service)
1477   {
1478     GNUNET_SERVICE_shutdown (service);
1479     service = NULL;
1480   }
1481   if (NULL != child_death_task)
1482   {
1483     GNUNET_SCHEDULER_cancel (child_death_task);
1484     child_death_task = NULL;
1485   }
1486 }
1487
1488
1489 /**
1490  * Count how many services are still active.
1491  *
1492  * @param running_head list of services
1493  * @return number of active services found
1494  */
1495 static unsigned int
1496 list_count (struct ServiceList *running_head)
1497 {
1498   struct ServiceList *i;
1499   unsigned int res;
1500
1501   for (res = 0, i = running_head; i; i = i->next, res++)
1502     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1503                 "%s\n",
1504                 i->name);
1505   return res;
1506 }
1507
1508
1509 /**
1510  * Task run for shutdown.
1511  *
1512  * @param cls closure, NULL if we need to self-restart
1513  */
1514 static void
1515 shutdown_task (void *cls)
1516 {
1517   struct ServiceList *pos;
1518   struct ServiceList *nxt;
1519   struct ServiceListeningInfo *sli;
1520
1521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522               "First shutdown phase\n");
1523   if (NULL != child_restart_task)
1524   {
1525     GNUNET_SCHEDULER_cancel (child_restart_task);
1526     child_restart_task = NULL;
1527   }
1528   in_shutdown = GNUNET_YES;
1529   /* first, stop listening */
1530   for (pos = running_head; NULL != pos; pos = pos->next)
1531   {
1532     while (NULL != (sli = pos->listen_head))
1533     {
1534       GNUNET_CONTAINER_DLL_remove (pos->listen_head,
1535                                    pos->listen_tail,
1536                                    sli);
1537       if (NULL != sli->accept_task)
1538       {
1539         GNUNET_SCHEDULER_cancel (sli->accept_task);
1540         sli->accept_task = NULL;
1541       }
1542       GNUNET_break (GNUNET_OK ==
1543                     GNUNET_NETWORK_socket_close (sli->listen_socket));
1544       GNUNET_free (sli->service_addr);
1545       GNUNET_free (sli);
1546     }
1547   }
1548   /* then, shutdown all existing service processes */
1549   nxt = running_head;
1550   while (NULL != (pos = nxt))
1551   {
1552     nxt = pos->next;
1553     if (NULL != pos->proc)
1554     {
1555       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1556                   "Stopping service `%s'\n",
1557                   pos->name);
1558       pos->killed_at = GNUNET_TIME_absolute_get ();
1559       if (0 != GNUNET_OS_process_kill (pos->proc,
1560                                        GNUNET_TERM_SIG))
1561         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1562                              "kill");
1563     }
1564     else
1565     {
1566       free_service (pos);
1567     }
1568   }
1569   /* finally, should all service processes be already gone, terminate for real */
1570   if (NULL == running_head)
1571     do_shutdown ();
1572   else
1573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574                 "Delaying shutdown, have %u childs still running\n",
1575                 list_count (running_head));
1576 }
1577
1578
1579 /**
1580  * Task run whenever it is time to restart a child that died.
1581  *
1582  * @param cls closure, always NULL
1583  */
1584 static void
1585 delayed_restart_task (void *cls)
1586
1587 {
1588   struct ServiceList *sl;
1589   struct GNUNET_TIME_Relative lowestRestartDelay;
1590   struct ServiceListeningInfo *sli;
1591
1592   child_restart_task = NULL;
1593   GNUNET_assert (GNUNET_NO == in_shutdown);
1594   lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL;
1595
1596   /* check for services that need to be restarted due to
1597    * configuration changes or because the last restart failed */
1598   for (sl = running_head; NULL != sl; sl = sl->next)
1599   {
1600     if (NULL != sl->proc)
1601       continue;
1602     /* service is currently not running */
1603     if (0 == GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value_us)
1604     {
1605       /* restart is now allowed */
1606       if (sl->force_start)
1607       {
1608         /* process should run by default, start immediately */
1609         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1610                     _("Restarting service `%s'.\n"),
1611                     sl->name);
1612         start_process (sl,
1613                        NULL,
1614                        0);
1615       }
1616       else
1617       {
1618         /* process is run on-demand, ensure it is re-started if there is demand */
1619         for (sli = sl->listen_head; NULL != sli; sli = sli->next)
1620           if (NULL == sli->accept_task)
1621           {
1622             /* accept was actually paused, so start it again */
1623             sli->accept_task
1624               = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1625                                                sli->listen_socket,
1626                                                &accept_connection,
1627                                                sli);
1628           }
1629       }
1630     }
1631     else
1632     {
1633       /* update calculation for earliest time to reactivate a service */
1634       lowestRestartDelay =
1635         GNUNET_TIME_relative_min (lowestRestartDelay,
1636                                   GNUNET_TIME_absolute_get_remaining
1637                                   (sl->restart_at));
1638     }
1639   }
1640   if (lowestRestartDelay.rel_value_us != GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
1641   {
1642     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1643                 "Will restart process in %s\n",
1644                 GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay,
1645                                                         GNUNET_YES));
1646     child_restart_task =
1647       GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay,
1648                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1649                                                   &delayed_restart_task,
1650                                                   NULL);
1651   }
1652 }
1653
1654
1655 /**
1656  * Task triggered whenever we receive a SIGCHLD (child
1657  * process died).
1658  *
1659  * @param cls closure, NULL if we need to self-restart
1660  */
1661 static void
1662 maint_child_death (void *cls)
1663 {
1664   struct ServiceList *pos;
1665   struct ServiceList *next;
1666   struct ServiceListeningInfo *sli;
1667   const char *statstr;
1668   int statcode;
1669   int ret;
1670   char c[16];
1671   enum GNUNET_OS_ProcessStatusType statusType;
1672   unsigned long statusCode;
1673   const struct GNUNET_DISK_FileHandle *pr;
1674
1675   pr = GNUNET_DISK_pipe_handle (sigpipe,
1676                                 GNUNET_DISK_PIPE_END_READ);
1677   child_death_task = NULL;
1678   /* consume the signal */
1679   GNUNET_break (0 < GNUNET_DISK_file_read (pr,
1680                                            &c,
1681                                            sizeof (c)));
1682
1683   /* check for services that died (WAITPID) */
1684   next = running_head;
1685   while (NULL != (pos = next))
1686   {
1687     next = pos->next;
1688
1689     if (NULL == pos->proc)
1690     {
1691       if (GNUNET_YES == in_shutdown)
1692         free_service (pos);
1693       continue;
1694     }
1695 #if HAVE_WAIT4
1696     if (NULL != wait_file)
1697     {
1698       /* need to use 'wait4()' to obtain and log performance data */
1699       struct rusage ru;
1700       int status;
1701       pid_t pid;
1702
1703       pid = GNUNET_OS_process_get_pid (pos->proc);
1704       ret = wait4 (pid,
1705                    &status,
1706                    WNOHANG,
1707                    &ru);
1708       if (ret <= 0)
1709         continue; /* no process done */
1710       if (WIFEXITED (status))
1711       {
1712         statusType = GNUNET_OS_PROCESS_EXITED;
1713         statusCode = WEXITSTATUS (status);
1714       }
1715       else if (WIFSIGNALED (status))
1716       {
1717         statusType = GNUNET_OS_PROCESS_SIGNALED;
1718         statusCode = WTERMSIG (status);
1719       }
1720       else if (WIFSTOPPED (status))
1721       {
1722         statusType = GNUNET_OS_PROCESS_SIGNALED;
1723         statusCode = WSTOPSIG (status);
1724       }
1725 #ifdef WIFCONTINUED
1726       else if (WIFCONTINUED (status))
1727       {
1728         statusType = GNUNET_OS_PROCESS_RUNNING;
1729         statusCode = 0;
1730       }
1731 #endif
1732       else
1733       {
1734         statusType = GNUNET_OS_PROCESS_UNKNOWN;
1735         statusCode = 0;
1736       }
1737       if ( (GNUNET_OS_PROCESS_EXITED == statusType) ||
1738            (GNUNET_OS_PROCESS_SIGNALED == statusType) )
1739       {
1740         double utime = ru.ru_utime.tv_sec + (ru.ru_utime.tv_usec / 10e6);
1741         double stime = ru.ru_stime.tv_sec + (ru.ru_stime.tv_usec / 10e6);
1742         fprintf (wait_file,
1743                  "%s(%u) %.3f %.3f %llu %llu %llu %llu %llu\n",
1744                  pos->binary,
1745                  (unsigned int) pid,
1746                  utime,
1747                  stime,
1748                  (unsigned long long) ru.ru_maxrss,
1749                  (unsigned long long) ru.ru_inblock,
1750                  (unsigned long long) ru.ru_oublock,
1751                  (unsigned long long) ru.ru_nvcsw,
1752                  (unsigned long long) ru.ru_nivcsw);
1753       }
1754     }
1755     else /* continue with JUST this "if" as "else" (intentionally no brackets!) */
1756 #endif
1757     if ( (GNUNET_SYSERR ==
1758           (ret =
1759            GNUNET_OS_process_status (pos->proc,
1760                                      &statusType,
1761                                      &statusCode))) ||
1762          (ret == GNUNET_NO) ||
1763          (statusType == GNUNET_OS_PROCESS_STOPPED) ||
1764          (statusType == GNUNET_OS_PROCESS_UNKNOWN) ||
1765          (statusType == GNUNET_OS_PROCESS_RUNNING) )
1766       continue;
1767
1768     if (statusType == GNUNET_OS_PROCESS_EXITED)
1769     {
1770       statstr = _( /* process termination method */ "exit");
1771       statcode = statusCode;
1772     }
1773     else if (statusType == GNUNET_OS_PROCESS_SIGNALED)
1774     {
1775       statstr = _( /* process termination method */ "signal");
1776       statcode = statusCode;
1777     }
1778     else
1779     {
1780       statstr = _( /* process termination method */ "unknown");
1781       statcode = 0;
1782     }
1783     if (0 != pos->killed_at.abs_value_us)
1784     {
1785       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1786                   _("Service `%s' took %s to terminate\n"),
1787                   pos->name,
1788                   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->killed_at),
1789                                                           GNUNET_YES));
1790     }
1791     GNUNET_OS_process_destroy (pos->proc);
1792     pos->proc = NULL;
1793     broadcast_status (pos->name,
1794                       GNUNET_ARM_SERVICE_STOPPED,
1795                       NULL);
1796     if (NULL != pos->killing_client)
1797     {
1798       signal_result (pos->killing_client, pos->name,
1799                      pos->killing_client_request_id,
1800                      GNUNET_ARM_RESULT_STOPPED);
1801       pos->killing_client = NULL;
1802       pos->killing_client_request_id = 0;
1803     }
1804     if (GNUNET_YES != in_shutdown)
1805     {
1806       if ( (statusType == GNUNET_OS_PROCESS_EXITED) &&
1807            (statcode == 0) )
1808       {
1809         /* process terminated normally, allow restart at any time */
1810         pos->restart_at.abs_value_us = 0;
1811         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1812                     _("Service `%s' terminated normally, will restart at any time\n"),
1813                     pos->name);
1814         /* process can still be re-started on-demand, ensure it is re-started if there is demand */
1815         for (sli = pos->listen_head; NULL != sli; sli = sli->next)
1816         {
1817           GNUNET_break (NULL == sli->accept_task);
1818           sli->accept_task =
1819             GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1820                                            sli->listen_socket,
1821                                            &accept_connection,
1822                                            sli);
1823         }
1824       }
1825       else
1826       {
1827         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1828                     _("Service `%s' terminated with status %s/%d, will restart in %s\n"),
1829                     pos->name,
1830                     statstr,
1831                     statcode,
1832                     GNUNET_STRINGS_relative_time_to_string (pos->backoff,
1833                                                             GNUNET_YES));
1834         {
1835           /* Reduce backoff based on runtime of the process,
1836              so that there is a cool-down if a process actually
1837              runs for a while. */
1838           struct GNUNET_TIME_Relative runtime;
1839           unsigned int minutes;
1840
1841           runtime = GNUNET_TIME_absolute_get_duration (pos->restart_at);
1842           minutes = runtime.rel_value_us / GNUNET_TIME_UNIT_MINUTES.rel_value_us;
1843           if (minutes > 31)
1844             pos->backoff = GNUNET_TIME_UNIT_ZERO;
1845           else
1846             pos->backoff.rel_value_us <<= minutes;
1847         }
1848         /* schedule restart */
1849         pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff);
1850         pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff);
1851         if (NULL != child_restart_task)
1852           GNUNET_SCHEDULER_cancel (child_restart_task);
1853         child_restart_task
1854           = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1855                                                 &delayed_restart_task,
1856                                                 NULL);
1857       }
1858     }
1859     else
1860     {
1861       free_service (pos);
1862     }
1863   }
1864   child_death_task = GNUNET_SCHEDULER_add_read_file (
1865       GNUNET_TIME_UNIT_FOREVER_REL,
1866       pr,
1867       &maint_child_death, NULL);
1868   if ((NULL == running_head) && (GNUNET_YES == in_shutdown))
1869     do_shutdown ();
1870   else if (GNUNET_YES == in_shutdown)
1871     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1872         "Delaying shutdown after child's death, still have %u children\n",
1873         list_count (running_head));
1874
1875 }
1876
1877
1878 /**
1879  * Signal handler called for SIGCHLD.  Triggers the
1880  * respective handler by writing to the trigger pipe.
1881  */
1882 static void
1883 sighandler_child_death ()
1884 {
1885   static char c;
1886   int old_errno = errno;        /* back-up errno */
1887
1888   GNUNET_break (1 ==
1889                 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle (sigpipe,
1890                                                                  GNUNET_DISK_PIPE_END_WRITE),
1891                                         &c,
1892                                         sizeof (c)));
1893   errno = old_errno;            /* restore errno */
1894 }
1895
1896
1897 /**
1898  * Setup our service record for the given section in the configuration file
1899  * (assuming the section is for a service).
1900  *
1901  * @param cls unused
1902  * @param section a section in the configuration file
1903  * @return #GNUNET_OK (continue)
1904  */
1905 static void
1906 setup_service (void *cls,
1907                const char *section)
1908 {
1909   struct ServiceList *sl;
1910   char *binary;
1911   char *config;
1912   struct stat sbuf;
1913   struct sockaddr **addrs;
1914   socklen_t *addr_lens;
1915   int ret;
1916
1917   if (0 == strcasecmp (section,
1918                        "arm"))
1919     return;
1920   if (GNUNET_OK !=
1921       GNUNET_CONFIGURATION_get_value_string (cfg,
1922                                              section,
1923                                              "BINARY",
1924                                              &binary))
1925   {
1926     /* not a service section */
1927     return;
1928   }
1929   if ((GNUNET_YES ==
1930        GNUNET_CONFIGURATION_have_value (cfg,
1931                                         section,
1932                                         "USER_SERVICE")) &&
1933       (GNUNET_YES ==
1934        GNUNET_CONFIGURATION_get_value_yesno (cfg,
1935                                              section,
1936                                              "USER_SERVICE")))
1937   {
1938     if (GNUNET_NO == start_user)
1939     {
1940       GNUNET_free (binary);
1941       return; /* user service, and we don't deal with those */
1942     }
1943   }
1944   else
1945   {
1946     if (GNUNET_NO == start_system)
1947     {
1948       GNUNET_free (binary);
1949       return; /* system service, and we don't deal with those */
1950     }
1951   }
1952   sl = find_service (section);
1953   if (NULL != sl)
1954   {
1955     /* got the same section twice!? */
1956     GNUNET_break (0);
1957     GNUNET_free (binary);
1958     return;
1959   }
1960   config = NULL;
1961   if (( (GNUNET_OK !=
1962          GNUNET_CONFIGURATION_get_value_filename (cfg,
1963                                                   section,
1964                                                   "CONFIG",
1965                                                   &config)) &&
1966         (GNUNET_OK !=
1967          GNUNET_CONFIGURATION_get_value_filename (cfg,
1968                                                   "PATHS",
1969                                                   "DEFAULTCONFIG",
1970                                                   &config)) ) ||
1971       (0 != STAT (config, &sbuf)))
1972   {
1973     if (NULL != config)
1974     {
1975       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1976                                  section, "CONFIG",
1977                                  STRERROR (errno));
1978       GNUNET_free (config);
1979       config = NULL;
1980     }
1981   }
1982   sl = GNUNET_new (struct ServiceList);
1983   sl->name = GNUNET_strdup (section);
1984   sl->binary = binary;
1985   sl->config = config;
1986   sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
1987   sl->restart_at = GNUNET_TIME_UNIT_FOREVER_ABS;
1988 #if WINDOWS
1989   sl->pipe_control = GNUNET_YES;
1990 #else
1991   if (GNUNET_CONFIGURATION_have_value (cfg,
1992                                        section,
1993                                        "PIPECONTROL"))
1994     sl->pipe_control = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1995                                                              section,
1996                                                              "PIPECONTROL");
1997 #endif
1998   GNUNET_CONTAINER_DLL_insert (running_head,
1999                                running_tail,
2000                                sl);
2001   if (GNUNET_YES ==
2002       GNUNET_CONFIGURATION_get_value_yesno (cfg,
2003                                             section,
2004                                             "FORCESTART"))
2005   {
2006     sl->force_start = GNUNET_YES;
2007     if (GNUNET_YES ==
2008         GNUNET_CONFIGURATION_get_value_yesno (cfg,
2009                                               section,
2010                                               "NOARMBIND"))
2011       return;
2012   }
2013   else
2014   {
2015     if (GNUNET_YES !=
2016         GNUNET_CONFIGURATION_get_value_yesno (cfg,
2017                                               section,
2018                                               "AUTOSTART"))
2019       return;
2020   }
2021   if (0 >= (ret = get_server_addresses (section,
2022                                         cfg,
2023                                         &addrs,
2024                                         &addr_lens)))
2025     return;
2026   /* this will free (or capture) addrs[i] */
2027   for (unsigned int i = 0; i < ret; i++)
2028     create_listen_socket (addrs[i],
2029                           addr_lens[i],
2030                           sl);
2031   GNUNET_free (addrs);
2032   GNUNET_free (addr_lens);
2033 }
2034
2035
2036 /**
2037  * A client connected, mark as a monitoring client.
2038  *
2039  * @param cls closure
2040  * @param client identification of the client
2041  * @param mq queue to talk to @a client
2042  * @return @a client
2043  */
2044 static void *
2045 client_connect_cb (void *cls,
2046                    struct GNUNET_SERVICE_Client *client,
2047                    struct GNUNET_MQ_Handle *mq)
2048 {
2049   /* All clients are considered to be of the "monitor" kind
2050    * (that is, they don't affect ARM shutdown).
2051    */
2052   GNUNET_SERVICE_client_mark_monitor (client);
2053   return client;
2054 }
2055
2056
2057 /**
2058  * A client disconnected, clean up associated state.
2059  *
2060  * @param cls closure
2061  * @param client identification of the client
2062  * @param app_ctx must match @a client
2063  */
2064 static void
2065 client_disconnect_cb (void *cls,
2066                       struct GNUNET_SERVICE_Client *client,
2067                       void *app_ctx)
2068 {
2069   struct ServiceList *sl;
2070
2071   GNUNET_assert (client == app_ctx);
2072
2073   for (sl = running_head; NULL != sl; sl = sl->next)
2074     if (sl->killing_client == client)
2075       sl->killing_client = NULL;
2076 }
2077
2078
2079 /**
2080  * Handle MONITOR-message.
2081  *
2082  * @param cls identification of the client
2083  * @param message the actual message
2084  * @return #GNUNET_OK to keep the connection open,
2085  *         #GNUNET_SYSERR to close it (signal serious error)
2086  */
2087 static void
2088 handle_monitor (void *cls,
2089                 const struct GNUNET_MessageHeader *message)
2090 {
2091   struct GNUNET_SERVICE_Client *client = cls;
2092
2093   /* FIXME: might want to start by letting monitor know about
2094      services that are already running */
2095   /* Removal is handled by the server implementation, internally. */
2096   GNUNET_notification_context_add (notifier,
2097                                    GNUNET_SERVICE_client_get_mq (client));
2098   broadcast_status ("arm",
2099                     GNUNET_ARM_SERVICE_MONITORING_STARTED,
2100                     client);
2101   GNUNET_SERVICE_client_continue (client);
2102 }
2103
2104
2105 /**
2106  * Process arm requests.
2107  *
2108  * @param cls closure
2109  * @param serv the initialized service
2110  * @param c configuration to use
2111  */
2112 static void
2113 run (void *cls,
2114      const struct GNUNET_CONFIGURATION_Handle *c,
2115      struct GNUNET_SERVICE_Handle *serv)
2116 {
2117   struct ServiceList *sl;
2118
2119   cfg = c;
2120   service = serv;
2121   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
2122                                  NULL);
2123   child_death_task =
2124     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2125                                     GNUNET_DISK_pipe_handle (sigpipe,
2126                                                              GNUNET_DISK_PIPE_END_READ),
2127                                     &maint_child_death,
2128                                     NULL);
2129 #if HAVE_WAIT4
2130   if (GNUNET_OK ==
2131       GNUNET_CONFIGURATION_get_value_filename (cfg,
2132                                                "ARM",
2133                                                "RESOURCE_DIAGNOSTICS",
2134                                                &wait_filename))
2135   {
2136     wait_file = fopen (wait_filename,
2137                        "w");
2138     if (NULL == wait_file)
2139     {
2140       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2141                                 "fopen",
2142                                 wait_filename);
2143     }
2144   }
2145 #endif
2146   if (GNUNET_OK !=
2147       GNUNET_CONFIGURATION_get_value_string (cfg,
2148                                              "ARM",
2149                                              "GLOBAL_PREFIX",
2150                                              &prefix_command))
2151     prefix_command = GNUNET_strdup ("");
2152   else
2153     prefix_command = GNUNET_CONFIGURATION_expand_dollar (cfg,
2154                                                          prefix_command);
2155   if (GNUNET_OK !=
2156       GNUNET_CONFIGURATION_get_value_string (cfg,
2157                                              "ARM",
2158                                              "GLOBAL_POSTFIX",
2159                                              &final_option))
2160     final_option = GNUNET_strdup ("");
2161   else
2162     final_option = GNUNET_CONFIGURATION_expand_dollar (cfg,
2163                                                        final_option);
2164   if (GNUNET_YES ==
2165       GNUNET_CONFIGURATION_get_value_yesno (cfg,
2166                                             "ARM",
2167                                             "USER_ONLY"))
2168   {
2169     GNUNET_break (GNUNET_YES == start_user);
2170     start_system = GNUNET_NO;
2171   }
2172   if (GNUNET_YES ==
2173       GNUNET_CONFIGURATION_get_value_yesno (cfg,
2174                                             "ARM",
2175                                             "SYSTEM_ONLY"))
2176   {
2177     GNUNET_break (GNUNET_YES == start_system);
2178     start_user = GNUNET_NO;
2179   }
2180   GNUNET_CONFIGURATION_iterate_sections (cfg,
2181                                          &setup_service,
2182                                          NULL);
2183
2184   /* start default services... */
2185   for (sl = running_head; NULL != sl; sl = sl->next)
2186     if (GNUNET_YES == sl->force_start)
2187       start_process (sl,
2188                      NULL,
2189                      0);
2190   notifier = GNUNET_notification_context_create (MAX_NOTIFY_QUEUE);
2191 }
2192
2193
2194 /**
2195  * The main function for the arm service.
2196  *
2197  * @param argc number of arguments from the command line
2198  * @param argv command line arguments
2199  * @return 0 ok, 1 on error
2200  */
2201 int
2202 main (int argc,
2203       char *const *argv)
2204 {
2205   int ret;
2206   struct GNUNET_SIGNAL_Context *shc_chld;
2207   struct GNUNET_MQ_MessageHandler handlers[] = {
2208     GNUNET_MQ_hd_var_size (start,
2209                            GNUNET_MESSAGE_TYPE_ARM_START,
2210                            struct GNUNET_ARM_Message,
2211                            NULL),
2212     GNUNET_MQ_hd_var_size (stop,
2213                            GNUNET_MESSAGE_TYPE_ARM_STOP,
2214                            struct GNUNET_ARM_Message,
2215                            NULL),
2216     GNUNET_MQ_hd_fixed_size (monitor,
2217                              GNUNET_MESSAGE_TYPE_ARM_MONITOR,
2218                              struct GNUNET_MessageHeader,
2219                              NULL),
2220     GNUNET_MQ_hd_fixed_size (list,
2221                              GNUNET_MESSAGE_TYPE_ARM_LIST,
2222                              struct GNUNET_ARM_Message,
2223                              NULL),
2224     GNUNET_MQ_hd_fixed_size (test,
2225                              GNUNET_MESSAGE_TYPE_ARM_TEST,
2226                              struct GNUNET_MessageHeader,
2227                              NULL),
2228     GNUNET_MQ_handler_end ()
2229   };
2230
2231   sigpipe = GNUNET_DISK_pipe (GNUNET_NO,
2232                               GNUNET_NO,
2233                               GNUNET_NO,
2234                               GNUNET_NO);
2235   GNUNET_assert (NULL != sigpipe);
2236   shc_chld =
2237     GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD,
2238                                    &sighandler_child_death);
2239   ret = GNUNET_SERVICE_run_ (argc,
2240                              argv,
2241                              "arm",
2242                              GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN,
2243                              &run,
2244                              &client_connect_cb,
2245                              &client_disconnect_cb,
2246                              NULL,
2247                              handlers);
2248 #if HAVE_WAIT4
2249   if (NULL != wait_file)
2250   {
2251     fclose (wait_file);
2252     wait_file = NULL;
2253   }
2254   if (NULL != wait_filename)
2255   {
2256     GNUNET_free (wait_filename);
2257     wait_filename = NULL;
2258   }
2259 #endif
2260   GNUNET_SIGNAL_handler_uninstall (shc_chld);
2261   shc_chld = NULL;
2262   GNUNET_DISK_pipe_close (sigpipe);
2263   sigpipe = NULL;
2264   return ret;
2265 }
2266
2267
2268 #if defined(LINUX) && defined(__GLIBC__)
2269 #include <malloc.h>
2270
2271 /**
2272  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
2273  */
2274 void __attribute__ ((constructor)) GNUNET_ARM_memory_init ()
2275 {
2276   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
2277   mallopt (M_TOP_PAD, 1 * 1024);
2278   malloc_trim (0);
2279 }
2280 #endif
2281
2282
2283 /* end of gnunet-service-arm.c */