5f58bcf6a04a2bcc6a4bc87d1c286f1dc7148914
[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 *serviceName;
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  *
540  * @param cls
541  * @param size
542  * @param buf
543  * @return 
544  */
545 static size_t
546 write_test (void *cls, size_t size, void *buf)
547 {
548   struct GNUNET_SERVER_Client *client = cls;
549   struct GNUNET_MessageHeader *msg;
550
551   if (size < sizeof (struct GNUNET_MessageHeader))
552   {
553     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
554     return 0;                   /* client disconnected */
555   }
556   msg = (struct GNUNET_MessageHeader *) buf;
557   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
558   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
559   GNUNET_SERVER_receive_done (client, GNUNET_OK);
560   return sizeof (struct GNUNET_MessageHeader);
561 }
562
563
564 /**
565  * Handler for TEST message.
566  *
567  * @param cls closure (refers to service)
568  * @param client identification of the client
569  * @param message the actual message
570  */
571 static void
572 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
573              const struct GNUNET_MessageHeader *message)
574 {
575   /* simply bounce message back to acknowledge */
576   if (NULL ==
577       GNUNET_SERVER_notify_transmit_ready (client,
578                                            sizeof (struct GNUNET_MessageHeader),
579                                            GNUNET_TIME_UNIT_FOREVER_REL,
580                                            &write_test, client))
581     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
582 }
583
584
585 /**
586  * Default handlers for all services.  Will be copied and the
587  * "callback_cls" fields will be replaced with the specific service
588  * struct.
589  */
590 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
591   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
592    sizeof (struct GNUNET_MessageHeader)},
593   {NULL, NULL, 0, 0}
594 };
595
596
597 /* ****************** service core routines ************** */
598
599
600 /**
601  * Check if access to the service is allowed from the given address.
602  *
603  * @param cls closure
604  * @param uc credentials, if available, otherwise NULL
605  * @param addr address
606  * @param addrlen length of address
607  * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
608  *   for unknown address family (will be denied).
609  */
610 static int
611 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
612               const struct sockaddr *addr, socklen_t addrlen)
613 {
614   struct GNUNET_SERVICE_Context *sctx = cls;
615   const struct sockaddr_in *i4;
616   const struct sockaddr_in6 *i6;
617   int ret;
618
619   switch (addr->sa_family)
620   {
621   case AF_INET:
622     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
623     i4 = (const struct sockaddr_in *) addr;
624     ret = ((NULL == sctx->v4_allowed) ||
625            (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
626         ((NULL == sctx->v4_denied) ||
627          (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
628     break;
629   case AF_INET6:
630     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
631     i6 = (const struct sockaddr_in6 *) addr;
632     ret = ((NULL == sctx->v6_allowed) ||
633            (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
634         ((NULL == sctx->v6_denied) ||
635          (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
636     break;
637 #ifndef WINDOWS
638   case AF_UNIX:
639     ret = GNUNET_OK;            /* always OK for now */
640     if (GNUNET_YES == sctx->match_uid) 
641     {
642       /* UID match required */
643       ret = (NULL != uc) && (uc->uid == geteuid ());
644     }
645     else if ( (GNUNET_YES == sctx->match_gid) &&
646               ( (NULL == uc) || (uc->uid != geteuid ()) ) )
647     {
648       /* group match required and UID does not match */
649       if (NULL == uc) 
650       {
651         /* no credentials, group match not possible */
652         ret = GNUNET_NO;
653       }
654       else
655       {
656         struct group *grp;
657         unsigned int i;
658
659         if (uc->gid != getegid())
660         {
661           /* default group did not match, but maybe the user is in our group, let's check */
662           grp = getgrgid (getegid ());
663           if (NULL == grp)
664           {
665             GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "getgrgid");
666             return GNUNET_NO;
667           }
668           ret = GNUNET_NO;
669           for (i=0; NULL != grp->gr_mem[i]; i++)
670           {
671             struct passwd *nam = getpwnam (grp->gr_mem[i]);
672             if (NULL == nam)
673               continue; /* name in group that is not in user DB !? */
674             if (nam->pw_uid == uc->uid)
675             {
676               /* yes, uid is in our group, allow! */
677               ret = GNUNET_YES;
678               break;
679             }
680           }
681         }
682       }
683     }
684     if (GNUNET_NO == ret)
685       LOG (GNUNET_ERROR_TYPE_WARNING, _("Access denied to UID %d / GID %d\n"),
686            (NULL == uc) ? -1 : uc->uid, (NULL == uc) ? -1 : uc->gid);
687     break;
688 #endif
689   default:
690     LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
691          addr->sa_family);
692     return GNUNET_SYSERR;
693   }
694   if (GNUNET_OK != ret)
695   {
696     LOG (GNUNET_ERROR_TYPE_WARNING,
697          _("Access from `%s' denied to service `%s'\n"), 
698          GNUNET_a2s (addr, addrlen),
699          sctx->serviceName);
700   }
701   return ret;
702 }
703
704
705 /**
706  * Get the name of the file where we will
707  * write the PID of the service.
708  *
709  * @param sctx service context
710  * @return name of the file for the process ID
711  */
712 static char *
713 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
714 {
715   char *pif;
716
717   if (GNUNET_OK !=
718       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
719                                                "PIDFILE", &pif))
720     return NULL;
721   return pif;
722 }
723
724
725 /**
726  * Parse an IPv4 access control list.
727  *
728  * @param ret
729  * @param sctx
730  * @param option
731  * @return 
732  */
733 static int
734 process_acl4 (struct IPv4NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
735               const char *option)
736 {
737   char *opt;
738
739   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
740     return GNUNET_OK;
741   GNUNET_break (GNUNET_OK ==
742                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
743                                                        sctx->serviceName,
744                                                        option, &opt));
745   if (NULL == (*ret = parse_ipv4_specification (opt)))
746   {
747     LOG (GNUNET_ERROR_TYPE_WARNING,
748          _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
749          opt, sctx->serviceName, option);
750     GNUNET_free (opt);
751     return GNUNET_SYSERR;
752   }
753   GNUNET_free (opt);
754   return GNUNET_OK;
755 }
756
757
758 /**
759  * Parse an IPv6 access control list.
760  *
761  * @param ret
762  * @param sctx
763  * @param option
764  * @return
765  */
766 static int
767 process_acl6 (struct IPv6NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
768               const char *option)
769 {
770   char *opt;
771
772   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
773     return GNUNET_OK;
774   GNUNET_break (GNUNET_OK ==
775                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
776                                                        sctx->serviceName,
777                                                        option, &opt));
778   if (NULL == (*ret = parse_ipv6_specification (opt)))
779   {
780     LOG (GNUNET_ERROR_TYPE_WARNING,
781          _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
782          opt, sctx->serviceName, option);
783     GNUNET_free (opt);
784     return GNUNET_SYSERR;
785   }
786   GNUNET_free (opt);
787   return GNUNET_OK;
788 }
789
790
791 /**
792  * Add the given UNIX domain path as an address to the
793  * list (as the first entry).
794  *
795  * @param saddrs array to update
796  * @param saddrlens where to store the address length
797  * @param unixpath path to add
798  */
799 static void
800 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
801               const char *unixpath)
802 {
803 #ifdef AF_UNIX
804   struct sockaddr_un *un;
805   size_t slen;
806
807   un = GNUNET_malloc (sizeof (struct sockaddr_un));
808   un->sun_family = AF_UNIX;
809   slen = strlen (unixpath) + 1;
810   if (slen >= sizeof (un->sun_path))
811     slen = sizeof (un->sun_path) - 1;
812   memcpy (un->sun_path, unixpath, slen);
813   un->sun_path[slen] = '\0';
814   slen = sizeof (struct sockaddr_un);
815 #if LINUX
816   un->sun_path[0] = '\0';
817 #endif
818 #if HAVE_SOCKADDR_IN_SIN_LEN
819   un->sun_len = (u_char) slen;
820 #endif
821   *saddrs = (struct sockaddr *) un;
822   *saddrlens = slen;
823 #else
824   /* this function should never be called
825    * unless AF_UNIX is defined! */
826   GNUNET_assert (0);
827 #endif
828 }
829
830
831 /**
832  * Get the list of addresses that a server for the given service
833  * should bind to.
834  *
835  * @param serviceName name of the service
836  * @param cfg configuration (which specifies the addresses)
837  * @param addrs set (call by reference) to an array of pointers to the
838  *              addresses the server should bind to and listen on; the
839  *              array will be NULL-terminated (on success)
840  * @param addr_lens set (call by reference) to an array of the lengths
841  *              of the respective 'struct sockaddr' struct in the 'addrs'
842  *              array (on success)
843  * @return number of addresses found on success,
844  *              GNUNET_SYSERR if the configuration
845  *              did not specify reasonable finding information or
846  *              if it specified a hostname that could not be resolved;
847  *              GNUNET_NO if the number of addresses configured is
848  *              zero (in this case, '*addrs' and '*addr_lens' will be
849  *              set to NULL).
850  */
851 int
852 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
853                                      const struct GNUNET_CONFIGURATION_Handle
854                                      *cfg, struct sockaddr ***addrs,
855                                      socklen_t ** addr_lens)
856 {
857   int disablev6;
858   struct GNUNET_NETWORK_Handle *desc;
859   unsigned long long port;
860   char *unixpath;
861   struct addrinfo hints;
862   struct addrinfo *res;
863   struct addrinfo *pos;
864   struct addrinfo *next;
865   unsigned int i;
866   int resi;
867   int ret;
868   struct sockaddr **saddrs;
869   socklen_t *saddrlens;
870   char *hostname;
871
872   *addrs = NULL;
873   *addr_lens = NULL;
874   desc = NULL;
875   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "DISABLEV6"))
876   {
877     if (GNUNET_SYSERR ==
878         (disablev6 =
879          GNUNET_CONFIGURATION_get_value_yesno (cfg, serviceName, "DISABLEV6")))
880       return GNUNET_SYSERR;
881   }
882   else
883     disablev6 = GNUNET_NO;
884
885   if (!disablev6)
886   {
887     /* probe IPv6 support */
888     desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
889     if (NULL == desc)
890     {
891       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
892           (EACCES == errno))
893       {
894         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
895         return GNUNET_SYSERR;
896       }
897       LOG (GNUNET_ERROR_TYPE_INFO,
898            _
899            ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
900            serviceName, STRERROR (errno));
901       disablev6 = GNUNET_YES;
902     }
903     else
904     {
905       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
906       desc = NULL;
907     }
908   }
909
910   port = 0;
911   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
912   {
913     GNUNET_break (GNUNET_OK ==
914                   GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
915                                                          "PORT", &port));
916     if (port > 65535)
917     {
918       LOG (GNUNET_ERROR_TYPE_ERROR,
919            _("Require valid port number for service `%s' in configuration!\n"),
920            serviceName);
921       return GNUNET_SYSERR;
922     }
923   }
924
925   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "BINDTO"))
926   {
927     GNUNET_break (GNUNET_OK ==
928                   GNUNET_CONFIGURATION_get_value_string (cfg, serviceName,
929                                                          "BINDTO", &hostname));
930   }
931   else
932     hostname = NULL;
933
934   unixpath = NULL;
935 #ifdef AF_UNIX
936   if ((GNUNET_YES ==
937        GNUNET_CONFIGURATION_have_value (cfg, serviceName, "UNIXPATH")) &&
938       (GNUNET_OK ==
939        GNUNET_CONFIGURATION_get_value_string (cfg, serviceName, "UNIXPATH",
940                                               &unixpath)) &&
941       (0 < strlen (unixpath)))
942   {
943     /* probe UNIX support */
944     struct sockaddr_un s_un;
945
946     if (strlen (unixpath) >= sizeof (s_un.sun_path))
947     {
948       LOG (GNUNET_ERROR_TYPE_WARNING,
949            _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
950            sizeof (s_un.sun_path));
951       GNUNET_free_non_null (hostname);
952       GNUNET_free (unixpath);
953       return GNUNET_SYSERR;
954     }
955
956     desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
957     if (NULL == desc)
958     {
959       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
960           (EACCES == errno))
961       {
962         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
963         GNUNET_free_non_null (hostname);
964         GNUNET_free (unixpath);
965         return GNUNET_SYSERR;
966       }
967       LOG (GNUNET_ERROR_TYPE_INFO,
968            _
969            ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
970            serviceName, STRERROR (errno));
971       GNUNET_free (unixpath);
972       unixpath = NULL;
973     }
974     else
975     {
976       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
977       desc = NULL;
978     }
979   }
980 #endif
981
982   if ((0 == port) && (NULL == unixpath))
983   {
984     LOG (GNUNET_ERROR_TYPE_ERROR,
985          _
986          ("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
987          serviceName);
988     GNUNET_free_non_null (hostname);
989     return GNUNET_SYSERR;
990   }
991   if (0 == port)
992   {
993     saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
994     saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
995     add_unixpath (saddrs, saddrlens, unixpath);
996     GNUNET_free_non_null (unixpath);
997     GNUNET_free_non_null (hostname);
998     *addrs = saddrs;
999     *addr_lens = saddrlens;
1000     return 1;
1001   }
1002
1003   if (NULL != hostname)
1004   {
1005     LOG (GNUNET_ERROR_TYPE_DEBUG,
1006          "Resolving `%s' since that is where `%s' will bind to.\n", hostname,
1007          serviceName);
1008     memset (&hints, 0, sizeof (struct addrinfo));
1009     if (disablev6)
1010       hints.ai_family = AF_INET;
1011     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
1012         (res == NULL))
1013     {
1014       LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"), hostname,
1015            gai_strerror (ret));
1016       GNUNET_free (hostname);
1017       GNUNET_free_non_null (unixpath);
1018       return GNUNET_SYSERR;
1019     }
1020     next = res;
1021     i = 0;
1022     while (NULL != (pos = next))
1023     {
1024       next = pos->ai_next;
1025       if ((disablev6) && (pos->ai_family == AF_INET6))
1026         continue;
1027       i++;
1028     }
1029     if (0 == i)
1030     {
1031       LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to find %saddress for `%s'.\n"),
1032            disablev6 ? "IPv4 " : "", hostname);
1033       freeaddrinfo (res);
1034       GNUNET_free (hostname);
1035       GNUNET_free_non_null (unixpath);
1036       return GNUNET_SYSERR;
1037     }
1038     resi = i;
1039     if (NULL != unixpath)
1040       resi++;
1041     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1042     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1043     i = 0;
1044     if (NULL != unixpath)
1045     {
1046       add_unixpath (saddrs, saddrlens, unixpath);
1047       i++;
1048     }
1049     next = res;
1050     while (NULL != (pos = next))
1051     {
1052       next = pos->ai_next;
1053       if ((disablev6) && (AF_INET6 == pos->ai_family))
1054         continue;
1055       if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
1056         continue;               /* not TCP */
1057       if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
1058         continue;               /* huh? */
1059       LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
1060            serviceName, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
1061       if (AF_INET == pos->ai_family)
1062       {
1063         GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1064         saddrlens[i] = pos->ai_addrlen;
1065         saddrs[i] = GNUNET_malloc (saddrlens[i]);
1066         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1067         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1068       }
1069       else
1070       {
1071         GNUNET_assert (AF_INET6 == pos->ai_family);
1072         GNUNET_assert (sizeof (struct sockaddr_in6) == 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_in6 *) saddrs[i])->sin6_port = htons (port);
1077       }
1078       i++;
1079     }
1080     GNUNET_free (hostname);
1081     freeaddrinfo (res);
1082     resi = i;
1083   }
1084   else
1085   {
1086     /* will bind against everything, just set port */
1087     if (disablev6)
1088     {
1089       /* V4-only */
1090       resi = 1;
1091       if (NULL != unixpath)
1092         resi++;
1093       i = 0;
1094       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1095       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1096       if (NULL != unixpath)
1097       {
1098         add_unixpath (saddrs, saddrlens, unixpath);
1099         i++;
1100       }
1101       saddrlens[i] = sizeof (struct sockaddr_in);
1102       saddrs[i] = GNUNET_malloc (saddrlens[i]);
1103 #if HAVE_SOCKADDR_IN_SIN_LEN
1104       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1105 #endif
1106       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1107       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1108     }
1109     else
1110     {
1111       /* dual stack */
1112       resi = 2;
1113       if (NULL != unixpath)
1114         resi++;
1115       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1116       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1117       i = 0;
1118       if (NULL != unixpath)
1119       {
1120         add_unixpath (saddrs, saddrlens, unixpath);
1121         i++;
1122       }
1123       saddrlens[i] = sizeof (struct sockaddr_in6);
1124       saddrs[i] = GNUNET_malloc (saddrlens[i]);
1125 #if HAVE_SOCKADDR_IN_SIN_LEN
1126       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1127 #endif
1128       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1129       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1130       i++;
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[1];
1135 #endif
1136       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1137       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1138     }
1139   }
1140   GNUNET_free_non_null (unixpath);
1141   *addrs = saddrs;
1142   *addr_lens = saddrlens;
1143   return resi;
1144 }
1145
1146
1147 #ifdef MINGW
1148 /**
1149  *
1150  *
1151  * @param sctx 
1152  * @return GNUNET_YES if ok, GNUNET_NO if not ok (must bind yourself),
1153  * and GNUNET_SYSERR on error.
1154  */
1155 static int
1156 receive_sockets_from_parent (struct GNUNET_SERVICE_Context *sctx)
1157 {
1158   const char *env_buf;
1159   int fail;
1160   uint64_t count;
1161   uint64_t i;
1162   HANDLE lsocks_pipe;
1163
1164   env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
1165   if ((NULL == env_buf) || (strlen (env_buf) <= 0))
1166     return GNUNET_NO;
1167   /* Using W32 API directly here, because this pipe will
1168    * never be used outside of this function, and it's just too much of a bother
1169    * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
1170    */
1171   lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10);
1172   if ( (0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
1173     return GNUNET_NO
1174   fail = 1;
1175   do
1176   {
1177     int ret;
1178     int fail2;
1179     DWORD rd;
1180
1181     ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
1182     if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
1183       break;
1184     sctx->lsocks =
1185         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (count + 1));
1186
1187     fail2 = 1;
1188     for (i = 0; i < count; i++)
1189     {
1190       WSAPROTOCOL_INFOA pi;
1191       uint64_t size;
1192       SOCKET s;
1193
1194       ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL);
1195       if ( (0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size) )
1196         break;
1197       ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL);
1198       if ( (0 == ret) || (sizeof (pi) != rd))
1199         break;
1200       s = WSASocketA (pi.iAddressFamily, pi.iSocketType, pi.iProtocol, &pi, 0, WSA_FLAG_OVERLAPPED);
1201       sctx->lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1202       if (NULL == sctx->lsocks[i])
1203         break;
1204       else if (i == count - 1)
1205         fail2 = 0;
1206     }
1207     if (fail2)
1208       break;
1209     sctx->lsocks[count] = NULL;
1210     fail = 0;
1211   }
1212   while (fail);
1213
1214   CloseHandle (lsocks_pipe);
1215
1216   if (fail)
1217   {
1218     LOG (GNUNET_ERROR_TYPE_ERROR,
1219          _("Could not access a pre-bound socket, will try to bind myself\n"));
1220     for (i = 0; (i < count) && (NULL != sctx->lsocks[i]); i++)
1221       GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[i]));
1222     GNUNET_free_non_null (sctx->lsocks);
1223     sctx->lsocks = NULL;
1224     return GNUNET_NO;
1225   }
1226   return GNUNET_YES;
1227 }
1228 #endif
1229
1230
1231 /**
1232  * Setup addr, addrlen, idle_timeout
1233  * based on configuration!
1234  *
1235  * Configuration may specify:
1236  * - PORT (where to bind to for TCP)
1237  * - UNIXPATH (where to bind to for UNIX domain sockets)
1238  * - TIMEOUT (after how many ms does an inactive service timeout);
1239  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1240  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1241  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
1242  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1243  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
1244  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1245  *
1246  * @param sctx
1247  * @return GNUNET_OK if configuration succeeded
1248  */
1249 static int
1250 setup_service (struct GNUNET_SERVICE_Context *sctx)
1251 {
1252   struct GNUNET_TIME_Relative idleout;
1253   int tolerant;
1254
1255 #ifndef MINGW
1256   const char *lpid;
1257   unsigned int pid;
1258   const char *nfds;
1259   unsigned int cnt;
1260   int flags;
1261 #endif
1262
1263   if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, "TIMEOUT"))
1264   {
1265     if (GNUNET_OK !=
1266         GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->serviceName,
1267                                              "TIMEOUT", &idleout))
1268     {
1269       LOG (GNUNET_ERROR_TYPE_ERROR,
1270            _("Specified value for `%s' of service `%s' is invalid\n"),
1271            "TIMEOUT", sctx->serviceName);
1272       return GNUNET_SYSERR;
1273     }
1274     sctx->timeout = idleout;
1275   }
1276   else
1277     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1278
1279   if (GNUNET_CONFIGURATION_have_value
1280       (sctx->cfg, sctx->serviceName, "TOLERANT"))
1281   {
1282     if (GNUNET_SYSERR ==
1283         (tolerant =
1284          GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1285                                                "TOLERANT")))
1286     {
1287       LOG (GNUNET_ERROR_TYPE_ERROR,
1288            _("Specified value for `%s' of service `%s' is invalid\n"),
1289            "TOLERANT", sctx->serviceName);
1290       return GNUNET_SYSERR;
1291     }
1292   }
1293   else
1294     tolerant = GNUNET_NO;
1295
1296 #ifndef MINGW
1297   errno = 0;
1298   if ((NULL != (lpid = getenv ("LISTEN_PID"))) &&
1299       (1 == SSCANF (lpid, "%u", &pid)) && (getpid () == (pid_t) pid) &&
1300       (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1301       (1 == SSCANF (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
1302       (cnt + 4 < FD_SETSIZE))
1303   {
1304     sctx->lsocks =
1305         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
1306     while (0 < cnt--)
1307     {
1308       flags = fcntl (3 + cnt, F_GETFD);
1309       if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1310           (NULL ==
1311            (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1312       {
1313         LOG (GNUNET_ERROR_TYPE_ERROR,
1314              _
1315              ("Could not access pre-bound socket %u, will try to bind myself\n"),
1316              (unsigned int) 3 + cnt);
1317         cnt++;
1318         while (sctx->lsocks[cnt] != NULL)
1319           GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1320         GNUNET_free (sctx->lsocks);
1321         sctx->lsocks = NULL;
1322         break;
1323       }
1324     }
1325     unsetenv ("LISTEN_PID");
1326     unsetenv ("LISTEN_FDS");
1327   }
1328 #else
1329   if (getenv ("GNUNET_OS_READ_LSOCKS") != NULL)
1330   {
1331     receive_sockets_from_parent (sctx);
1332     putenv ("GNUNET_OS_READ_LSOCKS=");
1333   }
1334 #endif
1335
1336   if ((NULL == sctx->lsocks) &&
1337       (GNUNET_SYSERR ==
1338        GNUNET_SERVICE_get_server_addresses (sctx->serviceName, sctx->cfg,
1339                                             &sctx->addrs, &sctx->addrlens)))
1340     return GNUNET_SYSERR;
1341   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1342   sctx->match_uid =
1343       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1344                                             "UNIX_MATCH_UID");
1345   sctx->match_gid =
1346       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1347                                             "UNIX_MATCH_GID");
1348   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1349   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1350   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1351   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1352
1353   return GNUNET_OK;
1354 }
1355
1356
1357 /**
1358  * Get the name of the user that'll be used
1359  * to provide the service.
1360  *
1361  * @param sctx
1362  * @return 
1363  */
1364 static char *
1365 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1366 {
1367   char *un;
1368
1369   if (GNUNET_OK !=
1370       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
1371                                                "USERNAME", &un))
1372     return NULL;
1373   return un;
1374 }
1375
1376 /**
1377  * Write PID file.
1378  *
1379  * @param sctx
1380  * @param pid
1381  * @return 
1382  */
1383 static int
1384 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1385 {
1386   FILE *pidfd;
1387   char *pif;
1388   char *user;
1389   char *rdir;
1390   int len;
1391
1392   if (NULL == (pif = get_pid_file_name (sctx)))
1393     return GNUNET_OK;           /* no file desired */
1394   user = get_user_name (sctx);
1395   rdir = GNUNET_strdup (pif);
1396   len = strlen (rdir);
1397   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1398     len--;
1399   rdir[len] = '\0';
1400   if (0 != ACCESS (rdir, F_OK))
1401   {
1402     /* we get to create a directory -- and claim it
1403      * as ours! */
1404     GNUNET_DISK_directory_create (rdir);
1405     if ((NULL != user) && (0 < strlen (user)))
1406       GNUNET_DISK_file_change_owner (rdir, user);
1407   }
1408   if (0 != ACCESS (rdir, W_OK | X_OK))
1409   {
1410     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1411     GNUNET_free (rdir);
1412     GNUNET_free_non_null (user);
1413     GNUNET_free (pif);
1414     return GNUNET_SYSERR;
1415   }
1416   GNUNET_free (rdir);
1417   pidfd = FOPEN (pif, "w");
1418   if (NULL == pidfd)
1419   {
1420     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1421     GNUNET_free (pif);
1422     GNUNET_free_non_null (user);
1423     return GNUNET_SYSERR;
1424   }
1425   if (0 > FPRINTF (pidfd, "%u", pid))
1426     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1427   GNUNET_break (0 == FCLOSE (pidfd));
1428   if ((NULL != user) && (0 < strlen (user)))
1429     GNUNET_DISK_file_change_owner (pif, user);
1430   GNUNET_free_non_null (user);
1431   GNUNET_free (pif);
1432   return GNUNET_OK;
1433 }
1434
1435
1436 /**
1437  * Task run during shutdown.
1438  *
1439  * @param cls unused
1440  * @param tc unused
1441  */
1442 static void
1443 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1444 {
1445   struct GNUNET_SERVER_Handle *server = cls;
1446
1447   // FIXME: we should not unconditionally destroy the server
1448   // here (often only stopping 'listening' would be better)
1449   GNUNET_SERVER_destroy (server);
1450 }
1451
1452
1453 /**
1454  * Initial task for the service.
1455  *
1456  * @param cls service context
1457  * @param tc unused
1458  */
1459 static void
1460 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1461 {
1462   struct GNUNET_SERVICE_Context *sctx = cls;
1463   unsigned int i;
1464
1465   GNUNET_RESOLVER_connect (sctx->cfg);
1466   if (NULL != sctx->lsocks)
1467     sctx->server =
1468         GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1469                                            sctx->timeout, sctx->require_found);
1470   else
1471     sctx->server =
1472         GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1473                               sctx->timeout, sctx->require_found);
1474   if (NULL == sctx->server)
1475   {
1476     if (NULL != sctx->addrs)
1477     {
1478       i = 0;
1479       while (NULL != sctx->addrs[i])
1480       {
1481         LOG (GNUNET_ERROR_TYPE_INFO, _("Failed to start `%s' at `%s'\n"),
1482              sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1483         i++;
1484       }
1485     }
1486     sctx->ret = GNUNET_SYSERR;
1487     return;
1488   }
1489   if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1490   {
1491     /* install a task that will kill the server
1492      * process if the scheduler ever gets a shutdown signal */
1493     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1494                                   sctx->server);
1495   }
1496   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1497   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1498   i = 0;
1499   while (NULL != sctx->my_handlers[i].callback)
1500     sctx->my_handlers[i++].callback_cls = sctx;
1501   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1502   if (-1 != sctx->ready_confirm_fd)
1503   {
1504     GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1505     GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1506     sctx->ready_confirm_fd = -1;
1507     write_pid_file (sctx, getpid ());
1508   }
1509   if (NULL != sctx->addrs)
1510   {
1511     i = 0;
1512     while (NULL != sctx->addrs[i])
1513     {
1514       LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1515            sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1516       i++;
1517     }
1518   }
1519   sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1520 }
1521
1522
1523 /**
1524  * Detach from terminal.
1525  *
1526  * @param sctx service context
1527  * @return
1528  */
1529 static int
1530 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1531 {
1532 #ifndef MINGW
1533   pid_t pid;
1534   int nullfd;
1535   int filedes[2];
1536
1537   if (0 != PIPE (filedes))
1538   {
1539     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1540     return GNUNET_SYSERR;
1541   }
1542   pid = fork ();
1543   if (pid < 0)
1544   {
1545     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1546     return GNUNET_SYSERR;
1547   }
1548   if (0 != pid)
1549   {
1550     /* Parent */
1551     char c;
1552
1553     GNUNET_break (0 == CLOSE (filedes[1]));
1554     c = 'X';
1555     if (1 != READ (filedes[0], &c, sizeof (char)))
1556       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1557     fflush (stdout);
1558     switch (c)
1559     {
1560     case '.':
1561       exit (0);
1562     case 'I':
1563       LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1564       break;
1565     case 'S':
1566       LOG (GNUNET_ERROR_TYPE_INFO,
1567            _("Service process could not initialize server function\n"));
1568       break;
1569     case 'X':
1570       LOG (GNUNET_ERROR_TYPE_INFO,
1571            _("Service process failed to report status\n"));
1572       break;
1573     }
1574     exit (1);                   /* child reported error */
1575   }
1576   GNUNET_break (0 == CLOSE (0));
1577   GNUNET_break (0 == CLOSE (1));
1578   GNUNET_break (0 == CLOSE (filedes[0]));
1579   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1580   if (nullfd < 0)
1581     return GNUNET_SYSERR;
1582   /* set stdin/stdout to /dev/null */
1583   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1584   {
1585     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1586     (void) CLOSE (nullfd);
1587     return GNUNET_SYSERR;
1588   }
1589   (void) CLOSE (nullfd);
1590   /* Detach from controlling terminal */
1591   pid = setsid ();
1592   if (-1 == pid)
1593     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1594   sctx->ready_confirm_fd = filedes[1];
1595 #else
1596   /* FIXME: we probably need to do something else
1597    * elsewhere in order to fork the process itself... */
1598   FreeConsole ();
1599 #endif
1600   return GNUNET_OK;
1601 }
1602
1603
1604 /**
1605  * Set user ID.
1606  *
1607  * @param sctx service context
1608  * @return
1609  */
1610 static int
1611 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1612 {
1613   char *user;
1614
1615   if (NULL == (user = get_user_name (sctx)))
1616     return GNUNET_OK;           /* keep */
1617 #ifndef MINGW
1618   struct passwd *pws;
1619
1620   errno = 0;
1621   pws = getpwnam (user);
1622   if (NULL == pws)
1623   {
1624     LOG (GNUNET_ERROR_TYPE_ERROR,
1625          _("Cannot obtain information about user `%s': %s\n"), user,
1626          errno == 0 ? _("No such user") : STRERROR (errno));
1627     GNUNET_free (user);
1628     return GNUNET_SYSERR;
1629   }
1630   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1631 #if HAVE_INITGROUPS
1632       (0 != initgroups (user, pws->pw_gid)) ||
1633 #endif
1634       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1635   {
1636     if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1637         (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1638     {
1639       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1640            user, STRERROR (errno));
1641       GNUNET_free (user);
1642       return GNUNET_SYSERR;
1643     }
1644   }
1645 #endif
1646   GNUNET_free (user);
1647   return GNUNET_OK;
1648 }
1649
1650
1651 /**
1652  * Delete the PID file that was created by our parent.
1653  *
1654  * @param sctx service context
1655  */
1656 static void
1657 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1658 {
1659   char *pif = get_pid_file_name (sctx);
1660
1661   if (NULL == pif)
1662     return;                     /* no PID file */
1663   if (0 != UNLINK (pif))
1664     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1665   GNUNET_free (pif);
1666 }
1667
1668
1669 /**
1670  * Run a standard GNUnet service startup sequence (initialize loggers
1671  * and configuration, parse options).
1672  *
1673  * @param argc number of command line arguments
1674  * @param argv command line arguments
1675  * @param serviceName our service name
1676  * @param opt service options
1677  * @param task main task of the service
1678  * @param task_cls closure for task
1679  * @return GNUNET_SYSERR on error, GNUNET_OK
1680  *         if we shutdown nicely
1681  */
1682 int
1683 GNUNET_SERVICE_run (int argc, char *const *argv, const char *serviceName,
1684                     enum GNUNET_SERVICE_Options opt, GNUNET_SERVICE_Main task,
1685                     void *task_cls)
1686 {
1687 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1688
1689   int err;
1690   char *cfg_fn;
1691   char *loglev;
1692   char *logfile;
1693   int do_daemonize;
1694   unsigned int i;
1695   unsigned long long skew_offset;
1696   unsigned long long skew_variance;
1697   long long clock_offset;
1698   struct GNUNET_SERVICE_Context sctx;
1699   struct GNUNET_CONFIGURATION_Handle *cfg;
1700
1701   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1702     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1703     {'d', "daemonize", NULL,
1704      gettext_noop ("do daemonize (detach from terminal)"), 0,
1705      GNUNET_GETOPT_set_one, &do_daemonize},
1706     GNUNET_GETOPT_OPTION_HELP (NULL),
1707     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1708     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1709     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1710     GNUNET_GETOPT_OPTION_END
1711   };
1712   err = 1;
1713   do_daemonize = 0;
1714   logfile = NULL;
1715   loglev = NULL;
1716   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1717   memset (&sctx, 0, sizeof (sctx));
1718   sctx.options = opt;
1719   sctx.ready_confirm_fd = -1;
1720   sctx.ret = GNUNET_OK;
1721   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1722   sctx.task = task;
1723   sctx.task_cls = task_cls;
1724   sctx.serviceName = serviceName;
1725   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1726   /* setup subsystems */
1727   if (GNUNET_SYSERR ==
1728       GNUNET_GETOPT_run (serviceName, service_options, argc, argv))
1729     goto shutdown;
1730   if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1731     HANDLE_ERROR;
1732   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1733     goto shutdown;
1734   if (GNUNET_OK != setup_service (&sctx))
1735     goto shutdown;
1736   if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1737     HANDLE_ERROR;
1738   if (GNUNET_OK != set_user_id (&sctx))
1739     goto shutdown;
1740   LOG (GNUNET_ERROR_TYPE_DEBUG,
1741        "Service `%s' runs with configuration from `%s'\n", serviceName, cfg_fn);
1742   if ((GNUNET_OK ==
1743        GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1744                                               "SKEW_OFFSET", &skew_offset)) &&
1745       (GNUNET_OK ==
1746        GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1747                                               "SKEW_VARIANCE", &skew_variance)))
1748   {
1749     clock_offset = skew_offset - skew_variance;
1750     GNUNET_TIME_set_offset (clock_offset);
1751     LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1752   }
1753   /* actually run service */
1754   err = 0;
1755   GNUNET_SCHEDULER_run (&service_task, &sctx);
1756
1757   /* shutdown */
1758   if ((1 == do_daemonize) && (NULL != sctx.server))
1759     pid_file_delete (&sctx);
1760   GNUNET_free_non_null (sctx.my_handlers);
1761
1762 shutdown:
1763   if (-1 != sctx.ready_confirm_fd)
1764   {
1765     if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1766       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1767     GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1768   }
1769
1770   GNUNET_CONFIGURATION_destroy (cfg);
1771   i = 0;
1772   if (NULL != sctx.addrs)
1773     while (NULL != sctx.addrs[i])
1774       GNUNET_free (sctx.addrs[i++]);
1775   GNUNET_free_non_null (sctx.addrs);
1776   GNUNET_free_non_null (sctx.addrlens);
1777   GNUNET_free_non_null (logfile);
1778   GNUNET_free_non_null (loglev);
1779   GNUNET_free (cfg_fn);
1780   GNUNET_free_non_null (sctx.v4_denied);
1781   GNUNET_free_non_null (sctx.v6_denied);
1782   GNUNET_free_non_null (sctx.v4_allowed);
1783   GNUNET_free_non_null (sctx.v6_allowed);
1784
1785   return err ? GNUNET_SYSERR : sctx.ret;
1786 }
1787
1788
1789 /**
1790  * Run a service startup sequence within an existing
1791  * initialized system.
1792  *
1793  * @param serviceName our service name
1794  * @param cfg configuration to use
1795  * @return NULL on error, service handle
1796  */
1797 struct GNUNET_SERVICE_Context *
1798 GNUNET_SERVICE_start (const char *serviceName,
1799                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1800 {
1801   int i;
1802   struct GNUNET_SERVICE_Context *sctx;
1803
1804   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1805   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1806   sctx->ret = GNUNET_OK;
1807   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1808   sctx->serviceName = serviceName;
1809   sctx->cfg = cfg;
1810
1811   /* setup subsystems */
1812   if (GNUNET_OK != setup_service (sctx))
1813   {
1814     GNUNET_SERVICE_stop (sctx);
1815     return NULL;
1816   }
1817   if (NULL != sctx->lsocks)
1818     sctx->server =
1819         GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1820                                            sctx->timeout, sctx->require_found);
1821   else
1822     sctx->server =
1823         GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1824                               sctx->timeout, sctx->require_found);
1825
1826   if (NULL == sctx->server)
1827   {
1828     GNUNET_SERVICE_stop (sctx);
1829     return NULL;
1830   }
1831   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1832   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1833   i = 0;
1834   while ((sctx->my_handlers[i].callback != NULL))
1835     sctx->my_handlers[i++].callback_cls = sctx;
1836   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1837   return sctx;
1838 }
1839
1840
1841 /**
1842  * Obtain the server used by a service.  Note that the server must NOT
1843  * be destroyed by the caller.
1844  *
1845  * @param ctx the service context returned from the start function
1846  * @return handle to the server for this service, NULL if there is none
1847  */
1848 struct GNUNET_SERVER_Handle *
1849 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1850 {
1851   return ctx->server;
1852 }
1853
1854
1855 /**
1856  * Stop a service that was started with "GNUNET_SERVICE_start".
1857  *
1858  * @param sctx the service context returned from the start function
1859  */
1860 void
1861 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1862 {
1863   unsigned int i;
1864
1865   if (NULL != sctx->server)
1866     GNUNET_SERVER_destroy (sctx->server);
1867   GNUNET_free_non_null (sctx->my_handlers);
1868   if (NULL != sctx->addrs)
1869   {
1870     i = 0;
1871     while (NULL != sctx->addrs[i])
1872       GNUNET_free (sctx->addrs[i++]);
1873     GNUNET_free (sctx->addrs);
1874   }
1875   GNUNET_free_non_null (sctx->addrlens);
1876   GNUNET_free_non_null (sctx->v4_denied);
1877   GNUNET_free_non_null (sctx->v6_denied);
1878   GNUNET_free_non_null (sctx->v4_allowed);
1879   GNUNET_free_non_null (sctx->v6_allowed);
1880   GNUNET_free (sctx);
1881 }
1882
1883
1884 /* end of service.c */