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