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