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