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