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