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