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