stuff
[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 static size_t
574 transmit_shutdown_deny (void *cls, size_t size, void *buf)
575 {
576   struct GNUNET_SERVER_Client *client = cls;
577   struct GNUNET_MessageHeader *msg;
578
579   if (size < sizeof (struct GNUNET_MessageHeader))
580     {
581       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
582       return 0;                 /* client disconnected */
583     }
584   msg = (struct GNUNET_MessageHeader *) buf;
585   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN_REFUSE);
586   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
587   GNUNET_SERVER_receive_done (client, GNUNET_OK);
588   GNUNET_SERVER_client_drop(client);
589   return sizeof (struct GNUNET_MessageHeader);
590 }
591
592 static size_t
593 transmit_shutdown_ack (void *cls, size_t size, void *buf)
594 {
595   struct GNUNET_SERVER_Client *client = cls;
596   struct GNUNET_MessageHeader *msg;
597
598   if (size < sizeof (struct GNUNET_MessageHeader))
599     {
600       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
601                   _("Failed to transmit shutdown ACK.\n"));
602       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
603       return 0;                 /* client disconnected */
604     }
605
606   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
607               _("Transmitting shutdown ACK.\n"));
608
609   msg = (struct GNUNET_MessageHeader *) buf;
610   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN_ACK);
611   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
612   GNUNET_SERVER_receive_done (client, GNUNET_OK);
613   GNUNET_SERVER_client_drop(client);
614   return sizeof (struct GNUNET_MessageHeader);
615 }
616
617 /**
618  * Handler for SHUTDOWN message.
619  *
620  * @param cls closure (refers to service)
621  * @param client identification of the client
622  * @param message the actual message
623  */
624 static void
625 handle_shutdown (void *cls,
626                  struct GNUNET_SERVER_Client *client,
627                  const struct GNUNET_MessageHeader *message)
628 {
629   struct GNUNET_SERVICE_Context *service = cls;
630
631   GNUNET_SERVER_client_keep(client);
632   if (!service->allow_shutdown)
633     {
634       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
635                   _
636                   ("Received shutdown request, but configured to ignore!\n"));
637       GNUNET_SERVER_notify_transmit_ready (client,
638                                            sizeof(struct GNUNET_MessageHeader),
639                                            GNUNET_TIME_UNIT_FOREVER_REL,
640                                            &transmit_shutdown_deny, client);
641       return;
642     }
643   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
644               _("Initiating shutdown as requested by client.\n"));
645
646   GNUNET_SERVER_notify_transmit_ready (client,
647                                        sizeof(struct GNUNET_MessageHeader),
648                                        GNUNET_TIME_UNIT_FOREVER_REL,
649                                        &transmit_shutdown_ack, client);
650
651   GNUNET_assert (service->sched != NULL);
652   GNUNET_SERVER_client_persist_ (client);
653   GNUNET_SCHEDULER_shutdown (service->sched);
654 }
655
656
657 /**
658  * Default handlers for all services.  Will be copied and the
659  * "callback_cls" fields will be replaced with the specific service
660  * struct.
661  */
662 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
663   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
664    sizeof (struct GNUNET_MessageHeader)},
665   {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_SHUTDOWN,
666    sizeof (struct GNUNET_MessageHeader)},
667   {NULL, NULL, 0, 0}
668 };
669
670
671
672 /* ****************** service core routines ************** */
673
674
675 /**
676  * Check if access to the service is allowed from the given address.
677  */
678 static int
679 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
680 {
681   struct GNUNET_SERVICE_Context *sctx = cls;
682   const struct sockaddr_in *i4;
683   const struct sockaddr_in6 *i6;
684   int ret;
685
686   switch (addr->sa_family)
687     {
688     case AF_INET:
689       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
690       i4 = (const struct sockaddr_in *) addr;
691       ret = ((sctx->v4_allowed == NULL) ||
692              (check_ipv4_listed (sctx->v4_allowed,
693                                  &i4->sin_addr)))
694         && ((sctx->v4_denied == NULL) ||
695             (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
696       break;
697     case AF_INET6:
698       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
699       i6 = (const struct sockaddr_in6 *) addr;
700       ret = ((sctx->v6_allowed == NULL) ||
701              (check_ipv6_listed (sctx->v6_allowed,
702                                  &i6->sin6_addr)))
703         && ((sctx->v6_denied == NULL) ||
704             (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
705       break;
706     default:
707       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
708                   _("Unknown address family %d\n"), addr->sa_family);
709       return GNUNET_SYSERR;
710     }
711   if (ret != GNUNET_OK)
712     {
713       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
714                   _("Access from `%s' denied to service `%s'\n"),
715                   GNUNET_a2s (addr, addrlen), sctx->serviceName);
716     }
717   return ret;
718 }
719
720
721 /**
722  * Get the name of the file where we will
723  * write the PID of the service.
724  */
725 static char *
726 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
727 {
728
729   char *pif;
730
731   if (GNUNET_OK !=
732       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
733                                                sctx->serviceName,
734                                                "PIDFILE", &pif))
735     return NULL;
736   return pif;
737 }
738
739
740 /**
741  * Parse an IPv4 access control list.
742  */
743 static int
744 process_acl4 (struct IPv4NetworkSet **ret,
745               struct GNUNET_SERVICE_Context *sctx, const char *option)
746 {
747   char *opt;
748
749   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
750     return GNUNET_OK;
751   GNUNET_break (GNUNET_OK ==
752                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
753                                                        sctx->serviceName,
754                                                        option, &opt));
755   if (NULL == (*ret = parse_ipv4_specification (opt)))
756     {
757       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
758                   _
759                   ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
760                   opt, sctx->serviceName, option);
761       GNUNET_free (opt);
762       return GNUNET_SYSERR;
763     }
764   GNUNET_free (opt);
765   return GNUNET_OK;
766 }
767
768
769 /**
770  * Parse an IPv4 access control list.
771  */
772 static int
773 process_acl6 (struct IPv6NetworkSet **ret,
774               struct GNUNET_SERVICE_Context *sctx, const char *option)
775 {
776   char *opt;
777   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
778     return GNUNET_OK;
779   GNUNET_break (GNUNET_OK ==
780                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
781                                                        sctx->serviceName,
782                                                        option, &opt));
783   if (NULL == (*ret = parse_ipv6_specification (opt)))
784     {
785       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
786                   _
787                   ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
788                   opt, sctx->serviceName, option);
789       GNUNET_free (opt);
790       return GNUNET_SYSERR;
791     }
792   GNUNET_free (opt);
793   return GNUNET_OK;
794 }
795
796
797 /**
798  * Get the list of addresses that a server for the given service
799  * should bind to.
800  *
801  * @param serviceName name of the service
802  * @param cfg configuration (which specifies the addresses)
803  * @param addrs set (call by reference) to an array of pointers to the
804  *              addresses the server should bind to and listen on; the
805  *              array will be NULL-terminated (on success)
806  * @param addr_lens set (call by reference) to an array of the lengths
807  *              of the respective 'struct sockaddr' struct in the 'addrs'
808  *              array (on success)
809  * @return number of addresses found on success,
810  *              GNUNET_SYSERR if the configuration
811  *              did not specify reasonable finding information or
812  *              if it specified a hostname that could not be resolved;
813  *              GNUNET_NO if the number of addresses configured is
814  *              zero (in this case, '*addrs' and '*addr_lens' will be
815  *              set to NULL).
816  */
817 int
818 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
819                                      const struct GNUNET_CONFIGURATION_Handle *cfg,
820                                      struct sockaddr ***addrs,
821                                      socklen_t **addr_lens)
822 {
823   int disablev6;
824   struct GNUNET_NETWORK_Handle *desc;
825   unsigned long long port;
826   struct addrinfo hints;
827   struct addrinfo *res;
828   struct addrinfo *pos;
829   struct addrinfo *next;
830   unsigned int i;
831   int resi;
832   int ret;
833   struct sockaddr **saddrs;
834   socklen_t *saddrlens;
835   char *hostname;
836
837   *addrs = NULL;
838   *addr_lens = NULL;
839   if (GNUNET_CONFIGURATION_have_value (cfg,
840                                        serviceName, "DISABLEV6"))
841     {
842       if (GNUNET_SYSERR ==
843           (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
844                                                              serviceName,
845                                                              "DISABLEV6")))
846         return GNUNET_SYSERR;
847     }
848   else
849     disablev6 = GNUNET_NO;
850
851   if (!disablev6)
852     {
853       /* probe IPv6 support */
854       desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
855       if (NULL == desc)
856         {
857           if ((errno == ENOBUFS) ||
858               (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
859             {
860               GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
861               return GNUNET_SYSERR;
862             }
863           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
864                       _
865                       ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
866                       serviceName, STRERROR (errno));
867           disablev6 = GNUNET_YES;
868         }
869       else
870         {
871           GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
872         }
873     }
874
875
876   if ((GNUNET_OK !=
877        GNUNET_CONFIGURATION_get_value_number (cfg,
878                                               serviceName,
879                                               "PORT",
880                                               &port)) || (port > 65535))
881     {
882       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
883                   _
884                   ("Require valid port number for service `%s' in configuration!\n"),
885                   serviceName);
886       return GNUNET_SYSERR;
887     }
888   if (GNUNET_CONFIGURATION_have_value (cfg,
889                                        serviceName, "BINDTO"))
890     {
891       GNUNET_break (GNUNET_OK ==
892                     GNUNET_CONFIGURATION_get_value_string (cfg,
893                                                            serviceName,
894                                                            "BINDTO",
895                                                            &hostname));
896     }
897   else
898     hostname = NULL;
899
900   if (hostname != NULL)
901     {
902 #if DEBUG_SERVICE
903       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904                   "Resolving `%s' since that is where `%s' will bind to.\n",
905                   hostname,
906                   serviceName);
907 #endif
908       memset (&hints, 0, sizeof (struct addrinfo));
909       if (disablev6)
910         hints.ai_family = AF_INET;
911       if ((0 != (ret = getaddrinfo (hostname,
912                                     NULL, &hints, &res))) || (res == NULL))
913         {
914           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
915                       _("Failed to resolve `%s': %s\n"),
916                       hostname, gai_strerror (ret));
917           GNUNET_free (hostname);
918           return GNUNET_SYSERR;
919         }
920       next = res;
921       i = 0;
922       while (NULL != (pos = next)) 
923         {
924           next = pos->ai_next;
925           if ( (disablev6) && (pos->ai_family == AF_INET6))
926             continue;
927           i++;
928         }
929       if (0 == i)
930         {
931           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
932                       _("Failed to find %saddress for `%s'.\n"),
933                       disablev6 ? "IPv4 " : "", hostname);
934           freeaddrinfo (res);
935           GNUNET_free (hostname);
936           return GNUNET_SYSERR;
937         }
938       resi = i;
939       saddrs = GNUNET_malloc ((i+1) * sizeof(struct sockaddr*));
940       saddrlens = GNUNET_malloc ((i+1) * sizeof (socklen_t));
941       i = 0;
942       next = res;
943       while (NULL != (pos = next)) 
944         {
945           next = pos->ai_next;
946           if ( (disablev6) && (pos->ai_family == AF_INET6))
947             continue;
948 #if DEBUG_SERVICE
949           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950                       "Service `%s' will bind to `%s'\n",
951                       serviceName,
952                       GNUNET_a2s (pos->ai_addr,
953                                   pos->ai_addrlen));
954 #endif
955           if (pos->ai_family == AF_INET)
956             {
957               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
958               saddrlens[i] = pos->ai_addrlen;
959               saddrs[i] = GNUNET_malloc (saddrlens[i]);
960               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
961               ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
962             }
963           else
964             {
965               GNUNET_assert (pos->ai_family == AF_INET6);
966               GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
967               saddrlens[i] = pos->ai_addrlen;
968               saddrs[i] = GNUNET_malloc (saddrlens[i]);
969               memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
970               ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
971             }     
972           i++;
973         }
974       GNUNET_free (hostname);
975       freeaddrinfo (res);
976     }
977   else
978     {
979       /* will bind against everything, just set port */
980       if (disablev6)
981         {
982           /* V4-only */
983           resi = 1;
984           saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
985           saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
986           saddrlens[0] = sizeof (struct sockaddr_in);
987           saddrs[0] = GNUNET_malloc (saddrlens[0]);
988 #if HAVE_SOCKADDR_IN_SIN_LEN
989           ((struct sockaddr_in *) saddrs[0])->sin_len = saddrlens[0];
990 #endif
991           ((struct sockaddr_in *) saddrs[0])->sin_family = AF_INET;
992           ((struct sockaddr_in *) saddrs[0])->sin_port = htons (port);
993         }
994       else
995         {
996           /* dual stack */
997           resi = 2;
998           saddrs = GNUNET_malloc (3 * sizeof(struct sockaddr*));
999           saddrlens = GNUNET_malloc (3 * sizeof (socklen_t));
1000
1001           saddrlens[0] = sizeof (struct sockaddr_in6);
1002           saddrs[0] = GNUNET_malloc (saddrlens[0]);
1003 #if HAVE_SOCKADDR_IN_SIN_LEN
1004           ((struct sockaddr_in6 *) saddrs[0])->sin6_len = saddrlens[0];
1005 #endif
1006           ((struct sockaddr_in6 *) saddrs[0])->sin6_family = AF_INET6;
1007           ((struct sockaddr_in6 *) saddrs[0])->sin6_port = htons (port);
1008
1009           saddrlens[1] = sizeof (struct sockaddr_in);
1010           saddrs[1] = GNUNET_malloc (saddrlens[1]);
1011 #if HAVE_SOCKADDR_IN_SIN_LEN
1012           ((struct sockaddr_in *) saddrs[1])->sin_len = saddrlens[1];
1013 #endif
1014           ((struct sockaddr_in *) saddrs[1])->sin_family = AF_INET;
1015           ((struct sockaddr_in *) saddrs[1])->sin_port = htons (port);
1016         }
1017     }
1018   *addrs = saddrs;
1019   *addr_lens = saddrlens;
1020   return resi;
1021 }
1022
1023
1024 /**
1025  * Setup addr, addrlen, maxbuf, idle_timeout
1026  * based on configuration!
1027  *
1028  * Configuration must specify a "PORT".  It may
1029  * specify:
1030  * - TIMEOUT (after how many ms does an inactive service timeout);
1031  * - MAXBUF (maximum incoming message size supported)
1032  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1033  * - ALLOW_SHUTDOWN (allow clients to shutdown this service)
1034  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1035  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
1036  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1037  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
1038  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1039  *
1040  * @return GNUNET_OK if configuration succeeded
1041  */
1042 static int
1043 setup_service (struct GNUNET_SERVICE_Context *sctx)
1044 {
1045   unsigned long long maxbuf;
1046   struct GNUNET_TIME_Relative idleout;
1047   int tolerant;
1048
1049   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1050                                        sctx->serviceName, "TIMEOUT"))
1051     {
1052       if (GNUNET_OK !=
1053           GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1054                                                sctx->serviceName,
1055                                                "TIMEOUT", &idleout))
1056         {
1057           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1058                       _("Specified value for `%s' of service `%s' is invalid\n"),
1059                       "TIMEOUT",
1060                       sctx->serviceName);
1061           return GNUNET_SYSERR;
1062         }
1063       sctx->timeout = idleout;
1064     }
1065   else
1066     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1067   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1068                                        sctx->serviceName, "MAXBUF"))
1069     {
1070       if (GNUNET_OK !=
1071           GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
1072                                                  sctx->serviceName,
1073                                                  "MAXBUF", &maxbuf))
1074         {
1075           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1076                       _("Specified value for `%s' of service `%s' is invalid\n"),
1077                       "MAXBUF",
1078                       sctx->serviceName);
1079           return GNUNET_SYSERR;
1080         }
1081     }
1082   else
1083     maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1084   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1085                                        sctx->serviceName, "ALLOW_SHUTDOWN"))
1086     {
1087       if (GNUNET_SYSERR ==
1088           (sctx->allow_shutdown =
1089            GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1090                                                  "ALLOW_SHUTDOWN")))
1091         {
1092           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1093                       _("Specified value for `%s' of service `%s' is invalid\n"),
1094                       "ALLOW_SHUTDOWN",
1095                       sctx->serviceName);
1096           return GNUNET_SYSERR;
1097         }
1098     }
1099   else
1100     sctx->allow_shutdown = GNUNET_NO;
1101
1102
1103   if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1104                                        sctx->serviceName, "TOLERANT"))
1105     {
1106       if (GNUNET_SYSERR ==
1107           (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1108                                                             sctx->serviceName,
1109                                                             "TOLERANT")))
1110         {
1111           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1112                       _("Specified value for `%s' of service `%s' is invalid\n"),
1113                       "TOLERANT",
1114                       sctx->serviceName);
1115           return GNUNET_SYSERR;
1116         }
1117     }
1118   else
1119     tolerant = GNUNET_NO;
1120
1121   if (GNUNET_SYSERR ==
1122       GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1123                                            sctx->cfg,
1124                                            &sctx->addrs,
1125                                            &sctx->addrlens))
1126     return GNUNET_SYSERR;
1127   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1128   sctx->maxbuf = (size_t) maxbuf;
1129   if (sctx->maxbuf != maxbuf)
1130     {
1131       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1132                   _
1133                   ("Value in configuration for `%s' and service `%s' too large!\n"),
1134                   "MAXBUF", sctx->serviceName);
1135       return GNUNET_SYSERR;
1136     }
1137
1138   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1139   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1140   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1141   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1142
1143   return GNUNET_OK;
1144 }
1145
1146
1147 /**
1148  * Get the name of the user that'll be used
1149  * to provide the service.
1150  */
1151 static char *
1152 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1153 {
1154
1155   char *un;
1156
1157   if (GNUNET_OK !=
1158       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1159                                                sctx->serviceName,
1160                                                "USERNAME", &un))
1161     return NULL;
1162   return un;
1163 }
1164
1165 /**
1166  * Write PID file.
1167  */
1168 static int
1169 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1170 {
1171   FILE *pidfd;
1172   char *pif;
1173   char *user;
1174   char *rdir;
1175   int len;
1176
1177   if (NULL == (pif = get_pid_file_name (sctx)))
1178     return GNUNET_OK;           /* no file desired */
1179   user = get_user_name (sctx);
1180   rdir = GNUNET_strdup (pif);
1181   len = strlen (rdir);
1182   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1183     len--;
1184   rdir[len] = '\0';
1185   if (0 != ACCESS (rdir, F_OK))
1186     {
1187       /* we get to create a directory -- and claim it
1188          as ours! */
1189       GNUNET_DISK_directory_create (rdir);
1190       if ((user != NULL) && (0 < strlen (user)))
1191         GNUNET_DISK_file_change_owner (rdir, user);
1192     }
1193   if (0 != ACCESS (rdir, W_OK | X_OK))
1194     {
1195       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1196       GNUNET_free (rdir);
1197       GNUNET_free_non_null (user);
1198       GNUNET_free (pif);
1199       return GNUNET_SYSERR;
1200     }
1201   GNUNET_free (rdir);
1202   pidfd = FOPEN (pif, "w");
1203   if (pidfd == NULL)
1204     {
1205       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1206       GNUNET_free (pif);
1207       GNUNET_free_non_null (user);
1208       return GNUNET_SYSERR;
1209     }
1210   if (0 > FPRINTF (pidfd, "%u", pid))
1211     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1212   GNUNET_break (0 == fclose (pidfd));
1213   if ((user != NULL) && (0 < strlen (user)))
1214     GNUNET_DISK_file_change_owner (pif, user);
1215   GNUNET_free_non_null (user);
1216   GNUNET_free (pif);
1217   return GNUNET_OK;
1218 }
1219
1220
1221 /**
1222  * Task run during shutdown.
1223  *
1224  * @param cls unused
1225  * @param tc unused
1226  */
1227 static void
1228 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1229 {
1230   struct GNUNET_SERVER_Handle *server = cls;
1231
1232   GNUNET_SERVER_destroy (server);
1233 }
1234
1235
1236 /**
1237  * Initial task for the service.
1238  */
1239 static void
1240 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1241 {
1242   struct GNUNET_SERVICE_Context *sctx = cls;
1243   unsigned int i;
1244
1245   sctx->sched = tc->sched;
1246   sctx->server = GNUNET_SERVER_create (tc->sched,
1247                                        &check_access,
1248                                        sctx,
1249                                        sctx->addrs,
1250                                        sctx->addrlens,
1251                                        sctx->maxbuf,
1252                                        sctx->timeout, sctx->require_found);
1253   if (sctx->server == NULL)
1254     {
1255       i = 0;
1256       while (sctx->addrs[i] != NULL)
1257         {
1258           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1259                       _("Failed to start `%s' at `%s'\n"),
1260                       sctx->serviceName, 
1261                       GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1262           i++;
1263         }
1264       sctx->ret = GNUNET_SYSERR;
1265       return;
1266     }
1267   if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1268     {
1269       /* install a task that will kill the server
1270          process if the scheduler ever gets a shutdown signal */
1271       GNUNET_SCHEDULER_add_delayed (tc->sched,
1272                                     GNUNET_TIME_UNIT_FOREVER_REL,
1273                                     &shutdown_task, sctx->server);
1274     }
1275   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1276   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1277   i = 0;
1278   while ((sctx->my_handlers[i].callback != NULL))
1279     sctx->my_handlers[i++].callback_cls = sctx;
1280   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1281   if (sctx->ready_confirm_fd != -1)
1282     {
1283       GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1284       GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1285       sctx->ready_confirm_fd = -1;
1286       write_pid_file (sctx, getpid ());
1287     }
1288   i = 0;
1289   while (sctx->addrs[i] != NULL)
1290     {
1291       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1292                   _("Service `%s' runs at %s\n"),
1293                   sctx->serviceName, 
1294                   GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1295       i++;
1296     }
1297   sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1298 }
1299
1300
1301 /**
1302  * Detach from terminal.
1303  */
1304 static int
1305 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1306 {
1307 #ifndef MINGW
1308   pid_t pid;
1309   int nullfd;
1310   int filedes[2];
1311
1312   if (0 != PIPE (filedes))
1313     {
1314       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1315       return GNUNET_SYSERR;
1316     }
1317   pid = fork ();
1318   if (pid < 0)
1319     {
1320       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1321       return GNUNET_SYSERR;
1322     }
1323   if (pid != 0)
1324     {
1325       /* Parent */
1326       char c;
1327
1328       GNUNET_break (0 == CLOSE (filedes[1]));
1329       c = 'X';
1330       if (1 != READ (filedes[0], &c, sizeof (char)))
1331         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1332       fflush (stdout);
1333       switch (c)
1334         {
1335         case '.':
1336           exit (0);
1337         case 'I':
1338           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1339                       _("Service process failed to initialize\n"));
1340           break;
1341         case 'S':
1342           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1343                       _
1344                       ("Service process could not initialize server function\n"));
1345           break;
1346         case 'X':
1347           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1348                       _("Service process failed to report status\n"));
1349           break;
1350         }
1351       exit (1);                 /* child reported error */
1352     }
1353   GNUNET_break (0 == CLOSE (0));
1354   GNUNET_break (0 == CLOSE (1));
1355   GNUNET_break (0 == CLOSE (filedes[0]));
1356   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1357   if (nullfd < 0)
1358     return GNUNET_SYSERR;
1359   /* set stdin/stdout to /dev/null */
1360   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1361     {
1362       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1363       return GNUNET_SYSERR;
1364     }
1365   /* Detach from controlling terminal */
1366   pid = setsid ();
1367   if (pid == -1)
1368     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1369   sctx->ready_confirm_fd = filedes[1];
1370 #else
1371   /* FIXME: we probably need to do something else
1372      elsewhere in order to fork the process itself... */
1373   FreeConsole ();
1374 #endif
1375   return GNUNET_OK;
1376 }
1377
1378
1379 /**
1380  * Set user ID.
1381  */
1382 static int
1383 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1384 {
1385   char *user;
1386
1387   if (NULL == (user = get_user_name (sctx)))
1388     return GNUNET_OK;           /* keep */
1389 #ifndef MINGW
1390   struct passwd *pws;
1391
1392   errno = 0;
1393   pws = getpwnam (user);
1394   if (pws == NULL)
1395     {
1396       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1397                   _("Cannot obtain information about user `%s': %s\n"),
1398                   user, errno == 0 ? _("No such user") : STRERROR (errno));
1399       GNUNET_free (user);
1400       return GNUNET_SYSERR;
1401     }
1402   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1403 #if HAVE_INITGROUPS
1404       (0 != initgroups (user, pws->pw_gid)) ||
1405 #endif
1406       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1407     {
1408       if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1409           (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1410         {
1411           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1412                       _("Cannot change user/group to `%s': %s\n"), user,
1413                       STRERROR (errno));
1414           GNUNET_free (user);
1415           return GNUNET_SYSERR;
1416         }
1417     }
1418 #endif
1419   GNUNET_free (user);
1420   return GNUNET_OK;
1421 }
1422
1423
1424 /**
1425  * Delete the PID file that was created by our parent.
1426  */
1427 static void
1428 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1429 {
1430   char *pif = get_pid_file_name (sctx);
1431   if (pif == NULL)
1432     return;                     /* no PID file */
1433   if (0 != UNLINK (pif))
1434     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1435   GNUNET_free (pif);
1436 }
1437
1438
1439 /**
1440  * Run a standard GNUnet service startup sequence (initialize loggers
1441  * and configuration, parse options).
1442  *
1443  * @param argc number of command line arguments
1444  * @param argv command line arguments
1445  * @param serviceName our service name
1446  * @param opt service options
1447  * @param task main task of the service
1448  * @param task_cls closure for task
1449  * @return GNUNET_SYSERR on error, GNUNET_OK
1450  *         if we shutdown nicely
1451  */
1452 int
1453 GNUNET_SERVICE_run (int argc,
1454                     char *const *argv,
1455                     const char *serviceName,
1456                     enum GNUNET_SERVICE_Options opt,
1457                     GNUNET_SERVICE_Main task, void *task_cls)
1458 {
1459 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1460
1461   int err;
1462   char *cfg_fn;
1463   char *loglev;
1464   char *logfile;
1465   int do_daemonize;
1466   unsigned int i;
1467   struct GNUNET_SERVICE_Context sctx;
1468   struct GNUNET_CONFIGURATION_Handle *cfg;
1469   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1470     GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1471     {'d', "daemonize", NULL,
1472      gettext_noop ("do daemonize (detach from terminal)"), 0,
1473      GNUNET_GETOPT_set_one, &do_daemonize},
1474     GNUNET_GETOPT_OPTION_HELP (serviceName),
1475     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1476     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1477     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1478     GNUNET_GETOPT_OPTION_END
1479   };
1480   err = 0;
1481   do_daemonize = 0;
1482   logfile = NULL;
1483   loglev = GNUNET_strdup ("WARNING");
1484   cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1485   memset (&sctx, 0, sizeof (sctx));
1486   sctx.options = opt;
1487   sctx.ready_confirm_fd = -1;
1488   sctx.ret = GNUNET_OK;
1489   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1490   sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1491   sctx.task = task;
1492   sctx.serviceName = serviceName;
1493   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1494   /* setup subsystems */
1495   if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1496       argv))    
1497     goto shutdown;
1498   if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1499     HANDLE_ERROR;
1500   if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1501     goto shutdown;
1502   if (GNUNET_OK != setup_service (&sctx))
1503     goto shutdown;
1504   if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))    
1505     HANDLE_ERROR;
1506   if (GNUNET_OK != set_user_id (&sctx))
1507     goto shutdown;
1508 #if DEBUG_SERVICE
1509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1510               "Service `%s' runs with configuration from `%s'\n",
1511               serviceName, cfg_fn);
1512 #endif
1513   /* actually run service */
1514   GNUNET_SCHEDULER_run (&service_task, &sctx);
1515
1516   /* shutdown */
1517   if ((do_daemonize == 1) && (sctx.server != NULL))
1518     pid_file_delete (&sctx);
1519   GNUNET_free_non_null (sctx.my_handlers);
1520
1521 shutdown:
1522   if (sctx.ready_confirm_fd != -1)
1523     {
1524       if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1525         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1526       GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1527     }
1528
1529   GNUNET_CONFIGURATION_destroy (cfg);
1530   i = 0;
1531   if (sctx.addrs != NULL)
1532     while (sctx.addrs[i] != NULL)    
1533       GNUNET_free (sctx.addrs[i++]);    
1534   GNUNET_free_non_null (sctx.addrs);
1535   GNUNET_free_non_null (sctx.addrlens);
1536   GNUNET_free_non_null (logfile);
1537   GNUNET_free (loglev);
1538   GNUNET_free (cfg_fn);
1539   GNUNET_free_non_null (sctx.v4_denied);
1540   GNUNET_free_non_null (sctx.v6_denied);
1541   GNUNET_free_non_null (sctx.v4_allowed);
1542   GNUNET_free_non_null (sctx.v6_allowed);
1543
1544   return err ? GNUNET_SYSERR : sctx.ret;
1545 }
1546
1547
1548 /**
1549  * Run a service startup sequence within an existing
1550  * initialized system.
1551  *
1552  * @param serviceName our service name
1553  * @param sched scheduler to use
1554  * @param cfg configuration to use
1555  * @return NULL on error, service handle
1556  */
1557 struct GNUNET_SERVICE_Context *
1558 GNUNET_SERVICE_start (const char *serviceName,
1559                       struct GNUNET_SCHEDULER_Handle *sched,
1560                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1561 {
1562   int i;
1563   struct GNUNET_SERVICE_Context *sctx;
1564
1565   sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1566   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1567   sctx->ret = GNUNET_OK;
1568   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1569   sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1570   sctx->serviceName = serviceName;
1571   sctx->cfg = cfg;
1572   sctx->sched = sched;
1573
1574   /* setup subsystems */
1575   if ((GNUNET_OK != setup_service (sctx)) ||
1576       (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1577                                                      &check_access,
1578                                                      sctx,
1579                                                      sctx->addrs,
1580                                                      sctx->addrlens,
1581                                                      sctx->maxbuf,
1582                                                      sctx->timeout,
1583                                                      sctx->require_found))))
1584     {
1585       GNUNET_SERVICE_stop (sctx);
1586       return NULL;
1587     }
1588   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1589   memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1590   i = 0;
1591   while ((sctx->my_handlers[i].callback != NULL))
1592     sctx->my_handlers[i++].callback_cls = sctx;
1593   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1594   return sctx;
1595 }
1596
1597 /**
1598  * Obtain the server used by a service.  Note that the server must NOT
1599  * be destroyed by the caller.
1600  *
1601  * @param ctx the service context returned from the start function
1602  * @return handle to the server for this service, NULL if there is none
1603  */
1604 struct GNUNET_SERVER_Handle *
1605 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1606 {
1607   return ctx->server;
1608 }
1609
1610
1611 /**
1612  * Stop a service that was started with "GNUNET_SERVICE_start".
1613  *
1614  * @param sctx the service context returned from the start function
1615  */
1616 void
1617 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1618 {
1619   unsigned int i;
1620   if (NULL != sctx->server)
1621     GNUNET_SERVER_destroy (sctx->server);
1622   GNUNET_free_non_null (sctx->my_handlers);
1623   i = 0;
1624   while (sctx->addrs[i] != NULL)    
1625     GNUNET_free (sctx->addrs[i++]);    
1626   GNUNET_free_non_null (sctx->addrs);
1627   GNUNET_free_non_null (sctx->addrlens);
1628   GNUNET_free_non_null (sctx->v4_denied);
1629   GNUNET_free_non_null (sctx->v6_denied);
1630   GNUNET_free_non_null (sctx->v4_allowed);
1631   GNUNET_free_non_null (sctx->v6_allowed);
1632   GNUNET_free (sctx);
1633 }
1634
1635
1636 /* end of service.c */