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