arm-specific
[oweals/gnunet.git] / src / util / service.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/service.c
23  * @brief functions related to starting services
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_common.h"
28 #include "gnunet_configuration_lib.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_getopt_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_service_lib.h"
37
38 #define DEBUG_SERVICE GNUNET_NO
39
40 /* ******************* access control ******************** */
41
42 /**
43  * @brief IPV4 network in CIDR notation.
44  */
45 struct IPv4NetworkSet
46 {
47   struct in_addr network;
48   struct in_addr netmask;
49 };
50
51 /**
52  * @brief network in CIDR notation for IPV6.
53  */
54 struct IPv6NetworkSet
55 {
56   struct in6_addr network;
57   struct in6_addr netmask;
58 };
59
60
61 /**
62  * Parse a network specification. The argument specifies
63  * a list of networks. The format is
64  * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
65  * with a semicolon). The network must be given in dotted-decimal
66  * notation. The netmask can be given in CIDR notation (/16) or
67  * in dotted-decimal (/255.255.0.0).
68  * <p>
69  * @param routeList a string specifying the forbidden networks
70  * @return the converted list, NULL if the synatx is flawed
71  */
72 static struct IPv4NetworkSet *
73 parse_ipv4_specification (const char *routeList)
74 {
75   unsigned int count;
76   unsigned int i;
77   unsigned int j;
78   unsigned int len;
79   int cnt;
80   unsigned int pos;
81   unsigned int temps[8];
82   int slash;
83   struct IPv4NetworkSet *result;
84
85   if (routeList == NULL)
86     return NULL;
87   len = strlen (routeList);
88   if (len == 0)
89     return NULL;
90   count = 0;
91   for (i = 0; i < len; i++)
92     if (routeList[i] == ';')
93       count++;
94   result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
95   /* add termination */
96   memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
97   i = 0;
98   pos = 0;
99   while (i < count)
100     {
101       cnt = sscanf (&routeList[pos],
102                     "%u.%u.%u.%u/%u.%u.%u.%u;",
103                     &temps[0],
104                     &temps[1],
105                     &temps[2],
106                     &temps[3], &temps[4], &temps[5], &temps[6], &temps[7]);
107       if (cnt == 8)
108         {
109           for (j = 0; j < 8; j++)
110             if (temps[j] > 0xFF)
111               {
112                 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
113                             _("Invalid format for IP: `%s'\n"),
114                             &routeList[pos]);
115                 GNUNET_free (result);
116                 return NULL;
117               }
118           result[i].network.s_addr
119             =
120             htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
121                    temps[3]);
122           result[i].netmask.s_addr =
123             htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
124                    temps[7]);
125           while (routeList[pos] != ';')
126             pos++;
127           pos++;
128           i++;
129           continue;
130         }
131       /* try second notation */
132       cnt = sscanf (&routeList[pos],
133                     "%u.%u.%u.%u/%u;",
134                     &temps[0], &temps[1], &temps[2], &temps[3], &slash);
135       if (cnt == 5)
136         {
137           for (j = 0; j < 4; j++)
138             if (temps[j] > 0xFF)
139               {
140                 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
141                             _("Invalid format for IP: `%s'\n"),
142                             &routeList[pos]);
143                 GNUNET_free (result);
144                 return NULL;
145               }
146           result[i].network.s_addr
147             =
148             htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
149                    temps[3]);
150           if ((slash <= 32) && (slash >= 0))
151             {
152               result[i].netmask.s_addr = 0;
153               while (slash > 0)
154                 {
155                   result[i].netmask.s_addr
156                     = (result[i].netmask.s_addr >> 1) + 0x80000000;
157                   slash--;
158                 }
159               result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
160               while (routeList[pos] != ';')
161                 pos++;
162               pos++;
163               i++;
164               continue;
165             }
166           else
167             {
168               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
169                           _
170                           ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
171                           slash);
172               GNUNET_free (result);
173               return NULL;      /* error */
174             }
175         }
176       /* try third notation */
177       slash = 32;
178       cnt = sscanf (&routeList[pos],
179                     "%u.%u.%u.%u;",
180                     &temps[0], &temps[1], &temps[2], &temps[3]);
181       if (cnt == 4)
182         {
183           for (j = 0; j < 4; j++)
184             if (temps[j] > 0xFF)
185               {
186                 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
187                             _("Invalid format for IP: `%s'\n"),
188                             &routeList[pos]);
189                 GNUNET_free (result);
190                 return NULL;
191               }
192           result[i].network.s_addr
193             =
194             htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
195                    temps[3]);
196           result[i].netmask.s_addr = 0;
197           while (slash > 0)
198             {
199               result[i].netmask.s_addr
200                 = (result[i].netmask.s_addr >> 1) + 0x80000000;
201               slash--;
202             }
203           result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
204           while (routeList[pos] != ';')
205             pos++;
206           pos++;
207           i++;
208           continue;
209         }
210       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
211                   _("Invalid format for IP: `%s'\n"), &routeList[pos]);
212       GNUNET_free (result);
213       return NULL;              /* error */
214     }
215   if (pos < strlen (routeList))
216     {
217       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
218                   _("Invalid format for IP: `%s'\n"), &routeList[pos]);
219       GNUNET_free (result);
220       return NULL;              /* oops */
221     }
222   return result;                /* ok */
223 }
224
225
226 /**
227  * Parse a network specification. The argument specifies
228  * a list of networks. The format is
229  * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
230  * with a semicolon). The network must be given in colon-hex
231  * notation.  The netmask must be given in CIDR notation (/16) or
232  * can be omitted to specify a single host.
233  * <p>
234  * @param routeListX a string specifying the forbidden networks
235  * @return the converted list, NULL if the synatx is flawed
236  */
237 static struct IPv6NetworkSet *
238 parse_ipv6_specification (const char *routeListX)
239 {
240   unsigned int count;
241   unsigned int i;
242   unsigned int len;
243   unsigned int pos;
244   int start;
245   int slash;
246   int ret;
247   char *routeList;
248   struct IPv6NetworkSet *result;
249   unsigned int bits;
250   unsigned int off;
251   int save;
252
253   if (routeListX == NULL)
254     return NULL;
255   len = strlen (routeListX);
256   if (len == 0)
257     return NULL;
258   routeList = GNUNET_strdup (routeListX);
259   count = 0;
260   for (i = 0; i < len; i++)
261     if (routeList[i] == ';')
262       count++;
263   if (routeList[len - 1] != ';')
264     {
265       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
266                   _
267                   ("Invalid network notation (does not end with ';': `%s')\n"),
268                   routeList);
269       GNUNET_free (routeList);
270       return NULL;
271     }
272
273   result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
274   memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
275   i = 0;
276   pos = 0;
277   while (i < count)
278     {
279       start = pos;
280       while (routeList[pos] != ';')
281         pos++;
282       slash = pos;
283       while ((slash >= start) && (routeList[slash] != '/'))
284         slash--;
285       if (slash < start)
286         {
287           memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
288           slash = pos;
289         }
290       else
291         {
292           routeList[pos] = '\0';
293           ret = inet_pton (AF_INET6,
294                            &routeList[slash + 1], &result[i].netmask);
295           if (ret <= 0)
296             {
297               save = errno;
298               if ((1 != SSCANF (&routeList[slash + 1],
299                                 "%u", &bits)) || (bits >= 128))
300                 {
301                   if (ret == 0)
302                     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
303                                 _("Wrong format `%s' for netmask\n"),
304                                 &routeList[slash + 1]);
305                   else
306                     {
307                       errno = save;
308                       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
309                                            "inet_pton");
310                     }
311                   GNUNET_free (result);
312                   GNUNET_free (routeList);
313                   return NULL;
314                 }
315               off = 0;
316               while (bits > 8)
317                 {
318                   result[i].netmask.s6_addr[off++] = 0xFF;
319                   bits -= 8;
320                 }
321               while (bits > 0)
322                 {
323                   result[i].netmask.s6_addr[off]
324                     = (result[i].netmask.s6_addr[off] >> 1) + 0x80;
325                   bits--;
326                 }
327             }
328         }
329       routeList[slash] = '\0';
330       ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
331       if (ret <= 0)
332         {
333           if (ret == 0)
334             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
335                         _("Wrong format `%s' for network\n"),
336                         &routeList[slash + 1]);
337           else
338             GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
339           GNUNET_free (result);
340           GNUNET_free (routeList);
341           return NULL;
342         }
343       pos++;
344       i++;
345     }
346   GNUNET_free (routeList);
347   return result;
348 }
349
350
351 /**
352  * Check if the given IP address is in the list of IP addresses.
353  *
354  * @param list a list of networks
355  * @param add the IP to check (in network byte order)
356  * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
357  */
358 static int
359 check_ipv4_listed (const struct IPv4NetworkSet *list,
360                    const struct in_addr *add)
361 {
362   int i;
363
364   i = 0;
365   if (list == NULL)
366     return GNUNET_NO;
367
368   while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
369     {
370       if ((add->s_addr & list[i].netmask.s_addr) ==
371           (list[i].network.s_addr & list[i].netmask.s_addr))
372         return GNUNET_YES;
373       i++;
374     }
375   return GNUNET_NO;
376 }
377
378 /**
379  * Check if the given IP address is in the list of IP addresses.
380  *
381  * @param list a list of networks
382  * @param ip the IP to check (in network byte order)
383  * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
384  */
385 static int
386 check_ipv6_listed (const struct IPv6NetworkSet *list,
387                    const struct in6_addr *ip)
388 {
389   unsigned int i;
390   unsigned int j;
391   struct in6_addr zero;
392
393   if (list == NULL)
394     return GNUNET_NO;
395
396   memset (&zero, 0, sizeof (struct in6_addr));
397   i = 0;
398 NEXT:
399   while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
400     {
401       for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
402         if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
403             (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
404           {
405             i++;
406             goto NEXT;
407           }
408       return GNUNET_YES;
409     }
410   return GNUNET_NO;
411 }
412
413
414 /* ****************** service struct ****************** */
415
416
417 /**
418  * Context for "service_task".
419  */
420 struct GNUNET_SERVICE_Context
421 {
422   /**
423    * Our configuration.
424    */
425   const struct GNUNET_CONFIGURATION_Handle *cfg;
426
427   /**
428    * Handle for the server.
429    */
430   struct GNUNET_SERVER_Handle *server;
431
432   /**
433    * Scheduler for the server.
434    */
435   struct GNUNET_SCHEDULER_Handle *sched;
436
437   /**
438    * NULL-terminated array of addresses to bind to.
439    */
440   struct sockaddr **addrs;
441
442   /**
443    * Name of our service.
444    */
445   const char *serviceName;
446
447   /**
448    * Main service-specific task to run.
449    */
450   GNUNET_SERVICE_Main task;
451
452   /**
453    * Closure for task.
454    */
455   void *task_cls;
456
457   /**
458    * IPv4 addresses that are not allowed to connect.
459    */
460   struct IPv4NetworkSet *v4_denied;
461
462   /**
463    * IPv6 addresses that are not allowed to connect.
464    */
465   struct IPv6NetworkSet *v6_denied;
466
467   /**
468    * IPv4 addresses that are allowed to connect (if not
469    * set, all are allowed).
470    */
471   struct IPv4NetworkSet *v4_allowed;
472
473   /**
474    * IPv6 addresses that are allowed to connect (if not
475    * set, all are allowed).
476    */
477   struct IPv6NetworkSet *v6_allowed;
478
479   /**
480    * My (default) message handlers.  Adjusted copy
481    * of "defhandlers".
482    */
483   struct GNUNET_SERVER_MessageHandler *my_handlers;
484
485   /**
486    * Idle timeout for server.
487    */
488   struct GNUNET_TIME_Relative timeout;
489
490   /**
491    * Maximum buffer size for the server.
492    */
493   size_t maxbuf;
494
495   /**
496    * Overall success/failure of the service start.
497    */
498   int ret;
499
500   /**
501    * If we are daemonizing, this FD is set to the
502    * pipe to the parent.  Send '.' if we started
503    * ok, '!' if not.  -1 if we are not daemonizing.
504    */
505   int ready_confirm_fd;
506
507   /**
508    * Do we close connections if we receive messages
509    * for which we have no handler?
510    */
511   int require_found;
512
513   /**
514    * Can clients ask us to initiate a shutdown?
515    */
516   int allow_shutdown;
517
518   /**
519    * Our options.
520    */
521   enum GNUNET_SERVICE_Options options;
522
523   /**
524    * Array of the lengths of the entries in addrs.
525    */
526   socklen_t * addrlens;
527
528 };
529
530
531 /* ****************** message handlers ****************** */
532
533 static size_t
534 write_test (void *cls, size_t size, void *buf)
535 {
536   struct GNUNET_SERVER_Client *client = cls;
537   struct GNUNET_MessageHeader *msg;
538
539   if (size < sizeof (struct GNUNET_MessageHeader))
540     {
541       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
542       return 0;                 /* client disconnected */
543     }
544   msg = (struct GNUNET_MessageHeader *) buf;
545   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
546   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
547   GNUNET_SERVER_receive_done (client, GNUNET_OK);
548   return sizeof (struct GNUNET_MessageHeader);
549 }
550
551 /**
552  * Handler for TEST message.
553  *
554  * @param cls closure (refers to service)
555  * @param client identification of the client
556  * @param message the actual message
557  */
558 static void
559 handle_test (void *cls,
560              struct GNUNET_SERVER_Client *client,
561              const struct GNUNET_MessageHeader *message)
562 {
563   /* simply bounce message back to acknowledge */
564   if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
565                                                    sizeof (struct
566                                                            GNUNET_MessageHeader),
567                                                    GNUNET_TIME_UNIT_FOREVER_REL,
568                                                    &write_test, client))
569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
570 }
571
572
573 /**
574  * Default handlers for all services.  Will be copied and the
575  * "callback_cls" fields will be replaced with the specific service
576  * struct.
577  */
578 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
579   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
580    sizeof (struct GNUNET_MessageHeader)},
581   {NULL, NULL, 0, 0}
582 };
583
584
585
586 /* ****************** service core routines ************** */
587
588
589 /**
590  * Check if access to the service is allowed from the given address.
591  */
592 static int
593 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
594 {
595   struct GNUNET_SERVICE_Context *sctx = cls;
596   const struct sockaddr_in *i4;
597   const struct sockaddr_in6 *i6;
598   int ret;
599
600   switch (addr->sa_family)
601     {
602     case AF_INET:
603       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
604       i4 = (const struct sockaddr_in *) addr;
605       ret = ((sctx->v4_allowed == NULL) ||
606              (check_ipv4_listed (sctx->v4_allowed,
607                                  &i4->sin_addr)))
608         && ((sctx->v4_denied == NULL) ||
609             (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
610       break;
611     case AF_INET6:
612       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
613       i6 = (const struct sockaddr_in6 *) addr;
614       ret = ((sctx->v6_allowed == NULL) ||
615              (check_ipv6_listed (sctx->v6_allowed,
616                                  &i6->sin6_addr)))
617         && ((sctx->v6_denied == NULL) ||
618             (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
619       break;
620     default:
621       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
622                   _("Unknown address family %d\n"), addr->sa_family);
623       return GNUNET_SYSERR;
624     }
625   if (ret != GNUNET_OK)
626     {
627       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
628                   _("Access from `%s' denied to service `%s'\n"),
629                   GNUNET_a2s (addr, addrlen), sctx->serviceName);
630     }
631   return ret;
632 }
633
634
635 /**
636  * Get the name of the file where we will
637  * write the PID of the service.
638  */
639 static char *
640 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
641 {
642
643   char *pif;
644
645   if (GNUNET_OK !=
646       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
647                                                sctx->serviceName,
648                                                "PIDFILE", &pif))
649     return NULL;
650   return pif;
651 }
652
653
654 /**
655  * Parse an IPv4 access control list.
656  */
657 static int
658 process_acl4 (struct IPv4NetworkSet **ret,
659               struct GNUNET_SERVICE_Context *sctx, const char *option)
660 {
661   char *opt;
662
663   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
664     return GNUNET_OK;
665   GNUNET_break (GNUNET_OK ==
666                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
667                                                        sctx->serviceName,
668                                                        option, &opt));
669   if (NULL == (*ret = parse_ipv4_specification (opt)))
670     {
671       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
672                   _
673                   ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
674                   opt, sctx->serviceName, option);
675       GNUNET_free (opt);
676       return GNUNET_SYSERR;
677     }
678   GNUNET_free (opt);
679   return GNUNET_OK;
680 }
681
682
683 /**
684  * Parse an IPv4 access control list.
685  */
686 static int
687 process_acl6 (struct IPv6NetworkSet **ret,
688               struct GNUNET_SERVICE_Context *sctx, const char *option)
689 {
690   char *opt;
691   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
692     return GNUNET_OK;
693   GNUNET_break (GNUNET_OK ==
694                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
695                                                        sctx->serviceName,
696                                                        option, &opt));
697   if (NULL == (*ret = parse_ipv6_specification (opt)))
698     {
699       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
700                   _
701                   ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
702                   opt, sctx->serviceName, option);
703       GNUNET_free (opt);
704       return GNUNET_SYSERR;
705     }
706   GNUNET_free (opt);
707   return GNUNET_OK;
708 }
709
710
711 /**
712  * Get the list of addresses that a server for the given service
713  * should bind to.
714  *
715  * @param serviceName name of the service
716  * @param cfg configuration (which specifies the addresses)
717  * @param addrs set (call by reference) to an array of pointers to the
718  *              addresses the server should bind to and listen on; the
719  *              array will be NULL-terminated (on success)
720  * @param addr_lens set (call by reference) to an array of the lengths
721  *              of the respective 'struct sockaddr' struct in the 'addrs'
722  *              array (on success)
723  * @return number of addresses found on success,
724  *              GNUNET_SYSERR if the configuration
725  *              did not specify reasonable finding information or
726  *              if it specified a hostname that could not be resolved;
727  *              GNUNET_NO if the number of addresses configured is
728  *              zero (in this case, '*addrs' and '*addr_lens' will be
729  *              set to NULL).
730  */
731 int
732 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
733                                      const struct GNUNET_CONFIGURATION_Handle *cfg,
734                                      struct sockaddr ***addrs,
735                                      socklen_t **addr_lens)
736 {
737   int disablev6;
738   struct GNUNET_NETWORK_Handle *desc;
739   unsigned long long port;
740   struct addrinfo hints;
741   struct addrinfo *res;
742   struct addrinfo *pos;
743   struct addrinfo *next;
744   unsigned int i;
745   int resi;
746   int ret;
747   struct sockaddr **saddrs;
748   socklen_t *saddrlens;
749   char *hostname;
750
751   *addrs = NULL;
752   *addr_lens = NULL;
753   if (GNUNET_CONFIGURATION_have_value (cfg,
754                                        serviceName, "DISABLEV6"))
755     {
756       if (GNUNET_SYSERR ==
757           (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
758                                                              serviceName,
759                                                              "DISABLEV6")))
760         return GNUNET_SYSERR;
761     }
762   else
763     disablev6 = GNUNET_NO;
764
765   if (!disablev6)
766     {
767       /* probe IPv6 support */
768       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
769       if (NULL == desc)
770         {
771           if ((errno == ENOBUFS) ||
772               (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
773             {
774               GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
775               return GNUNET_SYSERR;
776             }
777           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
778                       _
779                       ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
780                       serviceName, STRERROR (errno));
781           disablev6 = GNUNET_YES;
782         }
783       else
784         {
785           GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
786         }
787     }
788
789
790   if ((GNUNET_OK !=
791        GNUNET_CONFIGURATION_get_value_number (cfg,
792                                               serviceName,
793                                               "PORT",
794                                               &port)) || (port > 65535))
795     {
796       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
797                   _
798                   ("Require valid port number for service `%s' in configuration!\n"),
799                   serviceName);
800       return GNUNET_SYSERR;
801     }
802   if (GNUNET_CONFIGURATION_have_value (cfg,
803                                        serviceName, "BINDTO"))
804     {
805       GNUNET_break (GNUNET_OK ==
806                     GNUNET_CONFIGURATION_get_value_string (cfg,
807                                                            serviceName,
808                                                            "BINDTO",
809                                                            &hostname));
810     }
811   else
812     hostname = NULL;
813
814   if (hostname != NULL)
815     {
816 #if DEBUG_SERVICE
817       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818                   "Resolving `%s' since that is where `%s' will bind to.\n",
819                   hostname,
820                   serviceName);
821 #endif
822       memset (&hints, 0, sizeof (struct addrinfo));
823       if (disablev6)
824         hints.ai_family = AF_INET;
825       if ((0 != (ret = getaddrinfo (hostname,
826                                     NULL, &hints, &res))) || (res == NULL))
827         {
828           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
829                       _("Failed to resolve `%s': %s\n"),
830                       hostname, gai_strerror (ret));
831           GNUNET_free (hostname);
832           return GNUNET_SYSERR;
833         }
834       next = res;
835       i = 0;
836       while (NULL != (pos = next)) 
837         {
838           next = pos->ai_next;
839           if ( (disablev6) && (pos->ai_family == AF_INET6))
840             continue;
841           i++;
842         }
843       if (0 == i)
844         {
845           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
846                       _("Failed to find %saddress for `%s'.\n"),
847                       disablev6 ? "IPv4 " : "", hostname);
848           freeaddrinfo (res);
849           GNUNET_free (hostname);
850           return GNUNET_SYSERR;
851         }
852       resi = i;
853       saddrs = GNUNET_malloc ((i+1) * sizeof(struct sockaddr*));
854       saddrlens = GNUNET_malloc ((i+1) * sizeof (socklen_t));
855       i = 0;
856       next = res;
857       while (NULL != (pos = next)) 
858         {
859           next = pos->ai_next;
860           if ( (disablev6) && (pos->ai_family == AF_INET6))
861             continue;
862 #if DEBUG_SERVICE
863           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864                       "Service `%s' will bind to `%s'\n",
865                       serviceName,
866                       GNUNET_a2s (pos->ai_addr,
867                                   pos->ai_addrlen));
868 #endif
869           if (pos->ai_family == AF_INET)
870             {
871               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
872               saddrlens[i] = pos->ai_addrlen;
873               saddrs[i] = GNUNET_malloc (saddrlens[i]);
874               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
875               ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
876             }
877           else
878             {
879               GNUNET_assert (pos->ai_family == AF_INET6);
880               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
881               saddrlens[i] = pos->ai_addrlen;
882               saddrs[i] = GNUNET_malloc (saddrlens[i]);
883               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
884               ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
885             }     
886           i++;
887         }
888       GNUNET_free (hostname);
889       freeaddrinfo (res);
890     }
891   else
892     {
893       /* will bind against everything, just set port */
894       if (disablev6)
895         {
896           /* V4-only */
897           resi = 1;
898           saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
899           saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
900           saddrlens[0] = sizeof (struct sockaddr_in);
901           saddrs[0] = GNUNET_malloc (saddrlens[0]);
902 #if HAVE_SOCKADDR_IN_SIN_LEN
903           ((struct sockaddr_in *) saddrs[0])->sin_len = saddrlens[0];
904 #endif
905           ((struct sockaddr_in *) saddrs[0])->sin_family = AF_INET;
906           ((struct sockaddr_in *) saddrs[0])->sin_port = htons (port);
907         }
908       else
909         {
910           /* dual stack */
911           resi = 2;
912           saddrs = GNUNET_malloc (3 * sizeof(struct sockaddr*));
913           saddrlens = GNUNET_malloc (3 * sizeof (socklen_t));
914
915           saddrlens[0] = sizeof (struct sockaddr_in6);
916           saddrs[0] = GNUNET_malloc (saddrlens[0]);
917 #if HAVE_SOCKADDR_IN_SIN_LEN
918           ((struct sockaddr_in6 *) saddrs[0])->sin6_len = saddrlens[0];
919 #endif
920           ((struct sockaddr_in6 *) saddrs[0])->sin6_family = AF_INET6;
921           ((struct sockaddr_in6 *) saddrs[0])->sin6_port = htons (port);
922
923           saddrlens[1] = sizeof (struct sockaddr_in);
924           saddrs[1] = GNUNET_malloc (saddrlens[1]);
925 #if HAVE_SOCKADDR_IN_SIN_LEN
926           ((struct sockaddr_in *) saddrs[1])->sin_len = saddrlens[1];
927 #endif
928           ((struct sockaddr_in *) saddrs[1])->sin_family = AF_INET;
929           ((struct sockaddr_in *) saddrs[1])->sin_port = htons (port);
930         }
931     }
932   *addrs = saddrs;
933   *addr_lens = saddrlens;
934   return resi;
935 }
936
937
938 /**
939  * Setup addr, addrlen, maxbuf, idle_timeout
940  * based on configuration!
941  *
942  * Configuration must specify a "PORT".  It may
943  * specify:
944  * - TIMEOUT (after how many ms does an inactive service timeout);
945  * - MAXBUF (maximum incoming message size supported)
946  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
947  * - ALLOW_SHUTDOWN (allow clients to shutdown this service)
948  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
949  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
950  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
951  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
952  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
953  *
954  * @return GNUNET_OK if configuration succeeded
955  */
956 static int
957 setup_service (struct GNUNET_SERVICE_Context *sctx)
958 {
959   unsigned long long maxbuf;
960   struct GNUNET_TIME_Relative idleout;
961   int tolerant;
962
963   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
964                                        sctx->serviceName, "TIMEOUT"))
965     {
966       if (GNUNET_OK !=
967           GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
968                                                sctx->serviceName,
969                                                "TIMEOUT", &idleout))
970         {
971           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
972                       _("Specified value for `%s' of service `%s' is invalid\n"),
973                       "TIMEOUT",
974                       sctx->serviceName);
975           return GNUNET_SYSERR;
976         }
977       sctx->timeout = idleout;
978     }
979   else
980     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
981   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
982                                        sctx->serviceName, "MAXBUF"))
983     {
984       if (GNUNET_OK !=
985           GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
986                                                  sctx->serviceName,
987                                                  "MAXBUF", &maxbuf))
988         {
989           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
990                       _("Specified value for `%s' of service `%s' is invalid\n"),
991                       "MAXBUF",
992                       sctx->serviceName);
993           return GNUNET_SYSERR;
994         }
995     }
996   else
997     maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
998   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
999                                        sctx->serviceName, "ALLOW_SHUTDOWN"))
1000     {
1001       if (GNUNET_SYSERR ==
1002           (sctx->allow_shutdown =
1003            GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1004                                                  "ALLOW_SHUTDOWN")))
1005         {
1006           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1007                       _("Specified value for `%s' of service `%s' is invalid\n"),
1008                       "ALLOW_SHUTDOWN",
1009                       sctx->serviceName);
1010           return GNUNET_SYSERR;
1011         }
1012     }
1013   else
1014     sctx->allow_shutdown = GNUNET_NO;
1015
1016
1017   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1018                                        sctx->serviceName, "TOLERANT"))
1019     {
1020       if (GNUNET_SYSERR ==
1021           (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1022                                                             sctx->serviceName,
1023                                                             "TOLERANT")))
1024         {
1025           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1026                       _("Specified value for `%s' of service `%s' is invalid\n"),
1027                       "TOLERANT",
1028                       sctx->serviceName);
1029           return GNUNET_SYSERR;
1030         }
1031     }
1032   else
1033     tolerant = GNUNET_NO;
1034
1035   if (GNUNET_SYSERR ==
1036       GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1037                                            sctx->cfg,
1038                                            &sctx->addrs,
1039                                            &sctx->addrlens))
1040     return GNUNET_SYSERR;
1041   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1042   sctx->maxbuf = (size_t) maxbuf;
1043   if (sctx->maxbuf != maxbuf)
1044     {
1045       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1046                   _
1047                   ("Value in configuration for `%s' and service `%s' too large!\n"),
1048                   "MAXBUF", sctx->serviceName);
1049       return GNUNET_SYSERR;
1050     }
1051
1052   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1053   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1054   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1055   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1056
1057   return GNUNET_OK;
1058 }
1059
1060
1061 /**
1062  * Get the name of the user that'll be used
1063  * to provide the service.
1064  */
1065 static char *
1066 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1067 {
1068
1069   char *un;
1070
1071   if (GNUNET_OK !=
1072       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1073                                                sctx->serviceName,
1074                                                "USERNAME", &un))
1075     return NULL;
1076   return un;
1077 }
1078
1079 /**
1080  * Write PID file.
1081  */
1082 static int
1083 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1084 {
1085   FILE *pidfd;
1086   char *pif;
1087   char *user;
1088   char *rdir;
1089   int len;
1090
1091   if (NULL == (pif = get_pid_file_name (sctx)))
1092     return GNUNET_OK;           /* no file desired */
1093   user = get_user_name (sctx);
1094   rdir = GNUNET_strdup (pif);
1095   len = strlen (rdir);
1096   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1097     len--;
1098   rdir[len] = '\0';
1099   if (0 != ACCESS (rdir, F_OK))
1100     {
1101       /* we get to create a directory -- and claim it
1102          as ours! */
1103       GNUNET_DISK_directory_create (rdir);
1104       if ((user != NULL) && (0 < strlen (user)))
1105         GNUNET_DISK_file_change_owner (rdir, user);
1106     }
1107   if (0 != ACCESS (rdir, W_OK | X_OK))
1108     {
1109       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1110       GNUNET_free (rdir);
1111       GNUNET_free_non_null (user);
1112       GNUNET_free (pif);
1113       return GNUNET_SYSERR;
1114     }
1115   GNUNET_free (rdir);
1116   pidfd = FOPEN (pif, "w");
1117   if (pidfd == NULL)
1118     {
1119       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1120       GNUNET_free (pif);
1121       GNUNET_free_non_null (user);
1122       return GNUNET_SYSERR;
1123     }
1124   if (0 > FPRINTF (pidfd, "%u", pid))
1125     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1126   GNUNET_break (0 == fclose (pidfd));
1127   if ((user != NULL) && (0 < strlen (user)))
1128     GNUNET_DISK_file_change_owner (pif, user);
1129   GNUNET_free_non_null (user);
1130   GNUNET_free (pif);
1131   return GNUNET_OK;
1132 }
1133
1134
1135 /**
1136  * Task run during shutdown.
1137  *
1138  * @param cls unused
1139  * @param tc unused
1140  */
1141 static void
1142 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1143 {
1144   struct GNUNET_SERVER_Handle *server = cls;
1145
1146   GNUNET_SERVER_destroy (server);
1147 }
1148
1149
1150 /**
1151  * Initial task for the service.
1152  */
1153 static void
1154 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1155 {
1156   struct GNUNET_SERVICE_Context *sctx = cls;
1157   unsigned int i;
1158
1159   sctx->sched = tc->sched;
1160   sctx->server = GNUNET_SERVER_create (tc->sched,
1161                                        &check_access,
1162                                        sctx,
1163                                        sctx->addrs,
1164                                        sctx->addrlens,
1165                                        sctx->maxbuf,
1166                                        sctx->timeout, sctx->require_found);
1167   if (sctx->server == NULL)
1168     {
1169       i = 0;
1170       while (sctx->addrs[i] != NULL)
1171         {
1172           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1173                       _("Failed to start `%s' at `%s'\n"),
1174                       sctx->serviceName, 
1175                       GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1176           i++;
1177         }
1178       sctx->ret = GNUNET_SYSERR;
1179       return;
1180     }
1181   if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1182     {
1183       /* install a task that will kill the server
1184          process if the scheduler ever gets a shutdown signal */
1185       GNUNET_SCHEDULER_add_delayed (tc->sched,
1186                                     GNUNET_TIME_UNIT_FOREVER_REL,
1187                                     &shutdown_task, sctx->server);
1188     }
1189   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1190   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1191   i = 0;
1192   while ((sctx->my_handlers[i].callback != NULL))
1193     sctx->my_handlers[i++].callback_cls = sctx;
1194   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1195   if (sctx->ready_confirm_fd != -1)
1196     {
1197       GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1198       GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1199       sctx->ready_confirm_fd = -1;
1200       write_pid_file (sctx, getpid ());
1201     }
1202   i = 0;
1203   while (sctx->addrs[i] != NULL)
1204     {
1205       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1206                   _("Service `%s' runs at %s\n"),
1207                   sctx->serviceName, 
1208                   GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1209       i++;
1210     }
1211   sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1212 }
1213
1214
1215 /**
1216  * Detach from terminal.
1217  */
1218 static int
1219 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1220 {
1221 #ifndef MINGW
1222   pid_t pid;
1223   int nullfd;
1224   int filedes[2];
1225
1226   if (0 != PIPE (filedes))
1227     {
1228       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1229       return GNUNET_SYSERR;
1230     }
1231   pid = fork ();
1232   if (pid < 0)
1233     {
1234       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1235       return GNUNET_SYSERR;
1236     }
1237   if (pid != 0)
1238     {
1239       /* Parent */
1240       char c;
1241
1242       GNUNET_break (0 == CLOSE (filedes[1]));
1243       c = 'X';
1244       if (1 != READ (filedes[0], &c, sizeof (char)))
1245         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1246       fflush (stdout);
1247       switch (c)
1248         {
1249         case '.':
1250           exit (0);
1251         case 'I':
1252           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1253                       _("Service process failed to initialize\n"));
1254           break;
1255         case 'S':
1256           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1257                       _
1258                       ("Service process could not initialize server function\n"));
1259           break;
1260         case 'X':
1261           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1262                       _("Service process failed to report status\n"));
1263           break;
1264         }
1265       exit (1);                 /* child reported error */
1266     }
1267   GNUNET_break (0 == CLOSE (0));
1268   GNUNET_break (0 == CLOSE (1));
1269   GNUNET_break (0 == CLOSE (filedes[0]));
1270   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1271   if (nullfd < 0)
1272     return GNUNET_SYSERR;
1273   /* set stdin/stdout to /dev/null */
1274   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1275     {
1276       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1277       return GNUNET_SYSERR;
1278     }
1279   /* Detach from controlling terminal */
1280   pid = setsid ();
1281   if (pid == -1)
1282     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1283   sctx->ready_confirm_fd = filedes[1];
1284 #else
1285   /* FIXME: we probably need to do something else
1286      elsewhere in order to fork the process itself... */
1287   FreeConsole ();
1288 #endif
1289   return GNUNET_OK;
1290 }
1291
1292
1293 /**
1294  * Set user ID.
1295  */
1296 static int
1297 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1298 {
1299   char *user;
1300
1301   if (NULL == (user = get_user_name (sctx)))
1302     return GNUNET_OK;           /* keep */
1303 #ifndef MINGW
1304   struct passwd *pws;
1305
1306   errno = 0;
1307   pws = getpwnam (user);
1308   if (pws == NULL)
1309     {
1310       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311                   _("Cannot obtain information about user `%s': %s\n"),
1312                   user, errno == 0 ? _("No such user") : STRERROR (errno));
1313       GNUNET_free (user);
1314       return GNUNET_SYSERR;
1315     }
1316   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1317 #if HAVE_INITGROUPS
1318       (0 != initgroups (user, pws->pw_gid)) ||
1319 #endif
1320       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1321     {
1322       if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1323           (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1324         {
1325           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1326                       _("Cannot change user/group to `%s': %s\n"), user,
1327                       STRERROR (errno));
1328           GNUNET_free (user);
1329           return GNUNET_SYSERR;
1330         }
1331     }
1332 #endif
1333   GNUNET_free (user);
1334   return GNUNET_OK;
1335 }
1336
1337
1338 /**
1339  * Delete the PID file that was created by our parent.
1340  */
1341 static void
1342 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1343 {
1344   char *pif = get_pid_file_name (sctx);
1345   if (pif == NULL)
1346     return;                     /* no PID file */
1347   if (0 != UNLINK (pif))
1348     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1349   GNUNET_free (pif);
1350 }
1351
1352
1353 /**
1354  * Run a standard GNUnet service startup sequence (initialize loggers
1355  * and configuration, parse options).
1356  *
1357  * @param argc number of command line arguments
1358  * @param argv command line arguments
1359  * @param serviceName our service name
1360  * @param opt service options
1361  * @param task main task of the service
1362  * @param task_cls closure for task
1363  * @return GNUNET_SYSERR on error, GNUNET_OK
1364  *         if we shutdown nicely
1365  */
1366 int
1367 GNUNET_SERVICE_run (int argc,
1368                     char *const *argv,
1369                     const char *serviceName,
1370                     enum GNUNET_SERVICE_Options opt,
1371                     GNUNET_SERVICE_Main task, void *task_cls)
1372 {
1373 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1374
1375   int err;
1376   char *cfg_fn;
1377   char *loglev;
1378   char *logfile;
1379   int do_daemonize;
1380   unsigned int i;
1381   struct GNUNET_SERVICE_Context sctx;
1382   struct GNUNET_CONFIGURATION_Handle *cfg;
1383   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1384     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1385     {'d', "daemonize", NULL,
1386      gettext_noop ("do daemonize (detach from terminal)"), 0,
1387      GNUNET_GETOPT_set_one, &do_daemonize},
1388     GNUNET_GETOPT_OPTION_HELP (serviceName),
1389     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1390     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1391     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1392     GNUNET_GETOPT_OPTION_END
1393   };
1394   err = 0;
1395   do_daemonize = 0;
1396   logfile = NULL;
1397   loglev = GNUNET_strdup ("WARNING");
1398   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1399   memset (&sctx, 0, sizeof (sctx));
1400   sctx.options = opt;
1401   sctx.ready_confirm_fd = -1;
1402   sctx.ret = GNUNET_OK;
1403   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1404   sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1405   sctx.task = task;
1406   sctx.serviceName = serviceName;
1407   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1408   /* setup subsystems */
1409   if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1410       argv))    
1411     goto shutdown;
1412   if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1413     HANDLE_ERROR;
1414   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1415     goto shutdown;
1416   if (GNUNET_OK != setup_service (&sctx))
1417     goto shutdown;
1418   if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))    
1419     HANDLE_ERROR;
1420   if (GNUNET_OK != set_user_id (&sctx))
1421     goto shutdown;
1422 #if DEBUG_SERVICE
1423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424               "Service `%s' runs with configuration from `%s'\n",
1425               serviceName, cfg_fn);
1426 #endif
1427   /* actually run service */
1428   GNUNET_SCHEDULER_run (&service_task, &sctx);
1429
1430   /* shutdown */
1431   if ((do_daemonize == 1) && (sctx.server != NULL))
1432     pid_file_delete (&sctx);
1433   GNUNET_free_non_null (sctx.my_handlers);
1434
1435 shutdown:
1436   if (sctx.ready_confirm_fd != -1)
1437     {
1438       if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1439         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1440       GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1441     }
1442
1443   GNUNET_CONFIGURATION_destroy (cfg);
1444   i = 0;
1445   if (sctx.addrs != NULL)
1446     while (sctx.addrs[i] != NULL)    
1447       GNUNET_free (sctx.addrs[i++]);    
1448   GNUNET_free_non_null (sctx.addrs);
1449   GNUNET_free_non_null (sctx.addrlens);
1450   GNUNET_free_non_null (logfile);
1451   GNUNET_free (loglev);
1452   GNUNET_free (cfg_fn);
1453   GNUNET_free_non_null (sctx.v4_denied);
1454   GNUNET_free_non_null (sctx.v6_denied);
1455   GNUNET_free_non_null (sctx.v4_allowed);
1456   GNUNET_free_non_null (sctx.v6_allowed);
1457
1458   return err ? GNUNET_SYSERR : sctx.ret;
1459 }
1460
1461
1462 /**
1463  * Run a service startup sequence within an existing
1464  * initialized system.
1465  *
1466  * @param serviceName our service name
1467  * @param sched scheduler to use
1468  * @param cfg configuration to use
1469  * @return NULL on error, service handle
1470  */
1471 struct GNUNET_SERVICE_Context *
1472 GNUNET_SERVICE_start (const char *serviceName,
1473                       struct GNUNET_SCHEDULER_Handle *sched,
1474                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1475 {
1476   int i;
1477   struct GNUNET_SERVICE_Context *sctx;
1478
1479   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1480   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1481   sctx->ret = GNUNET_OK;
1482   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1483   sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1484   sctx->serviceName = serviceName;
1485   sctx->cfg = cfg;
1486   sctx->sched = sched;
1487
1488   /* setup subsystems */
1489   if ((GNUNET_OK != setup_service (sctx)) ||
1490       (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1491                                                      &check_access,
1492                                                      sctx,
1493                                                      sctx->addrs,
1494                                                      sctx->addrlens,
1495                                                      sctx->maxbuf,
1496                                                      sctx->timeout,
1497                                                      sctx->require_found))))
1498     {
1499       GNUNET_SERVICE_stop (sctx);
1500       return NULL;
1501     }
1502   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1503   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1504   i = 0;
1505   while ((sctx->my_handlers[i].callback != NULL))
1506     sctx->my_handlers[i++].callback_cls = sctx;
1507   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1508   return sctx;
1509 }
1510
1511 /**
1512  * Obtain the server used by a service.  Note that the server must NOT
1513  * be destroyed by the caller.
1514  *
1515  * @param ctx the service context returned from the start function
1516  * @return handle to the server for this service, NULL if there is none
1517  */
1518 struct GNUNET_SERVER_Handle *
1519 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1520 {
1521   return ctx->server;
1522 }
1523
1524
1525 /**
1526  * Stop a service that was started with "GNUNET_SERVICE_start".
1527  *
1528  * @param sctx the service context returned from the start function
1529  */
1530 void
1531 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1532 {
1533   unsigned int i;
1534   if (NULL != sctx->server)
1535     GNUNET_SERVER_destroy (sctx->server);
1536   GNUNET_free_non_null (sctx->my_handlers);
1537   i = 0;
1538   while (sctx->addrs[i] != NULL)    
1539     GNUNET_free (sctx->addrs[i++]);    
1540   GNUNET_free_non_null (sctx->addrs);
1541   GNUNET_free_non_null (sctx->addrlens);
1542   GNUNET_free_non_null (sctx->v4_denied);
1543   GNUNET_free_non_null (sctx->v6_denied);
1544   GNUNET_free_non_null (sctx->v4_allowed);
1545   GNUNET_free_non_null (sctx->v6_allowed);
1546   GNUNET_free (sctx);
1547 }
1548
1549
1550 /* end of service.c */