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