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