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