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