79b21e065fb0f9883974010ba6367ef83c0c7f1b
[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    * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
434    * listen sockets.
435    */
436   struct sockaddr **addrs;
437
438   /**
439    * Name of our service.
440    */
441   const char *serviceName;
442
443   /**
444    * Main service-specific task to run.
445    */
446   GNUNET_SERVICE_Main task;
447
448   /**
449    * Closure for task.
450    */
451   void *task_cls;
452
453   /**
454    * IPv4 addresses that are not allowed to connect.
455    */
456   struct IPv4NetworkSet *v4_denied;
457
458   /**
459    * IPv6 addresses that are not allowed to connect.
460    */
461   struct IPv6NetworkSet *v6_denied;
462
463   /**
464    * IPv4 addresses that are allowed to connect (if not
465    * set, all are allowed).
466    */
467   struct IPv4NetworkSet *v4_allowed;
468
469   /**
470    * IPv6 addresses that are allowed to connect (if not
471    * set, all are allowed).
472    */
473   struct IPv6NetworkSet *v6_allowed;
474
475   /**
476    * My (default) message handlers.  Adjusted copy
477    * of "defhandlers".
478    */
479   struct GNUNET_SERVER_MessageHandler *my_handlers;
480
481   /**
482    * Array of the lengths of the entries in addrs.
483    */
484   socklen_t * addrlens;
485
486   /**
487    * NULL-terminated array of listen sockets we should take over.
488    */
489   struct GNUNET_NETWORK_Handle **lsocks;
490
491   /**
492    * Idle timeout for server.
493    */
494   struct GNUNET_TIME_Relative timeout;
495
496   /**
497    * Overall success/failure of the service start.
498    */
499   int ret;
500
501   /**
502    * If we are daemonizing, this FD is set to the
503    * pipe to the parent.  Send '.' if we started
504    * ok, '!' if not.  -1 if we are not daemonizing.
505    */
506   int ready_confirm_fd;
507
508   /**
509    * Do we close connections if we receive messages
510    * for which we have no handler?
511    */
512   int require_found;
513
514   /**
515    * Our options.
516    */
517   enum GNUNET_SERVICE_Options options;
518
519 };
520
521
522 /* ****************** message handlers ****************** */
523
524 static size_t
525 write_test (void *cls, size_t size, void *buf)
526 {
527   struct GNUNET_SERVER_Client *client = cls;
528   struct GNUNET_MessageHeader *msg;
529
530   if (size < sizeof (struct GNUNET_MessageHeader))
531     {
532       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
533       return 0;                 /* client disconnected */
534     }
535   msg = (struct GNUNET_MessageHeader *) buf;
536   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
537   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
538   GNUNET_SERVER_receive_done (client, GNUNET_OK);
539   return sizeof (struct GNUNET_MessageHeader);
540 }
541
542 /**
543  * Handler for TEST message.
544  *
545  * @param cls closure (refers to service)
546  * @param client identification of the client
547  * @param message the actual message
548  */
549 static void
550 handle_test (void *cls,
551              struct GNUNET_SERVER_Client *client,
552              const struct GNUNET_MessageHeader *message)
553 {
554   /* simply bounce message back to acknowledge */
555   if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
556                                                    sizeof (struct
557                                                            GNUNET_MessageHeader),
558                                                    GNUNET_TIME_UNIT_FOREVER_REL,
559                                                    &write_test, client))
560     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
561 }
562
563
564 /**
565  * Default handlers for all services.  Will be copied and the
566  * "callback_cls" fields will be replaced with the specific service
567  * struct.
568  */
569 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
570   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
571    sizeof (struct GNUNET_MessageHeader)},
572   {NULL, NULL, 0, 0}
573 };
574
575
576
577 /* ****************** service core routines ************** */
578
579
580 /**
581  * Check if access to the service is allowed from the given address.
582  */
583 static int
584 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
585 {
586   struct GNUNET_SERVICE_Context *sctx = cls;
587   const struct sockaddr_in *i4;
588   const struct sockaddr_in6 *i6;
589   int ret;
590
591   switch (addr->sa_family)
592     {
593     case AF_INET:
594       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
595       i4 = (const struct sockaddr_in *) addr;
596       ret = ((sctx->v4_allowed == NULL) ||
597              (check_ipv4_listed (sctx->v4_allowed,
598                                  &i4->sin_addr)))
599         && ((sctx->v4_denied == NULL) ||
600             (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
601       break;
602     case AF_INET6:
603       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
604       i6 = (const struct sockaddr_in6 *) addr;
605       ret = ((sctx->v6_allowed == NULL) ||
606              (check_ipv6_listed (sctx->v6_allowed,
607                                  &i6->sin6_addr)))
608         && ((sctx->v6_denied == NULL) ||
609             (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
610       break;
611     case AF_UNIX:
612       /* FIXME: support checking UID/GID in the future... */
613       ret = GNUNET_OK; /* always OK for now */
614       break;
615     default:
616       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
617                   _("Unknown address family %d\n"), addr->sa_family);
618       return GNUNET_SYSERR;
619     }
620   if (ret != GNUNET_OK)
621     {
622       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
623                   _("Access from `%s' denied to service `%s'\n"),
624                   GNUNET_a2s (addr, addrlen), sctx->serviceName);
625     }
626   return ret;
627 }
628
629
630 /**
631  * Get the name of the file where we will
632  * write the PID of the service.
633  */
634 static char *
635 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
636 {
637
638   char *pif;
639
640   if (GNUNET_OK !=
641       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
642                                                sctx->serviceName,
643                                                "PIDFILE", &pif))
644     return NULL;
645   return pif;
646 }
647
648
649 /**
650  * Parse an IPv4 access control list.
651  */
652 static int
653 process_acl4 (struct IPv4NetworkSet **ret,
654               struct GNUNET_SERVICE_Context *sctx, const char *option)
655 {
656   char *opt;
657
658   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
659     return GNUNET_OK;
660   GNUNET_break (GNUNET_OK ==
661                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
662                                                        sctx->serviceName,
663                                                        option, &opt));
664   if (NULL == (*ret = parse_ipv4_specification (opt)))
665     {
666       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
667                   _
668                   ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
669                   opt, sctx->serviceName, option);
670       GNUNET_free (opt);
671       return GNUNET_SYSERR;
672     }
673   GNUNET_free (opt);
674   return GNUNET_OK;
675 }
676
677
678 /**
679  * Parse an IPv4 access control list.
680  */
681 static int
682 process_acl6 (struct IPv6NetworkSet **ret,
683               struct GNUNET_SERVICE_Context *sctx, const char *option)
684 {
685   char *opt;
686   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
687     return GNUNET_OK;
688   GNUNET_break (GNUNET_OK ==
689                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
690                                                        sctx->serviceName,
691                                                        option, &opt));
692   if (NULL == (*ret = parse_ipv6_specification (opt)))
693     {
694       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
695                   _
696                   ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
697                   opt, sctx->serviceName, option);
698       GNUNET_free (opt);
699       return GNUNET_SYSERR;
700     }
701   GNUNET_free (opt);
702   return GNUNET_OK;
703 }
704
705 /**
706  * Add the given UNIX domain path as an address to the
707  * list (as the first entry).
708  *
709  * @param saddrs array to update
710  * @param saddrlens where to store the address length
711  * @param unixpath path to add
712  */
713 static void
714 add_unixpath (struct sockaddr **saddrs,
715               socklen_t *saddrlens,
716               const char *unixpath)
717 {
718 #ifdef AF_UNIX  
719   struct sockaddr_un *un;
720   size_t slen;
721
722   un = GNUNET_malloc (sizeof (struct sockaddr_un));
723   un->sun_family = AF_UNIX;
724   slen = strlen (unixpath) + 1;
725   if (slen >= sizeof (un->sun_path))
726     slen = sizeof (un->sun_path) - 1;
727   memcpy (un->sun_path,
728           unixpath,
729           slen);
730   un->sun_path[slen] = '\0';
731 #if LINUX
732   un->sun_path[0] = '\0';
733   slen = sizeof (struct sockaddr_un);
734 #else
735   slen += sizeof (sa_family_t);
736 #endif
737   *saddrs = (struct sockaddr*) un;
738   *saddrlens = slen;
739 #else
740   /* this function should never be called 
741      unless AF_UNIX is defined! */
742   GNUNET_assert (0);
743 #endif
744 }
745
746
747 /**
748  * Get the list of addresses that a server for the given service
749  * should bind to.
750  *
751  * @param serviceName name of the service
752  * @param cfg configuration (which specifies the addresses)
753  * @param addrs set (call by reference) to an array of pointers to the
754  *              addresses the server should bind to and listen on; the
755  *              array will be NULL-terminated (on success)
756  * @param addr_lens set (call by reference) to an array of the lengths
757  *              of the respective 'struct sockaddr' struct in the 'addrs'
758  *              array (on success)
759  * @return number of addresses found on success,
760  *              GNUNET_SYSERR if the configuration
761  *              did not specify reasonable finding information or
762  *              if it specified a hostname that could not be resolved;
763  *              GNUNET_NO if the number of addresses configured is
764  *              zero (in this case, '*addrs' and '*addr_lens' will be
765  *              set to NULL).
766  */
767 int
768 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
769                                      const struct GNUNET_CONFIGURATION_Handle *cfg,
770                                      struct sockaddr ***addrs,
771                                      socklen_t **addr_lens)
772 {
773   int disablev6;
774   struct GNUNET_NETWORK_Handle *desc;
775   unsigned long long port;
776   char *unixpath;
777   struct addrinfo hints;
778   struct addrinfo *res;
779   struct addrinfo *pos;
780   struct addrinfo *next;
781   unsigned int i;
782   int resi;
783   int ret;
784   struct sockaddr **saddrs;
785   socklen_t *saddrlens;
786   char *hostname;
787
788   *addrs = NULL;
789   *addr_lens = NULL;
790   desc = NULL;
791   if (GNUNET_CONFIGURATION_have_value (cfg,
792                                        serviceName, "DISABLEV6"))
793     {
794       if (GNUNET_SYSERR ==
795           (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
796                                                              serviceName,
797                                                              "DISABLEV6")))
798         return GNUNET_SYSERR;
799     }
800   else
801     disablev6 = GNUNET_NO;
802
803   if (!disablev6)
804     {
805       /* probe IPv6 support */
806       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
807       if (NULL == desc)
808         {
809           if ((errno == ENOBUFS) ||
810               (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
811             {
812               GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
813               return GNUNET_SYSERR;
814             }
815           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
816                       _
817                       ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
818                       serviceName, STRERROR (errno));
819           disablev6 = GNUNET_YES;
820         }
821       else
822         {
823           GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
824           desc = NULL;
825         }
826     }
827
828   port = 0;
829   if (GNUNET_CONFIGURATION_have_value (cfg,
830                                        serviceName, "PORT"))
831     {
832       GNUNET_break (GNUNET_OK ==
833                     GNUNET_CONFIGURATION_get_value_number (cfg,
834                                                            serviceName,
835                                                            "PORT",
836                                                            &port));
837       if (port > 65535)
838         {
839           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
840                       _
841                       ("Require valid port number for service `%s' in configuration!\n"),
842                       serviceName);
843           return GNUNET_SYSERR;
844         }
845     }
846
847   if (GNUNET_CONFIGURATION_have_value (cfg,
848                                        serviceName, "BINDTO"))
849     {
850       GNUNET_break (GNUNET_OK ==
851                     GNUNET_CONFIGURATION_get_value_string (cfg,
852                                                            serviceName,
853                                                            "BINDTO",
854                                                            &hostname));
855     }
856   else
857     hostname = NULL;
858
859 #ifdef AF_UNIX
860   if (GNUNET_CONFIGURATION_have_value (cfg,
861                                        serviceName, "UNIXPATH"))
862     {
863       GNUNET_break (GNUNET_OK ==
864                     GNUNET_CONFIGURATION_get_value_string (cfg,
865                                                            serviceName,
866                                                            "UNIXPATH",
867                                                            &unixpath));
868
869       /* probe UNIX support */
870       struct sockaddr_un s_un;
871       if (strlen(unixpath) >= sizeof(s_un.sun_path))
872       {
873           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
874                   _("UNIXPATH `%s' too long, maximum length is %llu\n"),unixpath, sizeof(s_un.sun_path));
875       }
876       /* FIXME: Perhaps add an assertion or a break??? */
877
878       desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
879       if (NULL == desc)
880         {
881           if ((errno == ENOBUFS) ||
882               (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
883             {
884               GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
885               GNUNET_free_non_null (hostname);
886               GNUNET_free (unixpath);
887               return GNUNET_SYSERR;
888             }
889           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
890                       _
891                       ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
892                       serviceName, STRERROR (errno));
893           GNUNET_free (unixpath);
894           unixpath = NULL;
895         }
896       else
897         {
898           GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
899           desc = NULL;
900         }
901     }
902   else
903     unixpath = NULL;
904 #else
905   unixpath = NULL;
906 #endif
907
908   if ( (port == 0) &&
909        (unixpath == NULL) )
910     {
911       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
912                   _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
913                   serviceName);
914       GNUNET_free_non_null(hostname);
915       return GNUNET_SYSERR;
916     }
917   if (port == 0)
918     {
919       saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
920       saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
921       add_unixpath (saddrs, saddrlens, unixpath);
922       GNUNET_free_non_null (unixpath);
923       GNUNET_free_non_null(hostname);
924       *addrs = saddrs;
925       *addr_lens = saddrlens;
926       return 1;
927     }
928        
929   if (hostname != NULL)
930     {
931 #if DEBUG_SERVICE
932       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933                   "Resolving `%s' since that is where `%s' will bind to.\n",
934                   hostname,
935                   serviceName);
936 #endif
937       memset (&hints, 0, sizeof (struct addrinfo));
938       if (disablev6)
939         hints.ai_family = AF_INET;
940       if ((0 != (ret = getaddrinfo (hostname,
941                                     NULL, &hints, &res))) || (res == NULL))
942         {
943           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
944                       _("Failed to resolve `%s': %s\n"),
945                       hostname, gai_strerror (ret));
946           GNUNET_free (hostname);
947           GNUNET_free (unixpath);
948           return GNUNET_SYSERR;
949         }
950       next = res;
951       i = 0;
952       while (NULL != (pos = next)) 
953         {
954           next = pos->ai_next;
955           if ( (disablev6) && (pos->ai_family == AF_INET6))
956             continue;
957           i++;
958         }
959       if (0 == i)
960         {
961           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
962                       _("Failed to find %saddress for `%s'.\n"),
963                       disablev6 ? "IPv4 " : "", hostname);
964           freeaddrinfo (res);
965           GNUNET_free (hostname);
966           GNUNET_free (unixpath);
967           return GNUNET_SYSERR;
968         }
969       resi = i;
970       if (NULL != unixpath)
971         resi++;
972       saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
973       saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
974       i = 0;
975       if (NULL != unixpath)
976         {
977           add_unixpath (saddrs, saddrlens, unixpath);
978           i++;
979         }
980       next = res;
981       while (NULL != (pos = next)) 
982         {
983           next = pos->ai_next;
984           if ( (disablev6) && (pos->ai_family == AF_INET6))
985             continue;
986 #if DEBUG_SERVICE
987           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988                       "Service `%s' will bind to `%s'\n",
989                       serviceName,
990                       GNUNET_a2s (pos->ai_addr,
991                                   pos->ai_addrlen));
992 #endif
993           if (pos->ai_family == AF_INET)
994             {
995               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
996               saddrlens[i] = pos->ai_addrlen;
997               saddrs[i] = GNUNET_malloc (saddrlens[i]);
998               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
999               ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1000             }
1001           else
1002             {
1003               GNUNET_assert (pos->ai_family == AF_INET6);
1004               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1005               saddrlens[i] = pos->ai_addrlen;
1006               saddrs[i] = GNUNET_malloc (saddrlens[i]);
1007               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1008               ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1009             }     
1010           i++;
1011         }
1012       GNUNET_free (hostname);
1013       freeaddrinfo (res);
1014     }
1015   else
1016     {
1017       /* will bind against everything, just set port */
1018       if (disablev6)
1019         {
1020           /* V4-only */
1021           resi = 1;
1022           if (NULL != unixpath)
1023             resi++;
1024           i = 0;
1025           saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1026           saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1027           if (NULL != unixpath)
1028             {
1029               add_unixpath (saddrs, saddrlens, unixpath);
1030               i++;
1031             }
1032           saddrlens[i] = sizeof (struct sockaddr_in);
1033           saddrs[i] = GNUNET_malloc (saddrlens[i]);
1034 #if HAVE_SOCKADDR_IN_SIN_LEN
1035           ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1036 #endif
1037           ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1038           ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1039         }
1040       else
1041         {
1042           /* dual stack */
1043           resi = 2;
1044           if (NULL != unixpath)
1045             resi++;
1046           saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1047           saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1048           i = 0;
1049           if (NULL != unixpath)
1050             {
1051               add_unixpath (saddrs, saddrlens, unixpath);
1052               i++;
1053             }
1054           saddrlens[i] = sizeof (struct sockaddr_in6);
1055           saddrs[i] = GNUNET_malloc (saddrlens[i]);
1056 #if HAVE_SOCKADDR_IN_SIN_LEN
1057           ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1058 #endif
1059           ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1060           ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1061           i++;
1062           saddrlens[i] = sizeof (struct sockaddr_in);
1063           saddrs[i] = GNUNET_malloc (saddrlens[i]);
1064 #if HAVE_SOCKADDR_IN_SIN_LEN
1065           ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1066 #endif
1067           ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1068           ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1069         }
1070     }
1071   GNUNET_free_non_null (unixpath);
1072   *addrs = saddrs;
1073   *addr_lens = saddrlens;
1074   return resi;
1075 }
1076
1077
1078 /**
1079  * Setup addr, addrlen, idle_timeout
1080  * based on configuration!
1081  *
1082  * Configuration may specify:
1083  * - PORT (where to bind to for TCP)
1084  * - UNIXPATH (where to bind to for UNIX domain sockets)
1085  * - TIMEOUT (after how many ms does an inactive service timeout);
1086  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1087  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1088  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
1089  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1090  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
1091  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1092  *
1093  * @return GNUNET_OK if configuration succeeded
1094  */
1095 static int
1096 setup_service (struct GNUNET_SERVICE_Context *sctx)
1097 {
1098   struct GNUNET_TIME_Relative idleout;
1099   int tolerant;
1100 #ifndef MINGW
1101   const char *lpid;
1102   unsigned int pid;
1103   const char *nfds;
1104   unsigned int cnt;
1105   int flags;
1106 #endif
1107
1108   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1109                                        sctx->serviceName, "TIMEOUT"))
1110     {
1111       if (GNUNET_OK !=
1112           GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1113                                                sctx->serviceName,
1114                                                "TIMEOUT", &idleout))
1115         {
1116           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1117                       _("Specified value for `%s' of service `%s' is invalid\n"),
1118                       "TIMEOUT",
1119                       sctx->serviceName);
1120           return GNUNET_SYSERR;
1121         }
1122       sctx->timeout = idleout;
1123     }
1124   else
1125     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1126
1127   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1128                                        sctx->serviceName, "TOLERANT"))
1129     {
1130       if (GNUNET_SYSERR ==
1131           (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1132                                                             sctx->serviceName,
1133                                                             "TOLERANT")))
1134         {
1135           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1136                       _("Specified value for `%s' of service `%s' is invalid\n"),
1137                       "TOLERANT",
1138                       sctx->serviceName);
1139           return GNUNET_SYSERR;
1140         }
1141     }
1142   else
1143     tolerant = GNUNET_NO;
1144
1145 #ifndef MINGW
1146   errno = 0;
1147   if ( (NULL != (lpid = getenv ("LISTEN_PID"))) &&
1148        (1 == sscanf (lpid, "%u", &pid)) &&
1149        (getpid () == (pid_t) pid) &&
1150        (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1151        (1 == sscanf (nfds, "%u", &cnt)) &&
1152        (cnt > 0) &&
1153        (cnt < FD_SETSIZE) &&
1154        (cnt + 4 < FD_SETSIZE) )
1155     {
1156       sctx->lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle*) * (cnt+1));
1157       while (0 < cnt--)
1158         {
1159           flags = fcntl (3 + cnt, F_GETFD);      
1160           if ( (flags < 0) ||
1161                (0 != (flags & FD_CLOEXEC)) ||
1162                (NULL == (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))) )
1163             {
1164               GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1165                           _("Could not access pre-bound socket %u, will try to bind myself\n"),
1166                           (unsigned int) 3 +cnt);
1167               cnt++;
1168               while (sctx->lsocks[cnt] != NULL)
1169                 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1170               GNUNET_free (sctx->lsocks);
1171               sctx->lsocks = NULL;
1172               break;
1173             }
1174         }
1175       unsetenv ("LISTEN_PID");
1176       unsetenv ("LISTEN_FDS");
1177     }
1178 #endif
1179
1180   if ( (sctx->lsocks == NULL) &&
1181        (GNUNET_SYSERR ==
1182         GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1183                                              sctx->cfg,
1184                                              &sctx->addrs,
1185                                              &sctx->addrlens)) )
1186     return GNUNET_SYSERR;
1187   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1188
1189   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1190   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1191   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1192   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1193
1194   return GNUNET_OK;
1195 }
1196
1197
1198 /**
1199  * Get the name of the user that'll be used
1200  * to provide the service.
1201  */
1202 static char *
1203 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1204 {
1205
1206   char *un;
1207
1208   if (GNUNET_OK !=
1209       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1210                                                sctx->serviceName,
1211                                                "USERNAME", &un))
1212     return NULL;
1213   return un;
1214 }
1215
1216 /**
1217  * Write PID file.
1218  */
1219 static int
1220 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1221 {
1222   FILE *pidfd;
1223   char *pif;
1224   char *user;
1225   char *rdir;
1226   int len;
1227
1228   if (NULL == (pif = get_pid_file_name (sctx)))
1229     return GNUNET_OK;           /* no file desired */
1230   user = get_user_name (sctx);
1231   rdir = GNUNET_strdup (pif);
1232   len = strlen (rdir);
1233   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1234     len--;
1235   rdir[len] = '\0';
1236   if (0 != ACCESS (rdir, F_OK))
1237     {
1238       /* we get to create a directory -- and claim it
1239          as ours! */
1240       GNUNET_DISK_directory_create (rdir);
1241       if ((user != NULL) && (0 < strlen (user)))
1242         GNUNET_DISK_file_change_owner (rdir, user);
1243     }
1244   if (0 != ACCESS (rdir, W_OK | X_OK))
1245     {
1246       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1247       GNUNET_free (rdir);
1248       GNUNET_free_non_null (user);
1249       GNUNET_free (pif);
1250       return GNUNET_SYSERR;
1251     }
1252   GNUNET_free (rdir);
1253   pidfd = FOPEN (pif, "w");
1254   if (pidfd == NULL)
1255     {
1256       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1257       GNUNET_free (pif);
1258       GNUNET_free_non_null (user);
1259       return GNUNET_SYSERR;
1260     }
1261   if (0 > FPRINTF (pidfd, "%u", pid))
1262     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1263   GNUNET_break (0 == fclose (pidfd));
1264   if ((user != NULL) && (0 < strlen (user)))
1265     GNUNET_DISK_file_change_owner (pif, user);
1266   GNUNET_free_non_null (user);
1267   GNUNET_free (pif);
1268   return GNUNET_OK;
1269 }
1270
1271
1272 /**
1273  * Task run during shutdown.
1274  *
1275  * @param cls unused
1276  * @param tc unused
1277  */
1278 static void
1279 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1280 {
1281   struct GNUNET_SERVER_Handle *server = cls;
1282
1283   GNUNET_SERVER_destroy (server);
1284 }
1285
1286
1287 /**
1288  * Initial task for the service.
1289  */
1290 static void
1291 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1292 {
1293   struct GNUNET_SERVICE_Context *sctx = cls;
1294   unsigned int i;
1295
1296   if (sctx->lsocks != NULL)
1297     sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1298                                                       sctx,
1299                                                       sctx->lsocks,
1300                                                       sctx->timeout, sctx->require_found);
1301   else
1302     sctx->server = GNUNET_SERVER_create (&check_access,
1303                                          sctx,
1304                                          sctx->addrs,
1305                                          sctx->addrlens,
1306                                          sctx->timeout, sctx->require_found);
1307   if (sctx->server == NULL)
1308     {
1309       if (sctx->addrs != NULL)
1310         {
1311           i = 0;
1312           while (sctx->addrs[i] != NULL)
1313             {
1314               GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1315                           _("Failed to start `%s' at `%s'\n"),
1316                           sctx->serviceName, 
1317                           GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1318               i++;
1319             }
1320         }
1321       sctx->ret = GNUNET_SYSERR;
1322       return;
1323     }
1324   if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1325     {
1326       /* install a task that will kill the server
1327          process if the scheduler ever gets a shutdown signal */
1328       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1329                                     &shutdown_task, sctx->server);
1330     }
1331   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1332   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1333   i = 0;
1334   while ((sctx->my_handlers[i].callback != NULL))
1335     sctx->my_handlers[i++].callback_cls = sctx;
1336   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1337   if (sctx->ready_confirm_fd != -1)
1338     {
1339       GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1340       GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1341       sctx->ready_confirm_fd = -1;
1342       write_pid_file (sctx, getpid ());
1343     }
1344   if (sctx->addrs != NULL)
1345     {
1346       i = 0;
1347       while (sctx->addrs[i] != NULL)
1348         {
1349           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1350                       _("Service `%s' runs at %s\n"),
1351                       sctx->serviceName, 
1352                       GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1353           i++;
1354         }
1355     }
1356   sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1357 }
1358
1359
1360 /**
1361  * Detach from terminal.
1362  */
1363 static int
1364 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1365 {
1366 #ifndef MINGW
1367   pid_t pid;
1368   int nullfd;
1369   int filedes[2];
1370
1371   if (0 != PIPE (filedes))
1372     {
1373       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1374       return GNUNET_SYSERR;
1375     }
1376   pid = fork ();
1377   if (pid < 0)
1378     {
1379       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1380       return GNUNET_SYSERR;
1381     }
1382   if (pid != 0)
1383     {
1384       /* Parent */
1385       char c;
1386
1387       GNUNET_break (0 == CLOSE (filedes[1]));
1388       c = 'X';
1389       if (1 != READ (filedes[0], &c, sizeof (char)))
1390         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1391       fflush (stdout);
1392       switch (c)
1393         {
1394         case '.':
1395           exit (0);
1396         case 'I':
1397           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1398                       _("Service process failed to initialize\n"));
1399           break;
1400         case 'S':
1401           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1402                       _
1403                       ("Service process could not initialize server function\n"));
1404           break;
1405         case 'X':
1406           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1407                       _("Service process failed to report status\n"));
1408           break;
1409         }
1410       exit (1);                 /* child reported error */
1411     }
1412   GNUNET_break (0 == CLOSE (0));
1413   GNUNET_break (0 == CLOSE (1));
1414   GNUNET_break (0 == CLOSE (filedes[0]));
1415   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1416   if (nullfd < 0)
1417     return GNUNET_SYSERR;
1418   /* set stdin/stdout to /dev/null */
1419   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1420     {      
1421       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1422       (void) CLOSE (nullfd);
1423       return GNUNET_SYSERR;
1424     }
1425   (void) CLOSE (nullfd);
1426   /* Detach from controlling terminal */
1427   pid = setsid ();
1428   if (pid == -1)
1429     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1430   sctx->ready_confirm_fd = filedes[1];
1431 #else
1432   /* FIXME: we probably need to do something else
1433      elsewhere in order to fork the process itself... */
1434   FreeConsole ();
1435 #endif
1436   return GNUNET_OK;
1437 }
1438
1439
1440 /**
1441  * Set user ID.
1442  */
1443 static int
1444 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1445 {
1446   char *user;
1447
1448   if (NULL == (user = get_user_name (sctx)))
1449     return GNUNET_OK;           /* keep */
1450 #ifndef MINGW
1451   struct passwd *pws;
1452
1453   errno = 0;
1454   pws = getpwnam (user);
1455   if (pws == NULL)
1456     {
1457       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1458                   _("Cannot obtain information about user `%s': %s\n"),
1459                   user, errno == 0 ? _("No such user") : STRERROR (errno));
1460       GNUNET_free (user);
1461       return GNUNET_SYSERR;
1462     }
1463   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1464 #if HAVE_INITGROUPS
1465       (0 != initgroups (user, pws->pw_gid)) ||
1466 #endif
1467       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1468     {
1469       if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1470           (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1471         {
1472           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1473                       _("Cannot change user/group to `%s': %s\n"), user,
1474                       STRERROR (errno));
1475           GNUNET_free (user);
1476           return GNUNET_SYSERR;
1477         }
1478     }
1479 #endif
1480   GNUNET_free (user);
1481   return GNUNET_OK;
1482 }
1483
1484
1485 /**
1486  * Delete the PID file that was created by our parent.
1487  */
1488 static void
1489 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1490 {
1491   char *pif = get_pid_file_name (sctx);
1492   if (pif == NULL)
1493     return;                     /* no PID file */
1494   if (0 != UNLINK (pif))
1495     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1496   GNUNET_free (pif);
1497 }
1498
1499
1500 /**
1501  * Run a standard GNUnet service startup sequence (initialize loggers
1502  * and configuration, parse options).
1503  *
1504  * @param argc number of command line arguments
1505  * @param argv command line arguments
1506  * @param serviceName our service name
1507  * @param opt service options
1508  * @param task main task of the service
1509  * @param task_cls closure for task
1510  * @return GNUNET_SYSERR on error, GNUNET_OK
1511  *         if we shutdown nicely
1512  */
1513 int
1514 GNUNET_SERVICE_run (int argc,
1515                     char *const *argv,
1516                     const char *serviceName,
1517                     enum GNUNET_SERVICE_Options opt,
1518                     GNUNET_SERVICE_Main task, void *task_cls)
1519 {
1520 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1521
1522   int err;
1523   char *cfg_fn;
1524   char *loglev;
1525   char *logfile;
1526   int do_daemonize;
1527   unsigned int i;
1528   struct GNUNET_SERVICE_Context sctx;
1529   struct GNUNET_CONFIGURATION_Handle *cfg;
1530   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1531     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1532     {'d', "daemonize", NULL,
1533      gettext_noop ("do daemonize (detach from terminal)"), 0,
1534      GNUNET_GETOPT_set_one, &do_daemonize},
1535     GNUNET_GETOPT_OPTION_HELP (serviceName),
1536     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1537     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1538     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1539     GNUNET_GETOPT_OPTION_END
1540   };
1541   err = 0;
1542   do_daemonize = 0;
1543   logfile = NULL;
1544   loglev = GNUNET_strdup ("WARNING");
1545   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1546   memset (&sctx, 0, sizeof (sctx));
1547   sctx.options = opt;
1548   sctx.ready_confirm_fd = -1;
1549   sctx.ret = GNUNET_OK;
1550   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1551   sctx.task = task;
1552   sctx.task_cls = task_cls;
1553   sctx.serviceName = serviceName;
1554   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1555   /* setup subsystems */
1556   if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1557       argv))    
1558     goto shutdown;
1559   if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1560     HANDLE_ERROR;
1561   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1562     goto shutdown;
1563   if (GNUNET_OK != setup_service (&sctx))
1564     goto shutdown;
1565   if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))    
1566     HANDLE_ERROR;
1567   if (GNUNET_OK != set_user_id (&sctx))
1568     goto shutdown;
1569 #if DEBUG_SERVICE
1570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1571               "Service `%s' runs with configuration from `%s'\n",
1572               serviceName, cfg_fn);
1573 #endif
1574   /* actually run service */
1575   GNUNET_SCHEDULER_run (&service_task, &sctx);
1576
1577   /* shutdown */
1578   if ((do_daemonize == 1) && (sctx.server != NULL))
1579     pid_file_delete (&sctx);
1580   GNUNET_free_non_null (sctx.my_handlers);
1581
1582 shutdown:
1583   if (sctx.ready_confirm_fd != -1)
1584     {
1585       if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1586         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1587       GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1588     }
1589
1590   GNUNET_CONFIGURATION_destroy (cfg);
1591   i = 0;
1592   if (sctx.addrs != NULL)
1593     while (sctx.addrs[i] != NULL)    
1594       GNUNET_free (sctx.addrs[i++]);    
1595   GNUNET_free_non_null (sctx.addrs);
1596   GNUNET_free_non_null (sctx.addrlens);
1597   GNUNET_free_non_null (logfile);
1598   GNUNET_free (loglev);
1599   GNUNET_free (cfg_fn);
1600   GNUNET_free_non_null (sctx.v4_denied);
1601   GNUNET_free_non_null (sctx.v6_denied);
1602   GNUNET_free_non_null (sctx.v4_allowed);
1603   GNUNET_free_non_null (sctx.v6_allowed);
1604
1605   return err ? GNUNET_SYSERR : sctx.ret;
1606 }
1607
1608
1609 /**
1610  * Run a service startup sequence within an existing
1611  * initialized system.
1612  *
1613  * @param serviceName our service name
1614  * @param cfg configuration to use
1615  * @return NULL on error, service handle
1616  */
1617 struct GNUNET_SERVICE_Context *
1618 GNUNET_SERVICE_start (const char *serviceName,
1619                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1620 {
1621   int i;
1622   struct GNUNET_SERVICE_Context *sctx;
1623
1624   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1625   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1626   sctx->ret = GNUNET_OK;
1627   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1628   sctx->serviceName = serviceName;
1629   sctx->cfg = cfg;
1630
1631   /* setup subsystems */
1632   if (GNUNET_OK != setup_service (sctx))
1633     {
1634       GNUNET_SERVICE_stop (sctx);
1635       return NULL;
1636     }
1637   if (sctx->lsocks != NULL)
1638     sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1639                                                       sctx,
1640                                                       sctx->lsocks,
1641                                                       sctx->timeout, sctx->require_found);
1642   else
1643     sctx->server = GNUNET_SERVER_create (&check_access,
1644                                          sctx,
1645                                          sctx->addrs,
1646                                          sctx->addrlens,
1647                                          sctx->timeout,
1648                                          sctx->require_found);
1649                                          
1650   if (NULL == sctx->server)
1651     {
1652       GNUNET_SERVICE_stop (sctx);
1653       return NULL;
1654     }
1655   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1656   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1657   i = 0;
1658   while ((sctx->my_handlers[i].callback != NULL))
1659     sctx->my_handlers[i++].callback_cls = sctx;
1660   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1661   return sctx;
1662 }
1663
1664 /**
1665  * Obtain the server used by a service.  Note that the server must NOT
1666  * be destroyed by the caller.
1667  *
1668  * @param ctx the service context returned from the start function
1669  * @return handle to the server for this service, NULL if there is none
1670  */
1671 struct GNUNET_SERVER_Handle *
1672 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1673 {
1674   return ctx->server;
1675 }
1676
1677
1678 /**
1679  * Stop a service that was started with "GNUNET_SERVICE_start".
1680  *
1681  * @param sctx the service context returned from the start function
1682  */
1683 void
1684 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1685 {
1686   unsigned int i;
1687   if (NULL != sctx->server)
1688     GNUNET_SERVER_destroy (sctx->server);
1689   GNUNET_free_non_null (sctx->my_handlers);
1690   if (sctx->addrs != NULL)
1691     {
1692       i = 0;
1693       while (sctx->addrs[i] != NULL)    
1694         GNUNET_free (sctx->addrs[i++]);    
1695       GNUNET_free (sctx->addrs);
1696     }
1697   GNUNET_free_non_null (sctx->addrlens);
1698   GNUNET_free_non_null (sctx->v4_denied);
1699   GNUNET_free_non_null (sctx->v6_denied);
1700   GNUNET_free_non_null (sctx->v4_allowed);
1701   GNUNET_free_non_null (sctx->v6_allowed);
1702   GNUNET_free (sctx);
1703 }
1704
1705
1706 /* end of service.c */