unload again
[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 (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    * Length of addr.
518    */
519   socklen_t addrlen;
520
521 };
522
523
524 /* ****************** message handlers ****************** */
525
526 static size_t
527 write_test (void *cls, size_t size, void *buf)
528 {
529   struct GNUNET_SERVER_Client *client = cls;
530   struct GNUNET_MessageHeader *msg;
531
532   if (size < sizeof (struct GNUNET_MessageHeader))
533     {
534       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
535       return 0;                 /* client disconnected */
536     }
537   msg = (struct GNUNET_MessageHeader *) buf;
538   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
539   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
540   GNUNET_SERVER_receive_done (client, GNUNET_OK);
541   return sizeof (struct GNUNET_MessageHeader);
542 }
543
544 /**
545  * Handler for TEST message.
546  *
547  * @param cls closure (refers to service)
548  * @param client identification of the client
549  * @param message the actual message
550  */
551 static void
552 handle_test (void *cls,
553              struct GNUNET_SERVER_Client *client,
554              const struct GNUNET_MessageHeader *message)
555 {
556   /* simply bounce message back to acknowledge */
557   if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
558                                                    sizeof (struct
559                                                            GNUNET_MessageHeader),
560                                                    GNUNET_TIME_UNIT_FOREVER_REL,
561                                                    &write_test, client))
562     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
563 }
564
565
566 /**
567  * Handler for SHUTDOWN message.
568  *
569  * @param cls closure (refers to service)
570  * @param client identification of the client
571  * @param message the actual message
572  */
573 static void
574 handle_shutdown (void *cls,
575                  struct GNUNET_SERVER_Client *client,
576                  const struct GNUNET_MessageHeader *message)
577 {
578   struct GNUNET_SERVICE_Context *service = cls;
579   if (!service->allow_shutdown)
580     {
581       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
582                   _
583                   ("Received shutdown request, but configured to ignore!\n"));
584       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
585       return;
586     }
587   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
588               _("Initiating shutdown as requested by client.\n"));
589   GNUNET_assert (service->sched != NULL);
590   GNUNET_SCHEDULER_shutdown (service->sched);
591   GNUNET_SERVER_receive_done (client, GNUNET_OK);
592 }
593
594
595 /**
596  * Default handlers for all services.  Will be copied and the
597  * "callback_cls" fields will be replaced with the specific service
598  * struct.
599  */
600 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
601   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
602    sizeof (struct GNUNET_MessageHeader)},
603   {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_SHUTDOWN,
604    sizeof (struct GNUNET_MessageHeader)},
605   {NULL, NULL, 0, 0}
606 };
607
608
609
610 /* ****************** service core routines ************** */
611
612
613 /**
614  * Check if access to the service is allowed from the given address.
615  */
616 static int
617 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
618 {
619   struct GNUNET_SERVICE_Context *sctx = cls;
620   const struct sockaddr_in *i4;
621   const struct sockaddr_in6 *i6;
622   int ret;
623
624   switch (addr->sa_family)
625     {
626     case AF_INET:
627       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
628       i4 = (const struct sockaddr_in *) addr;
629       ret = ((sctx->v4_allowed == NULL) ||
630              (check_ipv4_listed (sctx->v4_allowed,
631                                  &i4->sin_addr)))
632         && ((sctx->v4_denied == NULL) ||
633             (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
634       break;
635     case AF_INET6:
636       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
637       i6 = (const struct sockaddr_in6 *) addr;
638       ret = ((sctx->v6_allowed == NULL) ||
639              (check_ipv6_listed (sctx->v6_allowed,
640                                  &i6->sin6_addr)))
641         && ((sctx->v6_denied == NULL) ||
642             (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
643       break;
644     default:
645       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
646                   _("Unknown address family %d\n"), addr->sa_family);
647       return GNUNET_SYSERR;
648     }
649   if (ret != GNUNET_OK)
650     {
651       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
652                   _("Access from `%s' denied to service `%s'\n"),
653                   GNUNET_a2s(addr, addrlen), sctx->serviceName);
654     }
655   return ret;
656 }
657
658
659 /**
660  * Get the name of the file where we will
661  * write the PID of the service.
662  */
663 static char *
664 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
665 {
666
667   char *pif;
668
669   if (GNUNET_OK !=
670       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
671                                                sctx->serviceName,
672                                                "PIDFILE", &pif))
673     return NULL;
674   return pif;
675 }
676
677
678 /**
679  * Parse an IPv4 access control list.
680  */
681 static int
682 process_acl4 (struct IPv4NetworkSet **ret,
683               struct GNUNET_SERVICE_Context *sctx, const char *option)
684 {
685   char *opt;
686
687   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
688     return GNUNET_OK;
689   GNUNET_break (GNUNET_OK ==
690                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
691                                                        sctx->serviceName,
692                                                        option, &opt));
693   if (NULL == (*ret = parse_ipv4_specification (opt)))
694     {
695       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
696                   _
697                   ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
698                   opt, sctx->serviceName, option);
699       GNUNET_free (opt);
700       return GNUNET_SYSERR;
701     }
702   GNUNET_free (opt);
703   return GNUNET_OK;
704 }
705
706
707 /**
708  * Parse an IPv4 access control list.
709  */
710 static int
711 process_acl6 (struct IPv6NetworkSet **ret,
712               struct GNUNET_SERVICE_Context *sctx, const char *option)
713 {
714   char *opt;
715   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
716     return GNUNET_OK;
717   GNUNET_break (GNUNET_OK ==
718                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
719                                                        sctx->serviceName,
720                                                        option, &opt));
721   if (NULL == (*ret = parse_ipv6_specification (opt)))
722     {
723       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
724                   _
725                   ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
726                   opt, sctx->serviceName, option);
727       GNUNET_free (opt);
728       return GNUNET_SYSERR;
729     }
730   GNUNET_free (opt);
731   return GNUNET_OK;
732 }
733
734
735 /**
736  * Setup addr, addrlen, maxbuf, idle_timeout
737  * based on configuration!
738  *
739  * Configuration must specify a "PORT".  It may
740  * specify:
741  * - TIMEOUT (after how many ms does an inactive service timeout);
742  * - MAXBUF (maximum incoming message size supported)
743  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
744  * - ALLOW_SHUTDOWN (allow clients to shutdown this service)
745  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
746  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
747  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
748  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
749  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
750  *
751  * @return GNUNET_OK if configuration succeeded
752  */
753 static int
754 setup_service (struct GNUNET_SERVICE_Context *sctx)
755 {
756   unsigned long long maxbuf;
757   struct GNUNET_TIME_Relative idleout;
758   char *hostname;
759   unsigned long long port;
760   int disablev6;
761   struct addrinfo hints;
762   struct addrinfo *res;
763   struct addrinfo *pos;
764   int ret;
765   int tolerant;
766   struct GNUNET_NETWORK_Handle *desc;
767
768   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
769                                        sctx->serviceName, "TIMEOUT"))
770     {
771       if (GNUNET_OK !=
772           GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
773                                                sctx->serviceName,
774                                                "TIMEOUT", &idleout))
775         return GNUNET_SYSERR;
776
777       sctx->timeout = idleout;
778     }
779   else
780     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
781   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
782                                        sctx->serviceName, "MAXBUF"))
783     {
784       if (GNUNET_OK !=
785           GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
786                                                  sctx->serviceName,
787                                                  "MAXBUF", &maxbuf))
788         return GNUNET_SYSERR;
789     }
790   else
791     maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
792   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
793                                        sctx->serviceName, "DISABLEV6"))
794     {
795       if (GNUNET_SYSERR ==
796           (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
797                                                              sctx->serviceName,
798                                                              "DISABLEV6")))
799         return GNUNET_SYSERR;
800     }
801   else
802     disablev6 = GNUNET_NO;
803   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
804                                        sctx->serviceName, "ALLOW_SHUTDOWN"))
805     {
806       if (GNUNET_SYSERR ==
807           (sctx->allow_shutdown =
808            GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
809                                                  "ALLOW_SHUTDOWN")))
810         return GNUNET_SYSERR;
811     }
812   else
813     sctx->allow_shutdown = GNUNET_NO;
814
815   if (!disablev6)
816     {
817       /* probe IPv6 support */
818       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
819       if (NULL == desc)
820         {
821           if ((errno == ENOBUFS) ||
822               (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
823             {
824               GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
825               return GNUNET_SYSERR;
826             }
827           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
828                       _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
829                       sctx->serviceName,
830                       STRERROR (errno));
831           disablev6 = GNUNET_YES;
832         }
833       else
834         {
835           GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
836         }
837     }
838
839
840
841   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
842                                        sctx->serviceName, "TOLERANT"))
843     {
844       if (GNUNET_SYSERR ==
845           (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
846                                                             sctx->serviceName,
847                                                             "TOLERANT")))
848         return GNUNET_SYSERR;
849     }
850   else
851     tolerant = GNUNET_NO;
852   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
853
854
855   if ((GNUNET_OK !=
856        GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
857                                               sctx->serviceName,
858                                               "PORT",
859                                               &port)) || (port > 65535))
860     {
861       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
862                   _
863                   ("Require valid port number for service `%s' in configuration!\n"),
864                   sctx->serviceName);
865       return GNUNET_SYSERR;
866     }
867   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
868                                        sctx->serviceName, "BINDTO"))
869     {
870       GNUNET_break (GNUNET_OK ==
871                     GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
872                                                            sctx->serviceName,
873                                                            "BINDTO",
874                                                            &hostname));
875     }
876   else
877     hostname = NULL;
878
879   if (hostname != NULL)
880     {
881       memset (&hints, 0, sizeof (struct addrinfo));
882       if (disablev6)
883         hints.ai_family = AF_INET;
884       if ((0 != (ret = getaddrinfo (hostname,
885                                     NULL, &hints, &res))) || (res == NULL))
886         {
887           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
888                       _("Failed to resolve `%s': %s\n"),
889                       hostname, gai_strerror (ret));
890           GNUNET_free (hostname);
891           return GNUNET_SYSERR;
892         }
893       pos = res;
894       while ((NULL != pos) &&
895              (((disablev6) &&
896                (pos->ai_family != AF_INET)) ||
897               ((pos->ai_family != AF_INET) && (pos->ai_family != AF_INET6))))
898         pos = pos->ai_next;
899       if (pos == NULL)
900         {
901           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
902                       _("Failed to find %saddress for `%s'.\n"),
903                       disablev6 ? "IPv4 " : "", hostname);
904           freeaddrinfo (res);
905           GNUNET_free (hostname);
906           return GNUNET_SYSERR;
907         }
908       GNUNET_free (hostname);
909       if (pos->ai_family == AF_INET)
910         {
911           GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
912           sctx->addrlen = pos->ai_addrlen;
913           sctx->addr = GNUNET_malloc (sctx->addrlen);
914           memcpy (sctx->addr, res->ai_addr, sctx->addrlen);
915           ((struct sockaddr_in *) sctx->addr)->sin_port = htons (port);
916           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
917                       _
918                       ("Configured to bind to %s address; %s connections to this service will fail!\n"),
919                       "IPv4", "IPv6");
920         }
921       else
922         {
923           GNUNET_assert (pos->ai_family == AF_INET6);
924           GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
925           sctx->addrlen = pos->ai_addrlen;
926           sctx->addr = GNUNET_malloc (sctx->addrlen);
927           memcpy (sctx->addr, res->ai_addr, sctx->addrlen);
928           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
929                       _
930                       ("Configured to bind to %s address; %s connections to this service will fail!\n"),
931                       "IPv6", "IPv4");
932           ((struct sockaddr_in6 *) sctx->addr)->sin6_port = htons (port);
933         }
934       freeaddrinfo (res);
935     }
936   else
937     {
938       /* will bind against everything, just set port */
939       if (disablev6)
940         {
941           /* V4-only */
942           sctx->addrlen = sizeof (struct sockaddr_in);
943           sctx->addr = GNUNET_malloc (sctx->addrlen);
944 #if HAVE_SOCKADDR_IN_SIN_LEN
945           ((struct sockaddr_in *) sctx->addr)->sin_len = sctx->addrlen;
946 #endif
947           ((struct sockaddr_in *) sctx->addr)->sin_family = AF_INET;
948           ((struct sockaddr_in *) sctx->addr)->sin_port = htons (port);
949           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
950                       _
951                       ("Configured to bind to %s address; %s connections to this service will fail!\n"),
952                       "IPv4", "IPv6");
953         }
954       else
955         {
956           /* dual stack */
957           sctx->addrlen = sizeof (struct sockaddr_in6);
958           sctx->addr = GNUNET_malloc (sctx->addrlen);
959 #if HAVE_SOCKADDR_IN_SIN_LEN
960           ((struct sockaddr_in6 *) sctx->addr)->sin6_len = sctx->addrlen;
961 #endif
962           ((struct sockaddr_in6 *) sctx->addr)->sin6_family = AF_INET6;
963           ((struct sockaddr_in6 *) sctx->addr)->sin6_port = htons (port);
964         }
965     }
966   sctx->maxbuf = (size_t) maxbuf;
967   if (sctx->maxbuf != maxbuf)
968     {
969       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
970                   _
971                   ("Value in configuration for `%s' and service `%s' too large!\n"),
972                   "MAXBUF", sctx->serviceName);
973       return GNUNET_SYSERR;
974     }
975
976
977   if ((GNUNET_OK !=
978        process_acl4 (&sctx->v4_denied,
979                      sctx,
980                      "REJECT_FROM")) ||
981       (GNUNET_OK !=
982        process_acl4 (&sctx->v4_allowed,
983                      sctx,
984                      "ACCEPT_FROM")) ||
985       (GNUNET_OK !=
986        process_acl6 (&sctx->v6_denied,
987                      sctx,
988                      "REJECT_FROM6")) ||
989       (GNUNET_OK != process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6")))
990     return GNUNET_SYSERR;
991   return GNUNET_OK;
992 }
993
994
995 /**
996  * Get the name of the user that'll be used
997  * to provide the service.
998  */
999 static char *
1000 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1001 {
1002
1003   char *un;
1004
1005   if (GNUNET_OK !=
1006       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1007                                                sctx->serviceName,
1008                                                "USERNAME", &un))
1009     return NULL;
1010   return un;
1011 }
1012
1013 /**
1014  * Write PID file.
1015  */
1016 static int
1017 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1018 {
1019   FILE *pidfd;
1020   char *pif;
1021   char *user;
1022   char *rdir;
1023   int len;
1024
1025   if (NULL == (pif = get_pid_file_name (sctx)))
1026     return GNUNET_OK;           /* no file desired */
1027   user = get_user_name (sctx);
1028   rdir = GNUNET_strdup (pif);
1029   len = strlen (rdir);
1030   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1031     len--;
1032   rdir[len] = '\0';
1033   if (0 != ACCESS (rdir, F_OK))
1034     {
1035       /* we get to create a directory -- and claim it
1036          as ours! */
1037       GNUNET_DISK_directory_create (rdir);
1038       if ((user != NULL) && (0 < strlen (user)))
1039         GNUNET_DISK_file_change_owner (rdir, user);
1040     }
1041   if (0 != ACCESS (rdir, W_OK | X_OK))
1042     {
1043       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1044       GNUNET_free (rdir);
1045       GNUNET_free_non_null (user);
1046       GNUNET_free (pif);
1047       return GNUNET_SYSERR;
1048     }
1049   GNUNET_free (rdir);
1050   pidfd = FOPEN (pif, "w");
1051   if (pidfd == NULL)
1052     {
1053       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1054       GNUNET_free (pif);
1055       GNUNET_free_non_null (user);
1056       return GNUNET_SYSERR;
1057     }
1058   if (0 > FPRINTF (pidfd, "%u", pid))
1059     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1060   GNUNET_break (0 == fclose (pidfd));
1061   if ((user != NULL) && (0 < strlen (user)))
1062     GNUNET_DISK_file_change_owner (pif, user);
1063   GNUNET_free_non_null (user);
1064   GNUNET_free (pif);
1065   return GNUNET_OK;
1066 }
1067
1068
1069 /**
1070  * Initial task for the service.
1071  */
1072 static void
1073 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1074 {
1075   struct GNUNET_SERVICE_Context *sctx = cls;
1076   unsigned int i;
1077
1078   sctx->sched = tc->sched;
1079   sctx->server = GNUNET_SERVER_create (tc->sched,
1080                                        &check_access,
1081                                        sctx,
1082                                        sctx->addr,
1083                                        sctx->addrlen,
1084                                        sctx->maxbuf,
1085                                        sctx->timeout, sctx->require_found);
1086   if (sctx->server == NULL)
1087     {
1088       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1089                   _("Failed to start `%s' at `%s'\n"),
1090                   sctx->serviceName, 
1091                   GNUNET_a2s (sctx->addr,
1092                               sctx->addrlen));
1093       sctx->ret = GNUNET_SYSERR;
1094       return;
1095     }
1096   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1097   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1098   i = 0;
1099   while ((sctx->my_handlers[i].callback != NULL))
1100     sctx->my_handlers[i++].callback_cls = sctx;
1101   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1102   if (sctx->ready_confirm_fd != -1)
1103     {
1104       GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1105       GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1106       sctx->ready_confirm_fd = -1;
1107       write_pid_file (sctx, getpid ());
1108     }
1109   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1110               _("Service `%s' runs at %s\n"),
1111               sctx->serviceName,
1112               GNUNET_a2s (sctx->addr,
1113                           sctx->addrlen));
1114   sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1115 }
1116
1117
1118 /**
1119  * Detach from terminal.
1120  */
1121 static int
1122 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1123 {
1124 #ifndef MINGW 
1125   pid_t pid;
1126   int nullfd;
1127   int filedes[2];
1128
1129   if (0 != PIPE (filedes))
1130     {
1131       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1132       return GNUNET_SYSERR;
1133     }
1134   pid = fork ();
1135   if (pid < 0)
1136     {
1137       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1138       return GNUNET_SYSERR;
1139     }
1140   if (pid != 0)
1141     {
1142       /* Parent */
1143       char c;
1144
1145       GNUNET_break (0 == CLOSE (filedes[1]));
1146       c = 'X';
1147       if (1 != READ (filedes[0], &c, sizeof (char)))
1148         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1149       fflush (stdout);
1150       switch (c)
1151         {
1152         case '.':
1153           exit (0);
1154         case 'I':
1155           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1156                       _("Service process failed to initialize\n"));
1157           break;
1158         case 'S':
1159           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1160                       _
1161                       ("Service process could not initialize server function\n"));
1162           break;
1163         case 'X':
1164           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1165                       _("Service process failed to report status\n"));
1166           break;
1167         }
1168       exit (1);                 /* child reported error */
1169     }
1170   GNUNET_break (0 == CLOSE (0));
1171   GNUNET_break (0 == CLOSE (1));
1172   GNUNET_break (0 == CLOSE (filedes[0]));
1173   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1174   if (nullfd < 0)
1175     return GNUNET_SYSERR;
1176   /* set stdin/stdout to /dev/null */
1177   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1178     {
1179       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1180       return GNUNET_SYSERR;
1181     }
1182   /* Detach from controlling terminal */
1183   pid = setsid ();
1184   if (pid == -1)
1185     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1186   sctx->ready_confirm_fd = filedes[1];
1187 #else
1188   /* FIXME: we probably need to do something else
1189      elsewhere in order to fork the process itself... */
1190   FreeConsole ();
1191 #endif
1192   return GNUNET_OK;
1193 }
1194
1195
1196 /**
1197  * Set user ID.
1198  */
1199 static int
1200 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1201 {
1202   char *user;
1203
1204   if (NULL == (user = get_user_name (sctx)))
1205     return GNUNET_OK;           /* keep */
1206 #ifndef MINGW
1207   struct passwd *pws;
1208
1209   errno = 0;
1210   pws = getpwnam (user);
1211   if (pws == NULL)
1212     {
1213       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1214                   _("Cannot obtain information about user `%s': %s\n"),
1215                   user, errno == 0 ? _("No such user") : STRERROR (errno));
1216       GNUNET_free (user);
1217       return GNUNET_SYSERR;
1218     }
1219   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1220 #if HAVE_INITGROUPS
1221       (0 != initgroups (user, pws->pw_gid)) ||
1222 #endif
1223       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1224     {
1225       if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1226           (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1227         {
1228           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1229                       _("Cannot change user/group to `%s': %s\n"), user,
1230                       STRERROR (errno));
1231           GNUNET_free (user);
1232           return GNUNET_SYSERR;
1233         }
1234     }
1235 #endif
1236   GNUNET_free (user);
1237   return GNUNET_OK;
1238 }
1239
1240
1241 /**
1242  * Delete the PID file that was created by our parent.
1243  */
1244 static void
1245 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1246 {
1247   char *pif = get_pid_file_name (sctx);
1248   if (pif == NULL)
1249     return;                     /* no PID file */
1250   if (0 != UNLINK (pif))
1251     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1252   GNUNET_free (pif);
1253 }
1254
1255 /**
1256  * Run a standard GNUnet service startup sequence (initialize loggers
1257  * and configuration, parse options).
1258  *
1259  * @param argc number of command line arguments
1260  * @param argv command line arguments
1261  * @param serviceName our service name
1262  * @param task main task of the service
1263  * @param task_cls closure for task
1264  * @param term termination task of the service
1265  * @param term_cls closure for term
1266  * @return GNUNET_SYSERR on error, GNUNET_OK
1267  *         if we shutdown nicely
1268  */
1269 int
1270 GNUNET_SERVICE_run (int argc,
1271                     char *const *argv,
1272                     const char *serviceName,
1273                     GNUNET_SERVICE_Main task,
1274                     void *task_cls, GNUNET_SERVICE_Term term, void *term_cls)
1275 {
1276   char *cfg_fn;
1277   char *loglev;
1278   char *logfile;
1279   int do_daemonize;
1280   struct GNUNET_SERVICE_Context sctx;
1281   struct GNUNET_CONFIGURATION_Handle *cfg;
1282   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1283     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1284     {'d', "daemonize", NULL,
1285      gettext_noop ("do daemonize (detach from terminal)"), 0,
1286      GNUNET_GETOPT_set_one, &do_daemonize},
1287     GNUNET_GETOPT_OPTION_HELP (serviceName),
1288     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1289     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1290     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1291     GNUNET_GETOPT_OPTION_END
1292   };
1293   do_daemonize = 0;
1294   logfile = NULL;
1295   loglev = GNUNET_strdup ("WARNING");
1296   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_DAEMON_CONFIG_FILE);
1297   memset (&sctx, 0, sizeof (sctx));
1298   sctx.ready_confirm_fd = -1;
1299   sctx.ret = GNUNET_OK;
1300   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1301   sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1302   sctx.task = task;
1303   sctx.serviceName = serviceName;
1304   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1305   /* setup subsystems */
1306   if ((GNUNET_SYSERR ==
1307        GNUNET_GETOPT_run (serviceName,                         
1308                           service_options,
1309                           argc,
1310                           argv)) ||
1311       (GNUNET_OK !=
1312        GNUNET_log_setup (serviceName, loglev, logfile)) ||
1313       (GNUNET_OK !=
1314        GNUNET_CONFIGURATION_load (cfg, cfg_fn)) ||
1315       (GNUNET_OK !=
1316        setup_service (&sctx)) ||
1317       ((do_daemonize == 1) &&
1318        (GNUNET_OK != detach_terminal (&sctx))) ||
1319       (GNUNET_OK != set_user_id (&sctx)))
1320     {
1321       if (sctx.ready_confirm_fd != -1)
1322         {
1323           if (1 != WRITE (sctx.ready_confirm_fd, "I", 1))
1324             GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1325           GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1326         }
1327       GNUNET_CONFIGURATION_destroy (cfg);
1328       GNUNET_free_non_null (sctx.addr);
1329       GNUNET_free_non_null (logfile);
1330       GNUNET_free (loglev);
1331       GNUNET_free (cfg_fn);
1332       GNUNET_free_non_null (sctx.v4_denied);
1333       GNUNET_free_non_null (sctx.v6_denied);
1334       GNUNET_free_non_null (sctx.v4_allowed);
1335       GNUNET_free_non_null (sctx.v6_allowed);
1336       return GNUNET_SYSERR;
1337     }
1338
1339   /* actually run service */
1340   GNUNET_SCHEDULER_run (&service_task, &sctx);
1341   if (sctx.ready_confirm_fd != -1)
1342     {
1343       if (1 != WRITE (sctx.ready_confirm_fd, "S", 1))
1344         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1345       GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1346     }
1347
1348   /* shutdown */
1349   if (term != NULL)
1350     term (term_cls, sctx.cfg);
1351   if ((do_daemonize == 1) && (sctx.server != NULL))
1352     pid_file_delete (&sctx);
1353   if (sctx.server != NULL)
1354     GNUNET_SERVER_destroy (sctx.server);
1355   GNUNET_free_non_null (sctx.my_handlers);
1356   GNUNET_CONFIGURATION_destroy (cfg);
1357   GNUNET_free_non_null (sctx.addr);
1358   GNUNET_free_non_null (logfile);
1359   GNUNET_free (loglev);
1360   GNUNET_free (cfg_fn);
1361   GNUNET_free_non_null (sctx.v4_denied);
1362   GNUNET_free_non_null (sctx.v6_denied);
1363   GNUNET_free_non_null (sctx.v4_allowed);
1364   GNUNET_free_non_null (sctx.v6_allowed);
1365   return sctx.ret;
1366 }
1367
1368
1369 /**
1370  * Run a service startup sequence within an existing
1371  * initialized system.
1372  *
1373  * @param serviceName our service name
1374  * @param sched scheduler to use
1375  * @param cfg configuration to use
1376  * @return NULL on error, service handle
1377  */
1378 struct GNUNET_SERVICE_Context *
1379 GNUNET_SERVICE_start (const char *serviceName,
1380                       struct GNUNET_SCHEDULER_Handle *sched,
1381                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1382 {
1383   int i;
1384   struct GNUNET_SERVICE_Context *sctx;
1385
1386   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1387   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1388   sctx->ret = GNUNET_OK;
1389   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1390   sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1391   sctx->serviceName = serviceName;
1392   sctx->cfg = cfg;
1393   sctx->sched = sched;
1394
1395   /* setup subsystems */
1396   if ((GNUNET_OK != setup_service (sctx)) ||
1397       (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1398                                                      &check_access,
1399                                                      sctx,
1400                                                      sctx->addr,
1401                                                      sctx->addrlen,
1402                                                      sctx->maxbuf,
1403                                                      sctx->timeout,
1404                                                      sctx->require_found))))
1405     {
1406       GNUNET_SERVICE_stop (sctx);
1407       return NULL;
1408     }
1409   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1410   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1411   i = 0;
1412   while ((sctx->my_handlers[i].callback != NULL))
1413     sctx->my_handlers[i++].callback_cls = sctx;
1414   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1415
1416
1417   return sctx;
1418 }
1419
1420 /**
1421  * Obtain the server used by a service.  Note that the server must NOT
1422  * be destroyed by the caller.
1423  *
1424  * @param ctx the service context returned from the start function
1425  * @return handle to the server for this service, NULL if there is none
1426  */
1427 struct GNUNET_SERVER_Handle *
1428 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1429 {
1430   return ctx->server;
1431 }
1432
1433
1434 /**
1435  * Stop a service that was started with "GNUNET_SERVICE_start".
1436  *
1437  * @param sctx the service context returned from the start function
1438  */
1439 void
1440 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1441 {
1442   if (NULL != sctx->server)
1443     GNUNET_SERVER_destroy (sctx->server);
1444   GNUNET_free_non_null (sctx->my_handlers);
1445   GNUNET_free_non_null (sctx->addr);
1446   GNUNET_free_non_null (sctx->v4_denied);
1447   GNUNET_free_non_null (sctx->v6_denied);
1448   GNUNET_free_non_null (sctx->v4_allowed);
1449   GNUNET_free_non_null (sctx->v6_allowed);
1450   GNUNET_free (sctx);
1451 }
1452
1453
1454 /* end of service.c */