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