use putenv instead of setenv for portability
[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 /**
1083  * Setup addr, addrlen, idle_timeout
1084  * based on configuration!
1085  *
1086  * Configuration may specify:
1087  * - PORT (where to bind to for TCP)
1088  * - UNIXPATH (where to bind to for UNIX domain sockets)
1089  * - TIMEOUT (after how many ms does an inactive service timeout);
1090  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1091  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1092  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
1093  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1094  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
1095  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1096  *
1097  * @return GNUNET_OK if configuration succeeded
1098  */
1099 static int
1100 setup_service (struct GNUNET_SERVICE_Context *sctx)
1101 {
1102   struct GNUNET_TIME_Relative idleout;
1103   int tolerant;
1104
1105 #ifndef MINGW
1106   const char *lpid;
1107   unsigned int pid;
1108   const char *nfds;
1109   unsigned int cnt;
1110   int flags;
1111 #endif
1112
1113   if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, "TIMEOUT"))
1114   {
1115     if (GNUNET_OK !=
1116         GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->serviceName,
1117                                              "TIMEOUT", &idleout))
1118     {
1119       LOG (GNUNET_ERROR_TYPE_ERROR,
1120            _("Specified value for `%s' of service `%s' is invalid\n"),
1121            "TIMEOUT", sctx->serviceName);
1122       return GNUNET_SYSERR;
1123     }
1124     sctx->timeout = idleout;
1125   }
1126   else
1127     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1128
1129   if (GNUNET_CONFIGURATION_have_value
1130       (sctx->cfg, sctx->serviceName, "TOLERANT"))
1131   {
1132     if (GNUNET_SYSERR ==
1133         (tolerant =
1134          GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1135                                                "TOLERANT")))
1136     {
1137       LOG (GNUNET_ERROR_TYPE_ERROR,
1138            _("Specified value for `%s' of service `%s' is invalid\n"),
1139            "TOLERANT", sctx->serviceName);
1140       return GNUNET_SYSERR;
1141     }
1142   }
1143   else
1144     tolerant = GNUNET_NO;
1145
1146 #ifndef MINGW
1147   errno = 0;
1148   if ((NULL != (lpid = getenv ("LISTEN_PID"))) &&
1149       (1 == sscanf (lpid, "%u", &pid)) && (getpid () == (pid_t) pid) &&
1150       (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1151       (1 == sscanf (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
1152       (cnt + 4 < FD_SETSIZE))
1153   {
1154     sctx->lsocks =
1155         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
1156     while (0 < cnt--)
1157     {
1158       flags = fcntl (3 + cnt, F_GETFD);
1159       if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1160           (NULL ==
1161            (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1162       {
1163         LOG (GNUNET_ERROR_TYPE_ERROR,
1164              _
1165              ("Could not access pre-bound socket %u, will try to bind myself\n"),
1166              (unsigned int) 3 + cnt);
1167         cnt++;
1168         while (sctx->lsocks[cnt] != NULL)
1169           GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1170         GNUNET_free (sctx->lsocks);
1171         sctx->lsocks = NULL;
1172         break;
1173       }
1174     }
1175     unsetenv ("LISTEN_PID");
1176     unsetenv ("LISTEN_FDS");
1177   }
1178 #endif
1179
1180   if ((sctx->lsocks == NULL) &&
1181       (GNUNET_SYSERR ==
1182        GNUNET_SERVICE_get_server_addresses (sctx->serviceName, sctx->cfg,
1183                                             &sctx->addrs, &sctx->addrlens)))
1184     return GNUNET_SYSERR;
1185   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1186   sctx->match_uid =
1187       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1188                                             "UNIX_MATCH_UID");
1189   sctx->match_gid =
1190       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1191                                             "UNIX_MATCH_GID");
1192   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1193   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1194   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1195   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1196
1197   return GNUNET_OK;
1198 }
1199
1200
1201 /**
1202  * Get the name of the user that'll be used
1203  * to provide the service.
1204  */
1205 static char *
1206 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1207 {
1208
1209   char *un;
1210
1211   if (GNUNET_OK !=
1212       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
1213                                                "USERNAME", &un))
1214     return NULL;
1215   return un;
1216 }
1217
1218 /**
1219  * Write PID file.
1220  */
1221 static int
1222 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1223 {
1224   FILE *pidfd;
1225   char *pif;
1226   char *user;
1227   char *rdir;
1228   int len;
1229
1230   if (NULL == (pif = get_pid_file_name (sctx)))
1231     return GNUNET_OK;           /* no file desired */
1232   user = get_user_name (sctx);
1233   rdir = GNUNET_strdup (pif);
1234   len = strlen (rdir);
1235   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1236     len--;
1237   rdir[len] = '\0';
1238   if (0 != ACCESS (rdir, F_OK))
1239   {
1240     /* we get to create a directory -- and claim it
1241      * as ours! */
1242     GNUNET_DISK_directory_create (rdir);
1243     if ((user != NULL) && (0 < strlen (user)))
1244       GNUNET_DISK_file_change_owner (rdir, user);
1245   }
1246   if (0 != ACCESS (rdir, W_OK | X_OK))
1247   {
1248     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1249     GNUNET_free (rdir);
1250     GNUNET_free_non_null (user);
1251     GNUNET_free (pif);
1252     return GNUNET_SYSERR;
1253   }
1254   GNUNET_free (rdir);
1255   pidfd = FOPEN (pif, "w");
1256   if (pidfd == NULL)
1257   {
1258     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1259     GNUNET_free (pif);
1260     GNUNET_free_non_null (user);
1261     return GNUNET_SYSERR;
1262   }
1263   if (0 > FPRINTF (pidfd, "%u", pid))
1264     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1265   GNUNET_break (0 == fclose (pidfd));
1266   if ((user != NULL) && (0 < strlen (user)))
1267     GNUNET_DISK_file_change_owner (pif, user);
1268   GNUNET_free_non_null (user);
1269   GNUNET_free (pif);
1270   return GNUNET_OK;
1271 }
1272
1273
1274 /**
1275  * Task run during shutdown.
1276  *
1277  * @param cls unused
1278  * @param tc unused
1279  */
1280 static void
1281 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1282 {
1283   struct GNUNET_SERVER_Handle *server = cls;
1284
1285   GNUNET_SERVER_destroy (server);
1286 }
1287
1288
1289 /**
1290  * Initial task for the service.
1291  */
1292 static void
1293 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1294 {
1295   struct GNUNET_SERVICE_Context *sctx = cls;
1296   unsigned int i;
1297
1298   GNUNET_RESOLVER_connect (sctx->cfg);
1299   if (sctx->lsocks != NULL)
1300     sctx->server =
1301         GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1302                                            sctx->timeout, sctx->require_found);
1303   else
1304     sctx->server =
1305         GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1306                               sctx->timeout, sctx->require_found);
1307   if (sctx->server == NULL)
1308   {
1309     if (sctx->addrs != NULL)
1310     {
1311       i = 0;
1312       while (sctx->addrs[i] != NULL)
1313       {
1314         LOG (GNUNET_ERROR_TYPE_INFO, _("Failed to start `%s' at `%s'\n"),
1315              sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1316         i++;
1317       }
1318     }
1319     sctx->ret = GNUNET_SYSERR;
1320     return;
1321   }
1322   if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1323   {
1324     /* install a task that will kill the server
1325      * process if the scheduler ever gets a shutdown signal */
1326     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1327                                   sctx->server);
1328   }
1329   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1330   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1331   i = 0;
1332   while ((sctx->my_handlers[i].callback != NULL))
1333     sctx->my_handlers[i++].callback_cls = sctx;
1334   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1335   if (sctx->ready_confirm_fd != -1)
1336   {
1337     GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1338     GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1339     sctx->ready_confirm_fd = -1;
1340     write_pid_file (sctx, getpid ());
1341   }
1342   if (sctx->addrs != NULL)
1343   {
1344     i = 0;
1345     while (sctx->addrs[i] != NULL)
1346     {
1347       LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1348            sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1349       i++;
1350     }
1351   }
1352   sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1353 }
1354
1355
1356 /**
1357  * Detach from terminal.
1358  */
1359 static int
1360 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1361 {
1362 #ifndef MINGW
1363   pid_t pid;
1364   int nullfd;
1365   int filedes[2];
1366
1367   if (0 != PIPE (filedes))
1368   {
1369     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1370     return GNUNET_SYSERR;
1371   }
1372   pid = fork ();
1373   if (pid < 0)
1374   {
1375     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1376     return GNUNET_SYSERR;
1377   }
1378   if (pid != 0)
1379   {
1380     /* Parent */
1381     char c;
1382
1383     GNUNET_break (0 == CLOSE (filedes[1]));
1384     c = 'X';
1385     if (1 != READ (filedes[0], &c, sizeof (char)))
1386       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1387     fflush (stdout);
1388     switch (c)
1389     {
1390     case '.':
1391       exit (0);
1392     case 'I':
1393       LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1394       break;
1395     case 'S':
1396       LOG (GNUNET_ERROR_TYPE_INFO,
1397            _("Service process could not initialize server function\n"));
1398       break;
1399     case 'X':
1400       LOG (GNUNET_ERROR_TYPE_INFO,
1401            _("Service process failed to report status\n"));
1402       break;
1403     }
1404     exit (1);                   /* child reported error */
1405   }
1406   GNUNET_break (0 == CLOSE (0));
1407   GNUNET_break (0 == CLOSE (1));
1408   GNUNET_break (0 == CLOSE (filedes[0]));
1409   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1410   if (nullfd < 0)
1411     return GNUNET_SYSERR;
1412   /* set stdin/stdout to /dev/null */
1413   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1414   {
1415     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1416     (void) CLOSE (nullfd);
1417     return GNUNET_SYSERR;
1418   }
1419   (void) CLOSE (nullfd);
1420   /* Detach from controlling terminal */
1421   pid = setsid ();
1422   if (pid == -1)
1423     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1424   sctx->ready_confirm_fd = filedes[1];
1425 #else
1426   /* FIXME: we probably need to do something else
1427    * elsewhere in order to fork the process itself... */
1428   FreeConsole ();
1429 #endif
1430   return GNUNET_OK;
1431 }
1432
1433
1434 /**
1435  * Set user ID.
1436  */
1437 static int
1438 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1439 {
1440   char *user;
1441
1442   if (NULL == (user = get_user_name (sctx)))
1443     return GNUNET_OK;           /* keep */
1444 #ifndef MINGW
1445   struct passwd *pws;
1446
1447   errno = 0;
1448   pws = getpwnam (user);
1449   if (pws == NULL)
1450   {
1451     LOG (GNUNET_ERROR_TYPE_ERROR,
1452          _("Cannot obtain information about user `%s': %s\n"), user,
1453          errno == 0 ? _("No such user") : STRERROR (errno));
1454     GNUNET_free (user);
1455     return GNUNET_SYSERR;
1456   }
1457   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1458 #if HAVE_INITGROUPS
1459       (0 != initgroups (user, pws->pw_gid)) ||
1460 #endif
1461       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1462   {
1463     if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1464         (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1465     {
1466       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1467            user, STRERROR (errno));
1468       GNUNET_free (user);
1469       return GNUNET_SYSERR;
1470     }
1471   }
1472 #endif
1473   GNUNET_free (user);
1474   return GNUNET_OK;
1475 }
1476
1477
1478 /**
1479  * Delete the PID file that was created by our parent.
1480  */
1481 static void
1482 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1483 {
1484   char *pif = get_pid_file_name (sctx);
1485
1486   if (pif == NULL)
1487     return;                     /* no PID file */
1488   if (0 != UNLINK (pif))
1489     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1490   GNUNET_free (pif);
1491 }
1492
1493
1494 /**
1495  * Run a standard GNUnet service startup sequence (initialize loggers
1496  * and configuration, parse options).
1497  *
1498  * @param argc number of command line arguments
1499  * @param argv command line arguments
1500  * @param serviceName our service name
1501  * @param opt service options
1502  * @param task main task of the service
1503  * @param task_cls closure for task
1504  * @return GNUNET_SYSERR on error, GNUNET_OK
1505  *         if we shutdown nicely
1506  */
1507 int
1508 GNUNET_SERVICE_run (int argc, char *const *argv, const char *serviceName,
1509                     enum GNUNET_SERVICE_Options opt, GNUNET_SERVICE_Main task,
1510                     void *task_cls)
1511 {
1512 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1513
1514   int err;
1515   char *cfg_fn;
1516   char *loglev;
1517   char *logfile;
1518   int do_daemonize;
1519   unsigned int i;
1520   unsigned long long skew_offset;
1521   unsigned long long skew_variance;
1522   long long clock_offset;
1523   struct GNUNET_SERVICE_Context sctx;
1524   struct GNUNET_CONFIGURATION_Handle *cfg;
1525
1526   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1527     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1528     {'d', "daemonize", NULL,
1529      gettext_noop ("do daemonize (detach from terminal)"), 0,
1530      GNUNET_GETOPT_set_one, &do_daemonize},
1531     GNUNET_GETOPT_OPTION_HELP (serviceName),
1532     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1533     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1534     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1535     GNUNET_GETOPT_OPTION_END
1536   };
1537   err = 1;
1538   do_daemonize = 0;
1539   logfile = NULL;
1540   loglev = NULL;
1541   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1542   memset (&sctx, 0, sizeof (sctx));
1543   sctx.options = opt;
1544   sctx.ready_confirm_fd = -1;
1545   sctx.ret = GNUNET_OK;
1546   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1547   sctx.task = task;
1548   sctx.task_cls = task_cls;
1549   sctx.serviceName = serviceName;
1550   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1551   /* setup subsystems */
1552   if (GNUNET_SYSERR ==
1553       GNUNET_GETOPT_run (serviceName, service_options, argc, argv))
1554     goto shutdown;
1555   if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1556     HANDLE_ERROR;
1557   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1558     goto shutdown;
1559   if (GNUNET_OK != setup_service (&sctx))
1560     goto shutdown;
1561   if ((do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1562     HANDLE_ERROR;
1563   if (GNUNET_OK != set_user_id (&sctx))
1564     goto shutdown;
1565 #if DEBUG_SERVICE
1566   LOG (GNUNET_ERROR_TYPE_DEBUG,
1567        "Service `%s' runs with configuration from `%s'\n", serviceName, cfg_fn);
1568 #endif
1569   if (GNUNET_OK ==
1570       GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing", "skew_offset",
1571                                              &skew_offset) &&
1572       (GNUNET_OK ==
1573        GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing",
1574                                               "skew_variance", &skew_variance)))
1575   {
1576     clock_offset = skew_offset - skew_variance;
1577     GNUNET_TIME_set_offset (clock_offset);
1578 #if DEBUG_SERVICE
1579     LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll\n", clock_offset);
1580 #endif
1581   }
1582   /* actually run service */
1583   err = 0;
1584   GNUNET_SCHEDULER_run (&service_task, &sctx);
1585
1586   /* shutdown */
1587   if ((do_daemonize == 1) && (sctx.server != NULL))
1588     pid_file_delete (&sctx);
1589   GNUNET_free_non_null (sctx.my_handlers);
1590
1591 shutdown:
1592   if (sctx.ready_confirm_fd != -1)
1593   {
1594     if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1595       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1596     GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1597   }
1598
1599   GNUNET_CONFIGURATION_destroy (cfg);
1600   i = 0;
1601   if (sctx.addrs != NULL)
1602     while (sctx.addrs[i] != NULL)
1603       GNUNET_free (sctx.addrs[i++]);
1604   GNUNET_free_non_null (sctx.addrs);
1605   GNUNET_free_non_null (sctx.addrlens);
1606   GNUNET_free_non_null (logfile);
1607   GNUNET_free_non_null (loglev);
1608   GNUNET_free (cfg_fn);
1609   GNUNET_free_non_null (sctx.v4_denied);
1610   GNUNET_free_non_null (sctx.v6_denied);
1611   GNUNET_free_non_null (sctx.v4_allowed);
1612   GNUNET_free_non_null (sctx.v6_allowed);
1613
1614   return err ? GNUNET_SYSERR : sctx.ret;
1615 }
1616
1617
1618 /**
1619  * Run a service startup sequence within an existing
1620  * initialized system.
1621  *
1622  * @param serviceName our service name
1623  * @param cfg configuration to use
1624  * @return NULL on error, service handle
1625  */
1626 struct GNUNET_SERVICE_Context *
1627 GNUNET_SERVICE_start (const char *serviceName,
1628                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1629 {
1630   int i;
1631   struct GNUNET_SERVICE_Context *sctx;
1632
1633   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1634   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1635   sctx->ret = GNUNET_OK;
1636   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1637   sctx->serviceName = serviceName;
1638   sctx->cfg = cfg;
1639
1640   /* setup subsystems */
1641   if (GNUNET_OK != setup_service (sctx))
1642   {
1643     GNUNET_SERVICE_stop (sctx);
1644     return NULL;
1645   }
1646   if (sctx->lsocks != NULL)
1647     sctx->server =
1648         GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1649                                            sctx->timeout, sctx->require_found);
1650   else
1651     sctx->server =
1652         GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1653                               sctx->timeout, sctx->require_found);
1654
1655   if (NULL == sctx->server)
1656   {
1657     GNUNET_SERVICE_stop (sctx);
1658     return NULL;
1659   }
1660   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1661   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1662   i = 0;
1663   while ((sctx->my_handlers[i].callback != NULL))
1664     sctx->my_handlers[i++].callback_cls = sctx;
1665   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1666   return sctx;
1667 }
1668
1669 /**
1670  * Obtain the server used by a service.  Note that the server must NOT
1671  * be destroyed by the caller.
1672  *
1673  * @param ctx the service context returned from the start function
1674  * @return handle to the server for this service, NULL if there is none
1675  */
1676 struct GNUNET_SERVER_Handle *
1677 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1678 {
1679   return ctx->server;
1680 }
1681
1682
1683 /**
1684  * Stop a service that was started with "GNUNET_SERVICE_start".
1685  *
1686  * @param sctx the service context returned from the start function
1687  */
1688 void
1689 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1690 {
1691   unsigned int i;
1692
1693   if (NULL != sctx->server)
1694     GNUNET_SERVER_destroy (sctx->server);
1695   GNUNET_free_non_null (sctx->my_handlers);
1696   if (sctx->addrs != NULL)
1697   {
1698     i = 0;
1699     while (sctx->addrs[i] != NULL)
1700       GNUNET_free (sctx->addrs[i++]);
1701     GNUNET_free (sctx->addrs);
1702   }
1703   GNUNET_free_non_null (sctx->addrlens);
1704   GNUNET_free_non_null (sctx->v4_denied);
1705   GNUNET_free_non_null (sctx->v6_denied);
1706   GNUNET_free_non_null (sctx->v4_allowed);
1707   GNUNET_free_non_null (sctx->v6_allowed);
1708   GNUNET_free (sctx);
1709 }
1710
1711
1712 /* end of service.c */