use NULL as flag for evaluation of query, ensure we pass non-NULL for reply_block...
[oweals/gnunet.git] / src / util / service_new.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2016 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/service_new.c
23  * @brief functions related to starting services (redesign)
24  * @author Christian Grothoff
25  * @author Florian Dold
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_resolver_service.h"
32 #include "speedup.h"
33
34 #if HAVE_MALLINFO
35 #include <malloc.h>
36 #include "gauger.h"
37 #endif
38
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45
46
47 /**
48  * Information the service tracks per listen operation.
49  */
50 struct ServiceListenContext
51 {
52
53   /**
54    * Kept in a DLL.
55    */
56   struct ServiceListenContext *next;
57
58   /**
59    * Kept in a DLL.
60    */
61   struct ServiceListenContext *prev;
62
63   /**
64    * Service this listen context belongs to.
65    */
66   struct GNUNET_SERVICE_Handle *sh;
67
68   /**
69    * Socket we are listening on.
70    */
71   struct GNUNET_NETWORK_Handle *listen_socket;
72
73   /**
74    * Task scheduled to do the listening.
75    */
76   struct GNUNET_SCHEDULER_Task *listen_task;
77
78 };
79
80
81 /**
82  * Handle to a service.
83  */
84 struct GNUNET_SERVICE_Handle
85 {
86   /**
87    * Our configuration.
88    */
89   const struct GNUNET_CONFIGURATION_Handle *cfg;
90
91   /**
92    * Name of our service.
93    */
94   const char *service_name;
95
96   /**
97    * Main service-specific task to run.
98    */
99   GNUNET_SERVICE_InitCallback service_init_cb;
100
101   /**
102    * Function to call when clients connect.
103    */
104   GNUNET_SERVICE_ConnectHandler connect_cb;
105
106   /**
107    * Function to call when clients disconnect / are disconnected.
108    */
109   GNUNET_SERVICE_DisconnectHandler disconnect_cb;
110
111   /**
112    * Closure for @e service_init_cb, @e connect_cb, @e disconnect_cb.
113    */
114   void *cb_cls;
115
116   /**
117    * DLL of listen sockets used to accept new connections.
118    */
119   struct ServiceListenContext *slc_head;
120
121   /**
122    * DLL of listen sockets used to accept new connections.
123    */
124   struct ServiceListenContext *slc_tail;
125
126   /**
127    * Our clients, kept in a DLL.
128    */
129   struct GNUNET_SERVICE_Client *clients_head;
130
131   /**
132    * Our clients, kept in a DLL.
133    */
134   struct GNUNET_SERVICE_Client *clients_tail;
135
136   /**
137    * Message handlers to use for all clients.
138    */
139   struct GNUNET_MQ_MessageHandler *handlers;
140
141   /**
142    * Closure for @e task.
143    */
144   void *task_cls;
145
146   /**
147    * IPv4 addresses that are not allowed to connect.
148    */
149   struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
150
151   /**
152    * IPv6 addresses that are not allowed to connect.
153    */
154   struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
155
156   /**
157    * IPv4 addresses that are allowed to connect (if not
158    * set, all are allowed).
159    */
160   struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
161
162   /**
163    * IPv6 addresses that are allowed to connect (if not
164    * set, all are allowed).
165    */
166   struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
167
168   /**
169    * Do we require a matching UID for UNIX domain socket connections?
170    * #GNUNET_NO means that the UID does not have to match (however,
171    * @e match_gid may still impose other access control checks).
172    */
173   int match_uid;
174
175   /**
176    * Do we require a matching GID for UNIX domain socket connections?
177    * Ignored if @e match_uid is #GNUNET_YES.  Note that this is about
178    * checking that the client's UID is in our group OR that the
179    * client's GID is our GID.  If both "match_gid" and @e match_uid are
180    * #GNUNET_NO, all users on the local system have access.
181    */
182   int match_gid;
183
184   /**
185    * Set to #GNUNET_YES if we got a shutdown signal and terminate
186    * the service if #have_non_monitor_clients() returns #GNUNET_YES.
187    */
188   int got_shutdown;
189
190   /**
191    * Our options.
192    */
193   enum GNUNET_SERVICE_Options options;
194
195   /**
196    * If we are daemonizing, this FD is set to the
197    * pipe to the parent.  Send '.' if we started
198    * ok, '!' if not.  -1 if we are not daemonizing.
199    */
200   int ready_confirm_fd;
201
202   /**
203    * Overall success/failure of the service start.
204    */
205   int ret;
206
207   /**
208    * If #GNUNET_YES, consider unknown message types an error where the
209    * client is disconnected.
210    */
211   int require_found;
212 };
213
214
215 /**
216  * Handle to a client that is connected to a service.
217  */
218 struct GNUNET_SERVICE_Client
219 {
220
221   /**
222    * Kept in a DLL.
223    */
224   struct GNUNET_SERVICE_Client *next;
225
226   /**
227    * Kept in a DLL.
228    */
229   struct GNUNET_SERVICE_Client *prev;
230
231   /**
232    * Service that this client belongs to.
233    */
234   struct GNUNET_SERVICE_Handle *sh;
235
236   /**
237    * Socket of this client.
238    */
239   struct GNUNET_NETWORK_Handle *sock;
240
241   /**
242    * Message queue for the client.
243    */
244   struct GNUNET_MQ_Handle *mq;
245
246   /**
247    * Tokenizer we use for processing incoming data.
248    */
249   struct GNUNET_MessageStreamTokenizer *mst;
250
251   /**
252    * Task that warns about missing calls to
253    * #GNUNET_SERVICE_client_continue().
254    */
255   struct GNUNET_SCHEDULER_Task *warn_task;
256
257   /**
258    * Task run to finish dropping the client after the stack has
259    * properly unwound.
260    */
261   struct GNUNET_SCHEDULER_Task *drop_task;
262
263   /**
264    * Task that receives data from the client to
265    * pass it to the handlers.
266    */
267   struct GNUNET_SCHEDULER_Task *recv_task;
268
269   /**
270    * Task that transmit data to the client.
271    */
272   struct GNUNET_SCHEDULER_Task *send_task;
273
274   /**
275    * Pointer to the message to be transmitted by @e send_task.
276    */
277   const struct GNUNET_MessageHeader *msg;
278
279   /**
280    * User context value, value returned from
281    * the connect callback.
282    */
283   void *user_context;
284
285   /**
286    * Time when we last gave a message from this client
287    * to the application.
288    */
289   struct GNUNET_TIME_Absolute warn_start;
290
291   /**
292    * Current position in @e msg at which we are transmitting.
293    */
294   size_t msg_pos;
295
296   /**
297    * Persist the file handle for this client no matter what happens,
298    * force the OS to close once the process actually dies.  Should only
299    * be used in special cases!
300    */
301   int persist;
302
303   /**
304    * Is this client a 'monitor' client that should not be counted
305    * when deciding on destroying the server during soft shutdown?
306    * (see also #GNUNET_SERVICE_start)
307    */
308   int is_monitor;
309
310   /**
311    * Are we waiting for the application to call #GNUNET_SERVICE_client_continue()?
312    */
313   int needs_continue;
314
315   /**
316    * Type of last message processed (for warn_no_receive_done).
317    */
318   uint16_t warn_type;
319 };
320
321
322 /**
323  * Check if any of the clients we have left are unrelated to
324  * monitoring.
325  *
326  * @param sh service to check clients for
327  * @return #GNUNET_YES if we have non-monitoring clients left
328  */
329 static int
330 have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
331 {
332   struct GNUNET_SERVICE_Client *client;
333
334   for (client = sh->clients_head;NULL != client; client = client->next)
335   {
336     if (client->is_monitor)
337       continue;
338     return GNUNET_YES;
339   }
340   return GNUNET_NO;
341 }
342
343
344 /**
345  * Shutdown task triggered when a service should be terminated.
346  * This considers active clients and the service options to see
347  * how this specific service is to be terminated, and depending
348  * on this proceeds with the shutdown logic.
349  *
350  * @param cls our `struct GNUNET_SERVICE_Handle`
351  */
352 static void
353 service_shutdown (void *cls)
354 {
355   struct GNUNET_SERVICE_Handle *sh = cls;
356
357   switch (sh->options)
358   {
359   case GNUNET_SERVICE_OPTION_NONE:
360     GNUNET_SERVICE_shutdown (sh);
361     break;
362   case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
363     /* This task should never be run if we are using
364        the manual shutdown. */
365     GNUNET_assert (0);
366     break;
367   case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
368     sh->got_shutdown = GNUNET_YES;
369     GNUNET_SERVICE_suspend (sh);
370     if (GNUNET_NO == have_non_monitor_clients (sh))
371       GNUNET_SERVICE_shutdown (sh);
372     break;
373   }
374 }
375
376
377 /**
378  * First task run by any service.  Initializes our shutdown task,
379  * starts the listening operation on our listen sockets and launches
380  * the custom logic of the application service.
381  *
382  * @param cls our `struct GNUNET_SERVICE_Handle`
383  */
384 static void
385 service_main (void *cls)
386 {
387   struct GNUNET_SERVICE_Handle *sh = cls;
388
389   if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
390     GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
391                                    sh);
392   GNUNET_SERVICE_resume (sh);
393
394   if (-1 != sh->ready_confirm_fd)
395   {
396     GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
397     GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
398     sh->ready_confirm_fd = -1;
399   }
400
401   if (NULL != sh->service_init_cb)
402     sh->service_init_cb (sh->cb_cls,
403                          sh->cfg,
404                          sh);
405 }
406
407
408 /**
409  * Parse an IPv4 access control list.
410  *
411  * @param ret location where to write the ACL (set)
412  * @param sh service context to use to get the configuration
413  * @param option name of the ACL option to parse
414  * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
415  *         no ACL configured)
416  */
417 static int
418 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
419               struct GNUNET_SERVICE_Handle *sh,
420               const char *option)
421 {
422   char *opt;
423
424   if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
425                                          sh->service_name,
426                                          option))
427   {
428     *ret = NULL;
429     return GNUNET_OK;
430   }
431   GNUNET_break (GNUNET_OK ==
432                 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
433                                                        sh->service_name,
434                                                        option,
435                                                        &opt));
436   if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
437   {
438     LOG (GNUNET_ERROR_TYPE_WARNING,
439          _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
440          opt,
441          sh->service_name,
442          option);
443     GNUNET_free (opt);
444     return GNUNET_SYSERR;
445   }
446   GNUNET_free (opt);
447   return GNUNET_OK;
448 }
449
450
451 /**
452  * Parse an IPv6 access control list.
453  *
454  * @param ret location where to write the ACL (set)
455  * @param sh service context to use to get the configuration
456  * @param option name of the ACL option to parse
457  * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
458  *         no ACL configured)
459  */
460 static int
461 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
462               struct GNUNET_SERVICE_Handle *sh,
463               const char *option)
464 {
465   char *opt;
466
467   if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
468                                          sh->service_name,
469                                          option))
470   {
471     *ret = NULL;
472     return GNUNET_OK;
473   }
474   GNUNET_break (GNUNET_OK ==
475                 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
476                                                        sh->service_name,
477                                                        option,
478                                                        &opt));
479   if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
480   {
481     LOG (GNUNET_ERROR_TYPE_WARNING,
482          _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
483          opt,
484          sh->service_name,
485          option);
486     GNUNET_free (opt);
487     return GNUNET_SYSERR;
488   }
489   GNUNET_free (opt);
490   return GNUNET_OK;
491 }
492
493
494 /**
495  * Add the given UNIX domain path as an address to the
496  * list (as the first entry).
497  *
498  * @param saddrs array to update
499  * @param saddrlens where to store the address length
500  * @param unixpath path to add
501  * @param abstract #GNUNET_YES to add an abstract UNIX domain socket.  This
502  *          parameter is ignore on systems other than LINUX
503  */
504 static void
505 add_unixpath (struct sockaddr **saddrs,
506               socklen_t *saddrlens,
507               const char *unixpath,
508               int abstract)
509 {
510 #ifdef AF_UNIX
511   struct sockaddr_un *un;
512
513   un = GNUNET_new (struct sockaddr_un);
514   un->sun_family = AF_UNIX;
515   strncpy (un->sun_path,
516            unixpath,
517            sizeof (un->sun_path) - 1);
518 #ifdef LINUX
519   if (GNUNET_YES == abstract)
520     un->sun_path[0] = '\0';
521 #endif
522 #if HAVE_SOCKADDR_IN_SIN_LEN
523   un->sun_len = (u_char) sizeof (struct sockaddr_un);
524 #endif
525   *saddrs = (struct sockaddr *) un;
526   *saddrlens = sizeof (struct sockaddr_un);
527 #else
528   /* this function should never be called
529    * unless AF_UNIX is defined! */
530   GNUNET_assert (0);
531 #endif
532 }
533
534
535 /**
536  * Get the list of addresses that a server for the given service
537  * should bind to.
538  *
539  * @param service_name name of the service
540  * @param cfg configuration (which specifies the addresses)
541  * @param addrs set (call by reference) to an array of pointers to the
542  *              addresses the server should bind to and listen on; the
543  *              array will be NULL-terminated (on success)
544  * @param addr_lens set (call by reference) to an array of the lengths
545  *              of the respective `struct sockaddr` struct in the @a addrs
546  *              array (on success)
547  * @return number of addresses found on success,
548  *              #GNUNET_SYSERR if the configuration
549  *              did not specify reasonable finding information or
550  *              if it specified a hostname that could not be resolved;
551  *              #GNUNET_NO if the number of addresses configured is
552  *              zero (in this case, `*addrs` and `*addr_lens` will be
553  *              set to NULL).
554  */
555 static int
556 get_server_addresses (const char *service_name,
557                       const struct GNUNET_CONFIGURATION_Handle *cfg,
558                       struct sockaddr ***addrs,
559                       socklen_t **addr_lens)
560 {
561   int disablev6;
562   struct GNUNET_NETWORK_Handle *desc;
563   unsigned long long port;
564   char *unixpath;
565   struct addrinfo hints;
566   struct addrinfo *res;
567   struct addrinfo *pos;
568   struct addrinfo *next;
569   unsigned int i;
570   int resi;
571   int ret;
572   int abstract;
573   struct sockaddr **saddrs;
574   socklen_t *saddrlens;
575   char *hostname;
576
577   *addrs = NULL;
578   *addr_lens = NULL;
579   desc = NULL;
580   if (GNUNET_CONFIGURATION_have_value (cfg,
581                                        service_name,
582                                        "DISABLEV6"))
583   {
584     if (GNUNET_SYSERR ==
585         (disablev6 =
586          GNUNET_CONFIGURATION_get_value_yesno (cfg,
587                                                service_name,
588                                                "DISABLEV6")))
589       return GNUNET_SYSERR;
590   }
591   else
592     disablev6 = GNUNET_NO;
593
594   if (! disablev6)
595   {
596     /* probe IPv6 support */
597     desc = GNUNET_NETWORK_socket_create (PF_INET6,
598                                          SOCK_STREAM,
599                                          0);
600     if (NULL == desc)
601     {
602       if ( (ENOBUFS == errno) ||
603            (ENOMEM == errno) ||
604            (ENFILE == errno) ||
605            (EACCES == errno) )
606       {
607         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
608                       "socket");
609         return GNUNET_SYSERR;
610       }
611       LOG (GNUNET_ERROR_TYPE_INFO,
612            _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
613            service_name,
614            STRERROR (errno));
615       disablev6 = GNUNET_YES;
616     }
617     else
618     {
619       GNUNET_break (GNUNET_OK ==
620                     GNUNET_NETWORK_socket_close (desc));
621       desc = NULL;
622     }
623   }
624
625   port = 0;
626   if (GNUNET_CONFIGURATION_have_value (cfg,
627                                        service_name,
628                                        "PORT"))
629   {
630     if (GNUNET_OK !=
631         GNUNET_CONFIGURATION_get_value_number (cfg,
632                                                service_name,
633                                                "PORT",
634                                                &port))
635     {
636       LOG (GNUNET_ERROR_TYPE_ERROR,
637            _("Require valid port number for service `%s' in configuration!\n"),
638            service_name);
639     }
640     if (port > 65535)
641     {
642       LOG (GNUNET_ERROR_TYPE_ERROR,
643            _("Require valid port number for service `%s' in configuration!\n"),
644            service_name);
645       return GNUNET_SYSERR;
646     }
647   }
648
649   if (GNUNET_CONFIGURATION_have_value (cfg,
650                                        service_name,
651                                        "BINDTO"))
652   {
653     GNUNET_break (GNUNET_OK ==
654                   GNUNET_CONFIGURATION_get_value_string (cfg,
655                                                          service_name,
656                                                          "BINDTO",
657                                                          &hostname));
658   }
659   else
660     hostname = NULL;
661
662   unixpath = NULL;
663   abstract = GNUNET_NO;
664 #ifdef AF_UNIX
665   if ((GNUNET_YES ==
666        GNUNET_CONFIGURATION_have_value (cfg,
667                                         service_name,
668                                         "UNIXPATH")) &&
669       (GNUNET_OK ==
670        GNUNET_CONFIGURATION_get_value_filename (cfg,
671                                                 service_name,
672                                                 "UNIXPATH",
673                                                 &unixpath)) &&
674       (0 < strlen (unixpath)))
675   {
676     /* probe UNIX support */
677     struct sockaddr_un s_un;
678
679     if (strlen (unixpath) >= sizeof (s_un.sun_path))
680     {
681       LOG (GNUNET_ERROR_TYPE_WARNING,
682            _("UNIXPATH `%s' too long, maximum length is %llu\n"),
683            unixpath,
684            (unsigned long long) sizeof (s_un.sun_path));
685       unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
686       LOG (GNUNET_ERROR_TYPE_INFO,
687            _("Using `%s' instead\n"),
688            unixpath);
689     }
690 #ifdef LINUX
691     abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
692                                                      "TESTING",
693                                                      "USE_ABSTRACT_SOCKETS");
694     if (GNUNET_SYSERR == abstract)
695       abstract = GNUNET_NO;
696 #endif
697     if ( (GNUNET_YES != abstract) &&
698          (GNUNET_OK !=
699           GNUNET_DISK_directory_create_for_file (unixpath)) )
700       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
701                                 "mkdir",
702                                 unixpath);
703   }
704   if (NULL != unixpath)
705   {
706     desc = GNUNET_NETWORK_socket_create (AF_UNIX,
707                                          SOCK_STREAM,
708                                          0);
709     if (NULL == desc)
710     {
711       if ((ENOBUFS == errno) ||
712           (ENOMEM == errno) ||
713           (ENFILE == errno) ||
714           (EACCES == errno))
715       {
716         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
717                       "socket");
718         GNUNET_free_non_null (hostname);
719         GNUNET_free (unixpath);
720         return GNUNET_SYSERR;
721       }
722       LOG (GNUNET_ERROR_TYPE_INFO,
723            _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
724            service_name,
725            STRERROR (errno));
726       GNUNET_free (unixpath);
727       unixpath = NULL;
728     }
729     else
730     {
731       GNUNET_break (GNUNET_OK ==
732                     GNUNET_NETWORK_socket_close (desc));
733       desc = NULL;
734     }
735   }
736 #endif
737
738   if ((0 == port) && (NULL == unixpath))
739   {
740     LOG (GNUNET_ERROR_TYPE_ERROR,
741          _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
742          service_name);
743     GNUNET_free_non_null (hostname);
744     return GNUNET_SYSERR;
745   }
746   if (0 == port)
747   {
748     saddrs = GNUNET_new_array (2,
749                                struct sockaddr *);
750     saddrlens = GNUNET_new_array (2,
751                                   socklen_t);
752     add_unixpath (saddrs,
753                   saddrlens,
754                   unixpath,
755                   abstract);
756     GNUNET_free_non_null (unixpath);
757     GNUNET_free_non_null (hostname);
758     *addrs = saddrs;
759     *addr_lens = saddrlens;
760     return 1;
761   }
762
763   if (NULL != hostname)
764   {
765     LOG (GNUNET_ERROR_TYPE_DEBUG,
766          "Resolving `%s' since that is where `%s' will bind to.\n",
767          hostname,
768          service_name);
769     memset (&hints,
770             0,
771             sizeof (struct addrinfo));
772     if (disablev6)
773       hints.ai_family = AF_INET;
774     hints.ai_protocol = IPPROTO_TCP;
775     if ((0 != (ret = getaddrinfo (hostname,
776                                   NULL,
777                                   &hints,
778                                   &res))) ||
779         (NULL == res))
780     {
781       LOG (GNUNET_ERROR_TYPE_ERROR,
782            _("Failed to resolve `%s': %s\n"),
783            hostname,
784            gai_strerror (ret));
785       GNUNET_free (hostname);
786       GNUNET_free_non_null (unixpath);
787       return GNUNET_SYSERR;
788     }
789     next = res;
790     i = 0;
791     while (NULL != (pos = next))
792     {
793       next = pos->ai_next;
794       if ( (disablev6) &&
795            (pos->ai_family == AF_INET6) )
796         continue;
797       i++;
798     }
799     if (0 == i)
800     {
801       LOG (GNUNET_ERROR_TYPE_ERROR,
802            _("Failed to find %saddress for `%s'.\n"),
803            disablev6 ? "IPv4 " : "",
804            hostname);
805       freeaddrinfo (res);
806       GNUNET_free (hostname);
807       GNUNET_free_non_null (unixpath);
808       return GNUNET_SYSERR;
809     }
810     resi = i;
811     if (NULL != unixpath)
812       resi++;
813     saddrs = GNUNET_new_array (resi + 1,
814                                struct sockaddr *);
815     saddrlens = GNUNET_new_array (resi + 1,
816                                   socklen_t);
817     i = 0;
818     if (NULL != unixpath)
819     {
820       add_unixpath (saddrs,
821                     saddrlens,
822                     unixpath,
823                     abstract);
824       i++;
825     }
826     next = res;
827     while (NULL != (pos = next))
828     {
829       next = pos->ai_next;
830       if ( (disablev6) &&
831            (AF_INET6 == pos->ai_family) )
832         continue;
833       if ( (IPPROTO_TCP != pos->ai_protocol) &&
834            (0 != pos->ai_protocol) )
835         continue;               /* not TCP */
836       if ( (SOCK_STREAM != pos->ai_socktype) &&
837            (0 != pos->ai_socktype) )
838         continue;               /* huh? */
839       LOG (GNUNET_ERROR_TYPE_DEBUG,
840            "Service `%s' will bind to `%s'\n",
841            service_name,
842            GNUNET_a2s (pos->ai_addr,
843                        pos->ai_addrlen));
844       if (AF_INET == pos->ai_family)
845       {
846         GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
847         saddrlens[i] = pos->ai_addrlen;
848         saddrs[i] = GNUNET_malloc (saddrlens[i]);
849         GNUNET_memcpy (saddrs[i],
850                        pos->ai_addr,
851                        saddrlens[i]);
852         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
853       }
854       else
855       {
856         GNUNET_assert (AF_INET6 == pos->ai_family);
857         GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
858         saddrlens[i] = pos->ai_addrlen;
859         saddrs[i] = GNUNET_malloc (saddrlens[i]);
860         GNUNET_memcpy (saddrs[i],
861                        pos->ai_addr,
862                        saddrlens[i]);
863         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
864       }
865       i++;
866     }
867     GNUNET_free (hostname);
868     freeaddrinfo (res);
869     resi = i;
870   }
871   else
872   {
873     /* will bind against everything, just set port */
874     if (disablev6)
875     {
876       /* V4-only */
877       resi = 1;
878       if (NULL != unixpath)
879         resi++;
880       i = 0;
881       saddrs = GNUNET_new_array (resi + 1,
882                                  struct sockaddr *);
883       saddrlens = GNUNET_new_array (resi + 1,
884                                     socklen_t);
885       if (NULL != unixpath)
886       {
887         add_unixpath (saddrs,
888                       saddrlens,
889                       unixpath,
890                       abstract);
891         i++;
892       }
893       saddrlens[i] = sizeof (struct sockaddr_in);
894       saddrs[i] = GNUNET_malloc (saddrlens[i]);
895 #if HAVE_SOCKADDR_IN_SIN_LEN
896       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
897 #endif
898       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
899       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
900     }
901     else
902     {
903       /* dual stack */
904       resi = 2;
905       if (NULL != unixpath)
906         resi++;
907       saddrs = GNUNET_new_array (resi + 1,
908                                  struct sockaddr *);
909       saddrlens = GNUNET_new_array (resi + 1,
910                                     socklen_t);
911       i = 0;
912       if (NULL != unixpath)
913       {
914         add_unixpath (saddrs,
915                       saddrlens,
916                       unixpath,
917                       abstract);
918         i++;
919       }
920       saddrlens[i] = sizeof (struct sockaddr_in6);
921       saddrs[i] = GNUNET_malloc (saddrlens[i]);
922 #if HAVE_SOCKADDR_IN_SIN_LEN
923       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
924 #endif
925       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
926       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
927       i++;
928       saddrlens[i] = sizeof (struct sockaddr_in);
929       saddrs[i] = GNUNET_malloc (saddrlens[i]);
930 #if HAVE_SOCKADDR_IN_SIN_LEN
931       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
932 #endif
933       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
934       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
935     }
936   }
937   GNUNET_free_non_null (unixpath);
938   *addrs = saddrs;
939   *addr_lens = saddrlens;
940   return resi;
941 }
942
943
944 #ifdef MINGW
945 /**
946  * Read listen sockets from the parent process (ARM).
947  *
948  * @param sh service context to initialize
949  * @return NULL-terminated array of sockets on success,
950  *         NULL if not ok (must bind yourself)
951  */
952 static struct GNUNET_NETWORK_Handle **
953 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
954 {
955   static struct GNUNET_NETWORK_Handle **lsocks;
956   const char *env_buf;
957   int fail;
958   uint64_t count;
959   uint64_t i;
960   HANDLE lsocks_pipe;
961
962   env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
963   if ( (NULL == env_buf) ||
964        (strlen (env_buf) <= 0) )
965     return NULL;
966   /* Using W32 API directly here, because this pipe will
967    * never be used outside of this function, and it's just too much of a bother
968    * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
969    */
970   lsocks_pipe = (HANDLE) strtoul (env_buf,
971                                   NULL,
972                                   10);
973   if ( (0 == lsocks_pipe) ||
974        (INVALID_HANDLE_VALUE == lsocks_pipe))
975     return NULL;
976   fail = 1;
977   do
978   {
979     int ret;
980     int fail2;
981     DWORD rd;
982
983     ret = ReadFile (lsocks_pipe,
984                     &count,
985                     sizeof (count),
986                     &rd,
987                     NULL);
988     if ( (0 == ret) ||
989          (sizeof (count) != rd) ||
990          (0 == count) )
991       break;
992     lsocks = GNUNET_new_array (count + 1,
993                                struct GNUNET_NETWORK_Handle *);
994
995     fail2 = 1;
996     for (i = 0; i < count; i++)
997     {
998       WSAPROTOCOL_INFOA pi;
999       uint64_t size;
1000       SOCKET s;
1001
1002       ret = ReadFile (lsocks_pipe,
1003                       &size,
1004                       sizeof (size),
1005                       &rd,
1006                       NULL);
1007       if ( (0 == ret) ||
1008            (sizeof (size) != rd) ||
1009            (sizeof (pi) != size) )
1010         break;
1011       ret = ReadFile (lsocks_pipe,
1012                       &pi,
1013                       sizeof (pi),
1014                       &rd,
1015                       NULL);
1016       if ( (0 == ret) ||
1017            (sizeof (pi) != rd))
1018         break;
1019       s = WSASocketA (pi.iAddressFamily,
1020                       pi.iSocketType,
1021                       pi.iProtocol,
1022                       &pi,
1023                       0,
1024                       WSA_FLAG_OVERLAPPED);
1025       lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1026       if (NULL == lsocks[i])
1027         break;
1028       else if (i == count - 1)
1029         fail2 = 0;
1030     }
1031     if (fail2)
1032       break;
1033     lsocks[count] = NULL;
1034     fail = 0;
1035   }
1036   while (fail);
1037   CloseHandle (lsocks_pipe);
1038
1039   if (fail)
1040   {
1041     LOG (GNUNET_ERROR_TYPE_ERROR,
1042          _("Could not access a pre-bound socket, will try to bind myself\n"));
1043     for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1044       GNUNET_break (GNUNET_OK ==
1045                     GNUNET_NETWORK_socket_close (lsocks[i]));
1046     GNUNET_free (lsocks);
1047     return NULL;
1048   }
1049   return lsocks;
1050 }
1051 #endif
1052
1053
1054 /**
1055  * Create and initialize a listen socket for the server.
1056  *
1057  * @param server_addr address to listen on
1058  * @param socklen length of @a server_addr
1059  * @return NULL on error, otherwise the listen socket
1060  */
1061 static struct GNUNET_NETWORK_Handle *
1062 open_listen_socket (const struct sockaddr *server_addr,
1063                     socklen_t socklen)
1064 {
1065   struct GNUNET_NETWORK_Handle *sock;
1066   uint16_t port;
1067   int eno;
1068
1069   switch (server_addr->sa_family)
1070   {
1071   case AF_INET:
1072     port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1073     break;
1074   case AF_INET6:
1075     port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1076     break;
1077   case AF_UNIX:
1078     port = 0;
1079     break;
1080   default:
1081     GNUNET_break (0);
1082     port = 0;
1083     break;
1084   }
1085   sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1086                                        SOCK_STREAM,
1087                                        0);
1088   if (NULL == sock)
1089   {
1090     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1091                   "socket");
1092     errno = 0;
1093     return NULL;
1094   }
1095   /* bind the socket */
1096   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1097                                                server_addr,
1098                                                socklen))
1099   {
1100     eno = errno;
1101     if (EADDRINUSE != errno)
1102     {
1103       /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1104        * fail if we already took the port on IPv6; if both IPv4 and
1105        * IPv6 binds fail, then our caller will log using the
1106        * errno preserved in 'eno' */
1107       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1108                     "bind");
1109       if (0 != port)
1110         LOG (GNUNET_ERROR_TYPE_ERROR,
1111              _("`%s' failed for port %d (%s).\n"),
1112              "bind",
1113              port,
1114              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1115       eno = 0;
1116     }
1117     else
1118     {
1119       if (0 != port)
1120         LOG (GNUNET_ERROR_TYPE_WARNING,
1121              _("`%s' failed for port %d (%s): address already in use\n"),
1122              "bind", port,
1123              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1124       else if (AF_UNIX == server_addr->sa_family)
1125       {
1126         LOG (GNUNET_ERROR_TYPE_WARNING,
1127              _("`%s' failed for `%s': address already in use\n"),
1128              "bind",
1129              GNUNET_a2s (server_addr, socklen));
1130       }
1131     }
1132     GNUNET_break (GNUNET_OK ==
1133                   GNUNET_NETWORK_socket_close (sock));
1134     errno = eno;
1135     return NULL;
1136   }
1137   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1138                                                  5))
1139   {
1140     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1141                   "listen");
1142     GNUNET_break (GNUNET_OK ==
1143                   GNUNET_NETWORK_socket_close (sock));
1144     errno = 0;
1145     return NULL;
1146   }
1147   if (0 != port)
1148     LOG (GNUNET_ERROR_TYPE_DEBUG,
1149          "Server starts to listen on port %u.\n",
1150          port);
1151   return sock;
1152 }
1153
1154
1155 /**
1156  * Setup service handle
1157  *
1158  * Configuration may specify:
1159  * - PORT (where to bind to for TCP)
1160  * - UNIXPATH (where to bind to for UNIX domain sockets)
1161  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1162  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1163  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
1164  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1165  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
1166  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1167  *
1168  * @param sh service context to initialize
1169  * @return #GNUNET_OK if configuration succeeded
1170  */
1171 static int
1172 setup_service (struct GNUNET_SERVICE_Handle *sh)
1173 {
1174   int tolerant;
1175   struct GNUNET_NETWORK_Handle **lsocks;
1176 #ifndef MINGW
1177   const char *nfds;
1178   unsigned int cnt;
1179   int flags;
1180 #endif
1181
1182   if (GNUNET_CONFIGURATION_have_value
1183       (sh->cfg,
1184        sh->service_name,
1185        "TOLERANT"))
1186   {
1187     if (GNUNET_SYSERR ==
1188         (tolerant =
1189          GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1190                                                sh->service_name,
1191                                                "TOLERANT")))
1192     {
1193       LOG (GNUNET_ERROR_TYPE_ERROR,
1194            _("Specified value for `%s' of service `%s' is invalid\n"),
1195            "TOLERANT",
1196            sh->service_name);
1197       return GNUNET_SYSERR;
1198     }
1199   }
1200   else
1201     tolerant = GNUNET_NO;
1202
1203   lsocks = NULL;
1204 #ifndef MINGW
1205   errno = 0;
1206   if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1207        (1 == SSCANF (nfds,
1208                      "%u",
1209                      &cnt)) &&
1210        (cnt > 0) &&
1211        (cnt < FD_SETSIZE) &&
1212        (cnt + 4 < FD_SETSIZE) )
1213   {
1214     lsocks = GNUNET_new_array (cnt + 1,
1215                                struct GNUNET_NETWORK_Handle *);
1216     while (0 < cnt--)
1217     {
1218       flags = fcntl (3 + cnt,
1219                      F_GETFD);
1220       if ( (flags < 0) ||
1221            (0 != (flags & FD_CLOEXEC)) ||
1222            (NULL ==
1223             (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1224       {
1225         LOG (GNUNET_ERROR_TYPE_ERROR,
1226              _("Could not access pre-bound socket %u, will try to bind myself\n"),
1227              (unsigned int) 3 + cnt);
1228         cnt++;
1229         while (NULL != lsocks[cnt])
1230           GNUNET_break (GNUNET_OK ==
1231                         GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1232         GNUNET_free (lsocks);
1233         lsocks = NULL;
1234         break;
1235       }
1236     }
1237     unsetenv ("LISTEN_FDS");
1238   }
1239 #else
1240   if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1241   {
1242     lsocks = receive_sockets_from_parent (sh);
1243     putenv ("GNUNET_OS_READ_LSOCKS=");
1244   }
1245 #endif
1246
1247   if (NULL != lsocks)
1248   {
1249     /* listen only on inherited sockets if we have any */
1250     struct GNUNET_NETWORK_Handle **ls;
1251
1252     for (ls = lsocks; NULL != *ls; ls++)
1253     {
1254       struct ServiceListenContext *slc;
1255
1256       slc = GNUNET_new (struct ServiceListenContext);
1257       slc->sh = sh;
1258       slc->listen_socket = *ls;
1259       GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1260                                    sh->slc_tail,
1261                                    slc);
1262     }
1263     GNUNET_free (lsocks);
1264   }
1265   else
1266   {
1267     struct sockaddr **addrs;
1268     socklen_t *addrlens;
1269     int num;
1270
1271     num = get_server_addresses (sh->service_name,
1272                                 sh->cfg,
1273                                 &addrs,
1274                                 &addrlens);
1275     if (GNUNET_SYSERR == num)
1276       return GNUNET_SYSERR;
1277
1278     for (int i = 0; i < num; i++)
1279     {
1280       struct ServiceListenContext *slc;
1281
1282       slc = GNUNET_new (struct ServiceListenContext);
1283       slc->sh = sh;
1284       slc->listen_socket = open_listen_socket (addrs[i],
1285                                                addrlens[i]);
1286       if (NULL == slc->listen_socket)
1287       {
1288         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1289                              "bind");
1290         GNUNET_free (addrs[i++]);
1291         GNUNET_free (slc);
1292         continue;
1293       }
1294       GNUNET_free (addrs[i++]);
1295       GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1296                                    sh->slc_tail,
1297                                    slc);
1298     }
1299     GNUNET_free_non_null (addrlens);
1300     GNUNET_free_non_null (addrs);
1301     if ( (0 != num) &&
1302          (NULL == sh->slc_head) )
1303     {
1304       /* All attempts to bind failed, hard failure */
1305       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1306                   _("Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1307       return GNUNET_SYSERR;
1308     }
1309   }
1310
1311   sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1312   sh->match_uid
1313     = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1314                                             sh->service_name,
1315                                             "UNIX_MATCH_UID");
1316   sh->match_gid
1317     = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1318                                             sh->service_name,
1319                                             "UNIX_MATCH_GID");
1320   process_acl4 (&sh->v4_denied,
1321                 sh,
1322                 "REJECT_FROM");
1323   process_acl4 (&sh->v4_allowed,
1324                 sh,
1325                 "ACCEPT_FROM");
1326   process_acl6 (&sh->v6_denied,
1327                 sh,
1328                 "REJECT_FROM6");
1329   process_acl6 (&sh->v6_allowed,
1330                 sh,
1331                 "ACCEPT_FROM6");
1332   return GNUNET_OK;
1333 }
1334
1335
1336 /**
1337  * Get the name of the user that'll be used
1338  * to provide the service.
1339  *
1340  * @param sh service context
1341  * @return value of the 'USERNAME' option
1342  */
1343 static char *
1344 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1345 {
1346   char *un;
1347
1348   if (GNUNET_OK !=
1349       GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1350                                                sh->service_name,
1351                                                "USERNAME",
1352                                                &un))
1353     return NULL;
1354   return un;
1355 }
1356
1357
1358 /**
1359  * Set user ID.
1360  *
1361  * @param sh service context
1362  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1363  */
1364 static int
1365 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1366 {
1367   char *user;
1368
1369   if (NULL == (user = get_user_name (sh)))
1370     return GNUNET_OK;           /* keep */
1371 #ifndef MINGW
1372   struct passwd *pws;
1373
1374   errno = 0;
1375   pws = getpwnam (user);
1376   if (NULL == pws)
1377   {
1378     LOG (GNUNET_ERROR_TYPE_ERROR,
1379          _("Cannot obtain information about user `%s': %s\n"),
1380          user,
1381          errno == 0 ? _("No such user") : STRERROR (errno));
1382     GNUNET_free (user);
1383     return GNUNET_SYSERR;
1384   }
1385   if ( (0 != setgid (pws->pw_gid)) ||
1386        (0 != setegid (pws->pw_gid)) ||
1387 #if HAVE_INITGROUPS
1388        (0 != initgroups (user,
1389                          pws->pw_gid)) ||
1390 #endif
1391        (0 != setuid (pws->pw_uid)) ||
1392        (0 != seteuid (pws->pw_uid)))
1393   {
1394     if ((0 != setregid (pws->pw_gid,
1395                         pws->pw_gid)) ||
1396         (0 != setreuid (pws->pw_uid,
1397                         pws->pw_uid)))
1398     {
1399       LOG (GNUNET_ERROR_TYPE_ERROR,
1400            _("Cannot change user/group to `%s': %s\n"),
1401            user,
1402            STRERROR (errno));
1403       GNUNET_free (user);
1404       return GNUNET_SYSERR;
1405     }
1406   }
1407 #endif
1408   GNUNET_free (user);
1409   return GNUNET_OK;
1410 }
1411
1412
1413 /**
1414  * Get the name of the file where we will
1415  * write the PID of the service.
1416  *
1417  * @param sh service context
1418  * @return name of the file for the process ID
1419  */
1420 static char *
1421 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1422 {
1423   char *pif;
1424
1425   if (GNUNET_OK !=
1426       GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1427                                                sh->service_name,
1428                                                "PIDFILE",
1429                                                &pif))
1430     return NULL;
1431   return pif;
1432 }
1433
1434
1435 /**
1436  * Delete the PID file that was created by our parent.
1437  *
1438  * @param sh service context
1439  */
1440 static void
1441 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1442 {
1443   char *pif = get_pid_file_name (sh);
1444
1445   if (NULL == pif)
1446     return;                     /* no PID file */
1447   if (0 != UNLINK (pif))
1448     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1449                        "unlink",
1450                        pif);
1451   GNUNET_free (pif);
1452 }
1453
1454
1455 /**
1456  * Detach from terminal.
1457  *
1458  * @param sh service context
1459  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1460  */
1461 static int
1462 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1463 {
1464 #ifndef MINGW
1465   pid_t pid;
1466   int nullfd;
1467   int filedes[2];
1468
1469   if (0 != PIPE (filedes))
1470   {
1471     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1472                   "pipe");
1473     return GNUNET_SYSERR;
1474   }
1475   pid = fork ();
1476   if (pid < 0)
1477   {
1478     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1479                   "fork");
1480     return GNUNET_SYSERR;
1481   }
1482   if (0 != pid)
1483   {
1484     /* Parent */
1485     char c;
1486
1487     GNUNET_break (0 == CLOSE (filedes[1]));
1488     c = 'X';
1489     if (1 != READ (filedes[0],
1490                    &c,
1491                    sizeof (char)))
1492       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1493                     "read");
1494     fflush (stdout);
1495     switch (c)
1496     {
1497     case '.':
1498       exit (0);
1499     case 'I':
1500       LOG (GNUNET_ERROR_TYPE_INFO,
1501            _("Service process failed to initialize\n"));
1502       break;
1503     case 'S':
1504       LOG (GNUNET_ERROR_TYPE_INFO,
1505            _("Service process could not initialize server function\n"));
1506       break;
1507     case 'X':
1508       LOG (GNUNET_ERROR_TYPE_INFO,
1509            _("Service process failed to report status\n"));
1510       break;
1511     }
1512     exit (1);                   /* child reported error */
1513   }
1514   GNUNET_break (0 == CLOSE (0));
1515   GNUNET_break (0 == CLOSE (1));
1516   GNUNET_break (0 == CLOSE (filedes[0]));
1517   nullfd = OPEN ("/dev/null",
1518                  O_RDWR | O_APPEND);
1519   if (nullfd < 0)
1520     return GNUNET_SYSERR;
1521   /* set stdin/stdout to /dev/null */
1522   if ( (dup2 (nullfd, 0) < 0) ||
1523        (dup2 (nullfd, 1) < 0) )
1524   {
1525     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1526                   "dup2");
1527     (void) CLOSE (nullfd);
1528     return GNUNET_SYSERR;
1529   }
1530   (void) CLOSE (nullfd);
1531   /* Detach from controlling terminal */
1532   pid = setsid ();
1533   if (-1 == pid)
1534     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1535                   "setsid");
1536   sh->ready_confirm_fd = filedes[1];
1537 #else
1538   /* FIXME: we probably need to do something else
1539    * elsewhere in order to fork the process itself... */
1540   FreeConsole ();
1541 #endif
1542   return GNUNET_OK;
1543 }
1544
1545
1546 /**
1547  * Tear down the service, closing the listen sockets and
1548  * freeing the ACLs.
1549  *
1550  * @param sh handle to the service to tear down.
1551  */
1552 static void
1553 teardown_service (struct GNUNET_SERVICE_Handle *sh)
1554 {
1555   struct ServiceListenContext *slc;
1556
1557   GNUNET_free_non_null (sh->v4_denied);
1558   GNUNET_free_non_null (sh->v6_denied);
1559   GNUNET_free_non_null (sh->v4_allowed);
1560   GNUNET_free_non_null (sh->v6_allowed);
1561   while (NULL != (slc = sh->slc_head))
1562   {
1563     GNUNET_CONTAINER_DLL_remove (sh->slc_head,
1564                                  sh->slc_tail,
1565                                  slc);
1566     if (NULL != slc->listen_task)
1567       GNUNET_SCHEDULER_cancel (slc->listen_task);
1568     GNUNET_break (GNUNET_OK ==
1569                   GNUNET_NETWORK_socket_close (slc->listen_socket));
1570     GNUNET_free (slc);
1571   }
1572 }
1573
1574
1575 /**
1576  * Low-level function to start a service if the scheduler
1577  * is already running.  Should only be used directly in
1578  * special cases.
1579  *
1580  * The function will launch the service with the name @a service_name
1581  * using the @a service_options to configure its shutdown
1582  * behavior. When clients connect or disconnect, the respective
1583  * @a connect_cb or @a disconnect_cb functions will be called. For
1584  * messages received from the clients, the respective @a handlers will
1585  * be invoked; for the closure of the handlers we use the return value
1586  * from the @a connect_cb invocation of the respective client.
1587  *
1588  * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1589  * message to receive further messages from this client.  If
1590  * #GNUNET_SERVICE_client_continue() is not called within a short
1591  * time, a warning will be logged. If delays are expected, services
1592  * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1593  * disable the warning.
1594  *
1595  * Clients sending invalid messages (based on @a handlers) will be
1596  * dropped. Additionally, clients can be dropped at any time using
1597  * #GNUNET_SERVICE_client_drop().
1598  *
1599  * The service must be stopped using #GNUNET_SERVICE_stoP().
1600  *
1601  * @param service_name name of the service to run
1602  * @param cfg configuration to use
1603  * @param connect_cb function to call whenever a client connects
1604  * @param disconnect_cb function to call whenever a client disconnects
1605  * @param cls closure argument for @a connect_cb and @a disconnect_cb
1606  * @param handlers NULL-terminated array of message handlers for the service,
1607  *                 the closure will be set to the value returned by
1608  *                 the @a connect_cb for the respective connection
1609  * @return NULL on error
1610  */
1611 struct GNUNET_SERVICE_Handle *
1612 GNUNET_SERVICE_starT (const char *service_name,
1613                       const struct GNUNET_CONFIGURATION_Handle *cfg,
1614                       GNUNET_SERVICE_ConnectHandler connect_cb,
1615                       GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1616                       void *cls,
1617                       const struct GNUNET_MQ_MessageHandler *handlers)
1618 {
1619   struct GNUNET_SERVICE_Handle *sh;
1620
1621   sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
1622   sh->service_name = service_name;
1623   sh->cfg = cfg;
1624   sh->connect_cb = connect_cb;
1625   sh->disconnect_cb = disconnect_cb;
1626   sh->cb_cls = cls;
1627   if (NULL != handlers)
1628   {
1629     unsigned int i;
1630
1631     for (i=0;NULL != handlers[i].cb; i++) ;
1632     sh->handlers = GNUNET_new_array (i + 1,
1633                                      struct GNUNET_MQ_MessageHandler);
1634     GNUNET_memcpy (sh->handlers,
1635                    handlers,
1636                    i * sizeof (struct GNUNET_MQ_MessageHandler));
1637   }
1638   if (GNUNET_OK != setup_service (sh))
1639   {
1640     GNUNET_free (sh->handlers);
1641     GNUNET_free (sh);
1642     return NULL;
1643   }
1644   GNUNET_SERVICE_resume (sh);
1645   return sh;
1646 }
1647
1648
1649 /**
1650  * Stops a service that was started with #GNUNET_SERVICE_starT().
1651  *
1652  * @param srv service to stop
1653  */
1654 void
1655 GNUNET_SERVICE_stoP (struct GNUNET_SERVICE_Handle *srv)
1656 {
1657   struct GNUNET_SERVICE_Client *client;
1658
1659   GNUNET_SERVICE_suspend (srv);
1660   while (NULL != (client = srv->clients_head))
1661     GNUNET_SERVICE_client_drop (client);
1662   teardown_service (srv);
1663   GNUNET_free (srv->handlers);
1664   GNUNET_free (srv);
1665 }
1666
1667
1668 /**
1669  * Creates the "main" function for a GNUnet service.  You
1670  * should almost always use the #GNUNET_SERVICE_MAIN macro
1671  * instead of calling this function directly (except
1672  * for ARM, which should call this function directly).
1673  *
1674  * The function will launch the service with the name @a service_name
1675  * using the @a service_options to configure its shutdown
1676  * behavior. Once the service is ready, the @a init_cb will be called
1677  * for service-specific initialization.  @a init_cb will be given the
1678  * service handler which can be used to control the service's
1679  * availability.  When clients connect or disconnect, the respective
1680  * @a connect_cb or @a disconnect_cb functions will be called. For
1681  * messages received from the clients, the respective @a handlers will
1682  * be invoked; for the closure of the handlers we use the return value
1683  * from the @a connect_cb invocation of the respective client.
1684  *
1685  * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1686  * message to receive further messages from this client.  If
1687  * #GNUNET_SERVICE_client_continue() is not called within a short
1688  * time, a warning will be logged. If delays are expected, services
1689  * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1690  * disable the warning.
1691  *
1692  * Clients sending invalid messages (based on @a handlers) will be
1693  * dropped. Additionally, clients can be dropped at any time using
1694  * #GNUNET_SERVICE_client_drop().
1695  *
1696  * @param argc number of command-line arguments in @a argv
1697  * @param argv array of command-line arguments
1698  * @param service_name name of the service to run
1699  * @param options options controlling shutdown of the service
1700  * @param service_init_cb function to call once the service is ready
1701  * @param connect_cb function to call whenever a client connects
1702  * @param disconnect_cb function to call whenever a client disconnects
1703  * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
1704  * @param handlers NULL-terminated array of message handlers for the service,
1705  *                 the closure will be set to the value returned by
1706  *                 the @a connect_cb for the respective connection
1707  * @return 0 on success, non-zero on error
1708  */
1709 int
1710 GNUNET_SERVICE_ruN_ (int argc,
1711                      char *const *argv,
1712                      const char *service_name,
1713                      enum GNUNET_SERVICE_Options options,
1714                      GNUNET_SERVICE_InitCallback service_init_cb,
1715                      GNUNET_SERVICE_ConnectHandler connect_cb,
1716                      GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1717                      void *cls,
1718                      const struct GNUNET_MQ_MessageHandler *handlers)
1719 {
1720   struct GNUNET_SERVICE_Handle sh;
1721   char *cfg_filename;
1722   char *opt_cfg_filename;
1723   char *loglev;
1724   const char *xdg;
1725   char *logfile;
1726   int do_daemonize;
1727   unsigned long long skew_offset;
1728   unsigned long long skew_variance;
1729   long long clock_offset;
1730   struct GNUNET_CONFIGURATION_Handle *cfg;
1731   int ret;
1732   int err;
1733
1734   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1735     GNUNET_GETOPT_OPTION_CFG_FILE (&opt_cfg_filename),
1736     {'d', "daemonize", NULL,
1737      gettext_noop ("do daemonize (detach from terminal)"), 0,
1738      GNUNET_GETOPT_set_one, &do_daemonize},
1739     GNUNET_GETOPT_OPTION_HELP (NULL),
1740     GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1741     GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1742     GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION),
1743     GNUNET_GETOPT_OPTION_END
1744   };
1745
1746   memset (&sh,
1747           0,
1748           sizeof (sh));
1749   xdg = getenv ("XDG_CONFIG_HOME");
1750   if (NULL != xdg)
1751     GNUNET_asprintf (&cfg_filename,
1752                      "%s%s%s",
1753                      xdg,
1754                      DIR_SEPARATOR_STR,
1755                      GNUNET_OS_project_data_get ()->config_file);
1756   else
1757     cfg_filename = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1758   sh.ready_confirm_fd = -1;
1759   sh.options = options;
1760   sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
1761   sh.service_init_cb = service_init_cb;
1762   sh.connect_cb = connect_cb;
1763   sh.disconnect_cb = disconnect_cb;
1764   sh.cb_cls = cls;
1765   if (NULL != handlers)
1766   {
1767     unsigned int i;
1768
1769     for (i=0;NULL != handlers[i].cb; i++) ;
1770     sh.handlers = GNUNET_new_array (i + 1,
1771                                      struct GNUNET_MQ_MessageHandler);
1772     GNUNET_memcpy (sh.handlers,
1773                    handlers,
1774                    i * sizeof (struct GNUNET_MQ_MessageHandler));
1775   }
1776   sh.service_name = service_name;
1777
1778   /* setup subsystems */
1779   loglev = NULL;
1780   logfile = NULL;
1781   opt_cfg_filename = NULL;
1782   do_daemonize = 0;
1783   ret = GNUNET_GETOPT_run (service_name,
1784                            service_options,
1785                            argc,
1786                            argv);
1787   if (GNUNET_SYSERR == ret)
1788     goto shutdown;
1789   if (GNUNET_NO == ret)
1790   {
1791     err = 0;
1792     goto shutdown;
1793   }
1794   if (GNUNET_OK != GNUNET_log_setup (service_name,
1795                                      loglev,
1796                                      logfile))
1797   {
1798     GNUNET_break (0);
1799     goto shutdown;
1800   }
1801   if (NULL == opt_cfg_filename)
1802     opt_cfg_filename = GNUNET_strdup (cfg_filename);
1803   if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_filename))
1804   {
1805     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg,
1806                                                     opt_cfg_filename))
1807     {
1808       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1809                   _("Malformed configuration file `%s', exit ...\n"),
1810                   opt_cfg_filename);
1811       goto shutdown;
1812     }
1813   }
1814   else
1815   {
1816     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg,
1817                                                     NULL))
1818     {
1819       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1820                   _("Malformed configuration, exit ...\n"));
1821       goto shutdown;
1822     }
1823     if (0 != strcmp (opt_cfg_filename,
1824                      cfg_filename))
1825       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1826                   _("Could not access configuration file `%s'\n"),
1827                   opt_cfg_filename);
1828   }
1829   if (GNUNET_OK != setup_service (&sh))
1830     goto shutdown;
1831   if ( (1 == do_daemonize) &&
1832        (GNUNET_OK != detach_terminal (&sh)) )
1833   {
1834     GNUNET_break (0);
1835     goto shutdown;
1836   }
1837   if (GNUNET_OK != set_user_id (&sh))
1838     goto shutdown;
1839   LOG (GNUNET_ERROR_TYPE_DEBUG,
1840        "Service `%s' runs with configuration from `%s'\n",
1841        service_name,
1842        opt_cfg_filename);
1843   if ((GNUNET_OK ==
1844        GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1845                                               "TESTING",
1846                                               "SKEW_OFFSET",
1847                                               &skew_offset)) &&
1848       (GNUNET_OK ==
1849        GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1850                                               "TESTING",
1851                                               "SKEW_VARIANCE",
1852                                               &skew_variance)))
1853   {
1854     clock_offset = skew_offset - skew_variance;
1855     GNUNET_TIME_set_offset (clock_offset);
1856     LOG (GNUNET_ERROR_TYPE_DEBUG,
1857          "Skewing clock by %dll ms\n",
1858          clock_offset);
1859   }
1860   GNUNET_RESOLVER_connect (sh.cfg);
1861
1862   /* actually run service */
1863   err = 0;
1864   GNUNET_SCHEDULER_run (&service_main,
1865                         &sh);
1866   /* shutdown */
1867   if (1 == do_daemonize)
1868     pid_file_delete (&sh);
1869
1870 shutdown:
1871   if (-1 != sh.ready_confirm_fd)
1872   {
1873     if (1 != WRITE (sh.ready_confirm_fd,
1874                     err ? "I" : "S",
1875                     1))
1876       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1877                     "write");
1878     GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
1879   }
1880 #if HAVE_MALLINFO
1881   {
1882     char *counter;
1883
1884     if ( (GNUNET_YES ==
1885           GNUNET_CONFIGURATION_have_value (sh.cfg,
1886                                            service_name,
1887                                            "GAUGER_HEAP")) &&
1888          (GNUNET_OK ==
1889           GNUNET_CONFIGURATION_get_value_string (sh.cfg,
1890                                                  service_name,
1891                                                  "GAUGER_HEAP",
1892                                                  &counter)) )
1893     {
1894       struct mallinfo mi;
1895
1896       mi = mallinfo ();
1897       GAUGER (service_name,
1898               counter,
1899               mi.usmblks,
1900               "blocks");
1901       GNUNET_free (counter);
1902     }
1903   }
1904 #endif
1905   teardown_service (&sh);
1906   GNUNET_free (sh.handlers);
1907   GNUNET_SPEEDUP_stop_ ();
1908   GNUNET_CONFIGURATION_destroy (cfg);
1909   GNUNET_free_non_null (logfile);
1910   GNUNET_free_non_null (loglev);
1911   GNUNET_free (cfg_filename);
1912   GNUNET_free_non_null (opt_cfg_filename);
1913
1914   return err ? GNUNET_SYSERR : sh.ret;
1915 }
1916
1917
1918 /**
1919  * Suspend accepting connections from the listen socket temporarily.
1920  * Resume activity using #GNUNET_SERVICE_resume.
1921  *
1922  * @param sh service to stop accepting connections.
1923  */
1924 void
1925 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
1926 {
1927   struct ServiceListenContext *slc;
1928
1929   for (slc = sh->slc_head; NULL != slc; slc = slc->next)
1930   {
1931     if (NULL != slc->listen_task)
1932     {
1933       GNUNET_SCHEDULER_cancel (slc->listen_task);
1934       slc->listen_task = NULL;
1935     }
1936   }
1937 }
1938
1939
1940 /**
1941  * Task run when we are ready to transmit data to the
1942  * client.
1943  *
1944  * @param cls the `struct GNUNET_SERVICE_Client *` to send to
1945  */
1946 static void
1947 do_send (void *cls)
1948 {
1949   struct GNUNET_SERVICE_Client *client = cls;
1950   ssize_t ret;
1951   size_t left;
1952   const char *buf;
1953
1954   client->send_task = NULL;
1955   buf = (const char *) client->msg;
1956   left = ntohs (client->msg->size) - client->msg_pos;
1957   ret = GNUNET_NETWORK_socket_send (client->sock,
1958                                     &buf[client->msg_pos],
1959                                     left);
1960   GNUNET_assert (ret <= (ssize_t) left);
1961   if (0 == ret)
1962   {
1963     GNUNET_MQ_inject_error (client->mq,
1964                             GNUNET_MQ_ERROR_WRITE);
1965     return;
1966   }
1967   if (-1 == ret)
1968   {
1969     if ( (EAGAIN == errno) ||
1970          (EINTR == errno) )
1971     {
1972       /* ignore */
1973       ret = 0;
1974     }
1975     else
1976     {
1977       if (EPIPE != errno)
1978         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1979                              "send");
1980       GNUNET_MQ_inject_error (client->mq,
1981                               GNUNET_MQ_ERROR_WRITE);
1982       return;
1983     }
1984   }
1985   if (0 == client->msg_pos)
1986   {
1987     GNUNET_MQ_impl_send_in_flight (client->mq);
1988   }
1989   client->msg_pos += ret;
1990   if (left > ret)
1991   {
1992     client->send_task
1993       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1994                                         client->sock,
1995                                         &do_send,
1996                                         client);
1997     return;
1998   }
1999   GNUNET_MQ_impl_send_continue (client->mq);
2000 }
2001
2002
2003 /**
2004  * Signature of functions implementing the sending functionality of a
2005  * message queue.
2006  *
2007  * @param mq the message queue
2008  * @param msg the message to send
2009  * @param impl_state our `struct GNUNET_SERVICE_Client *`
2010  */
2011 static void
2012 service_mq_send (struct GNUNET_MQ_Handle *mq,
2013                  const struct GNUNET_MessageHeader *msg,
2014                  void *impl_state)
2015 {
2016   struct GNUNET_SERVICE_Client *client = impl_state;
2017
2018   GNUNET_assert (NULL == client->send_task);
2019   client->msg = msg;
2020   client->msg_pos = 0;
2021   client->send_task
2022     = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2023                                       client->sock,
2024                                       &do_send,
2025                                       client);
2026 }
2027
2028
2029 /**
2030  * Implementation function that cancels the currently sent message.
2031  *
2032  * @param mq message queue
2033  * @param impl_state state specific to the implementation
2034  */
2035 static void
2036 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
2037                    void *impl_state)
2038 {
2039   struct GNUNET_SERVICE_Client *client = impl_state;
2040
2041   GNUNET_assert (0 == client->msg_pos);
2042   client->msg = NULL;
2043   GNUNET_SCHEDULER_cancel (client->send_task);
2044   client->send_task = NULL;
2045 }
2046
2047
2048 /**
2049  * Generic error handler, called with the appropriate
2050  * error code and the same closure specified at the creation of
2051  * the message queue.
2052  * Not every message queue implementation supports an error handler.
2053  *
2054  * @param cls closure with our `struct GNUNET_SERVICE_Client`
2055  * @param error error code
2056  */
2057 static void
2058 service_mq_error_handler (void *cls,
2059                           enum GNUNET_MQ_Error error)
2060 {
2061   struct GNUNET_SERVICE_Client *client = cls;
2062   struct GNUNET_SERVICE_Handle *sh = client->sh;
2063
2064   if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
2065        (GNUNET_NO == sh->require_found) )
2066   {
2067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2068                 "No handler for message of type %u found\n",
2069                 (unsigned int) client->warn_type);
2070     GNUNET_SERVICE_client_continue (client);
2071     return; /* ignore error */
2072   }
2073   GNUNET_SERVICE_client_drop (client);
2074 }
2075
2076
2077 /**
2078  * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
2079  *
2080  * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
2081  */
2082 static void
2083 warn_no_client_continue (void *cls)
2084 {
2085   struct GNUNET_SERVICE_Client *client = cls;
2086
2087   GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
2088   client->warn_task
2089     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2090                                     &warn_no_client_continue,
2091                                     client);
2092   LOG (GNUNET_ERROR_TYPE_WARNING,
2093        _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
2094        (unsigned int) client->warn_type,
2095        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
2096                                                GNUNET_YES));
2097 }
2098
2099
2100 /**
2101  * Functions with this signature are called whenever a
2102  * complete message is received by the tokenizer for a client.
2103  *
2104  * Do not call #GNUNET_MST_destroy() from within
2105  * the scope of this callback.
2106  *
2107  * @param cls closure with the `struct GNUNET_SERVICE_Client *`
2108  * @param message the actual message
2109  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
2110  */
2111 static int
2112 service_client_mst_cb (void *cls,
2113                        const struct GNUNET_MessageHeader *message)
2114 {
2115   struct GNUNET_SERVICE_Client *client = cls;
2116
2117   GNUNET_assert (GNUNET_NO == client->needs_continue);
2118   client->needs_continue = GNUNET_YES;
2119   client->warn_type = ntohs (message->type);
2120   client->warn_start = GNUNET_TIME_absolute_get ();
2121   GNUNET_assert (NULL == client->warn_task);
2122   client->warn_task
2123     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2124                                     &warn_no_client_continue,
2125                                     client);
2126   GNUNET_MQ_inject_message (client->mq,
2127                             message);
2128   if (NULL != client->drop_task)
2129     return GNUNET_SYSERR;
2130   return GNUNET_OK;
2131 }
2132
2133
2134 /**
2135  * A client sent us data. Receive and process it.  If we are done,
2136  * reschedule this task.
2137  *
2138  * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
2139  */
2140 static void
2141 service_client_recv (void *cls)
2142 {
2143   struct GNUNET_SERVICE_Client *client = cls;
2144   int ret;
2145
2146   client->recv_task = NULL;
2147   ret = GNUNET_MST_read (client->mst,
2148                          client->sock,
2149                          GNUNET_NO,
2150                          GNUNET_YES);
2151   if (GNUNET_SYSERR == ret)
2152   {
2153     /* client closed connection (or IO error) */
2154     if (NULL == client->drop_task)
2155     {
2156       GNUNET_assert (GNUNET_NO == client->needs_continue);
2157       GNUNET_SERVICE_client_drop (client);
2158     }
2159     return;
2160   }
2161   if (GNUNET_NO == ret)
2162     return; /* more messages in buffer, wait for application
2163                to be done processing */
2164   GNUNET_assert (GNUNET_OK == ret);
2165   if (GNUNET_YES == client->needs_continue)
2166     return;
2167   if (NULL != client->recv_task)
2168     return;
2169   /* MST needs more data, re-schedule read job */
2170   client->recv_task
2171     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2172                                      client->sock,
2173                                      &service_client_recv,
2174                                      client);
2175 }
2176
2177
2178 /**
2179  * We have successfully accepted a connection from a client.  Now
2180  * setup the client (with the scheduler) and tell the application.
2181  *
2182  * @param sh service that accepted the client
2183  * @param sock socket associated with the client
2184  */
2185 static void
2186 start_client (struct GNUNET_SERVICE_Handle *sh,
2187               struct GNUNET_NETWORK_Handle *csock)
2188 {
2189   struct GNUNET_SERVICE_Client *client;
2190
2191   client = GNUNET_new (struct GNUNET_SERVICE_Client);
2192   GNUNET_CONTAINER_DLL_insert (sh->clients_head,
2193                                sh->clients_tail,
2194                                client);
2195   client->sh = sh;
2196   client->sock = csock;
2197   client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
2198                                               NULL,
2199                                               &service_mq_cancel,
2200                                               client,
2201                                               sh->handlers,
2202                                               &service_mq_error_handler,
2203                                               client);
2204   client->mst = GNUNET_MST_create (&service_client_mst_cb,
2205                                    client);
2206   if (NULL != sh->connect_cb)
2207     client->user_context = sh->connect_cb (sh->cb_cls,
2208                                            client,
2209                                            client->mq);
2210   GNUNET_MQ_set_handlers_closure (client->mq,
2211                                   client->user_context);
2212   client->recv_task
2213     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2214                                      client->sock,
2215                                      &service_client_recv,
2216                                      client);
2217 }
2218
2219
2220 /**
2221  * Check if the given IP address is in the list of IP addresses.
2222  *
2223  * @param list a list of networks
2224  * @param add the IP to check (in network byte order)
2225  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2226  */
2227 static int
2228 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
2229                    const struct in_addr *add)
2230 {
2231   unsigned int i;
2232
2233   if (NULL == list)
2234     return GNUNET_NO;
2235   i = 0;
2236   while ( (0 != list[i].network.s_addr) ||
2237           (0 != list[i].netmask.s_addr) )
2238   {
2239     if ((add->s_addr & list[i].netmask.s_addr) ==
2240         (list[i].network.s_addr & list[i].netmask.s_addr))
2241       return GNUNET_YES;
2242     i++;
2243   }
2244   return GNUNET_NO;
2245 }
2246
2247
2248 /**
2249  * Check if the given IP address is in the list of IP addresses.
2250  *
2251  * @param list a list of networks
2252  * @param ip the IP to check (in network byte order)
2253  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2254  */
2255 static int
2256 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
2257                    const struct in6_addr *ip)
2258 {
2259   unsigned int i;
2260   unsigned int j;
2261   struct in6_addr zero;
2262
2263   if (NULL == list)
2264     return GNUNET_NO;
2265   memset (&zero,
2266           0,
2267           sizeof (struct in6_addr));
2268   i = 0;
2269 NEXT:
2270   while (0 != memcmp (&zero,
2271                       &list[i].network,
2272                       sizeof (struct in6_addr)))
2273   {
2274     for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
2275       if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
2276           (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
2277       {
2278         i++;
2279         goto NEXT;
2280       }
2281     return GNUNET_YES;
2282   }
2283   return GNUNET_NO;
2284 }
2285
2286
2287 /**
2288  * We have a client. Accept the incoming socket(s) (and reschedule
2289  * the listen task).
2290  *
2291  * @param cls the `struct ServiceListenContext` of the ready listen socket
2292  */
2293 static void
2294 accept_client (void *cls)
2295 {
2296   struct ServiceListenContext *slc = cls;
2297   struct GNUNET_SERVICE_Handle *sh = slc->sh;
2298
2299   slc->listen_task = NULL;
2300   while (1)
2301   {
2302     struct GNUNET_NETWORK_Handle *sock;
2303     const struct sockaddr_in *v4;
2304     const struct sockaddr_in6 *v6;
2305     struct sockaddr_storage sa;
2306     socklen_t addrlen;
2307     int ok;
2308
2309     addrlen = sizeof (sa);
2310     sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
2311                                          (struct sockaddr *) &sa,
2312                                          &addrlen);
2313     if (NULL == sock)
2314       break;
2315     switch (sa.ss_family)
2316     {
2317     case AF_INET:
2318       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2319       v4 = (const struct sockaddr_in *) &sa;
2320       ok = ( ( (NULL == sh->v4_allowed) ||
2321                (check_ipv4_listed (sh->v4_allowed,
2322                                    &v4->sin_addr))) &&
2323              ( (NULL == sh->v4_denied) ||
2324                (! check_ipv4_listed (sh->v4_denied,
2325                                      &v4->sin_addr)) ) );
2326       break;
2327     case AF_INET6:
2328       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2329       v6 = (const struct sockaddr_in6 *) &sa;
2330       ok = ( ( (NULL == sh->v6_allowed) ||
2331                (check_ipv6_listed (sh->v6_allowed,
2332                                    &v6->sin6_addr))) &&
2333              ( (NULL == sh->v6_denied) ||
2334                (! check_ipv6_listed (sh->v6_denied,
2335                                      &v6->sin6_addr)) ) );
2336       break;
2337 #ifndef WINDOWS
2338     case AF_UNIX:
2339       ok = GNUNET_OK;            /* controlled using file-system ACL now */
2340       break;
2341 #endif
2342     default:
2343       LOG (GNUNET_ERROR_TYPE_WARNING,
2344            _("Unknown address family %d\n"),
2345            sa.ss_family);
2346       return;
2347     }
2348     if (! ok)
2349     {
2350       LOG (GNUNET_ERROR_TYPE_DEBUG,
2351            "Service rejected incoming connection from %s due to policy.\n",
2352            GNUNET_a2s ((const struct sockaddr *) &sa,
2353                        addrlen));
2354       GNUNET_break (GNUNET_OK ==
2355                     GNUNET_NETWORK_socket_close (sock));
2356       continue;
2357     }
2358     LOG (GNUNET_ERROR_TYPE_DEBUG,
2359          "Service accepted incoming connection from %s.\n",
2360          GNUNET_a2s ((const struct sockaddr *) &sa,
2361                      addrlen));
2362     start_client (slc->sh,
2363                   sock);
2364   }
2365   slc->listen_task
2366     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2367                                      slc->listen_socket,
2368                                      &accept_client,
2369                                      slc);
2370 }
2371
2372
2373 /**
2374  * Resume accepting connections from the listen socket.
2375  *
2376  * @param sh service to resume accepting connections.
2377  */
2378 void
2379 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2380 {
2381   struct ServiceListenContext *slc;
2382
2383   for (slc = sh->slc_head; NULL != slc; slc = slc->next)
2384   {
2385     GNUNET_assert (NULL == slc->listen_task);
2386     slc->listen_task
2387       = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2388                                        slc->listen_socket,
2389                                        &accept_client,
2390                                        slc);
2391   }
2392 }
2393
2394
2395 /**
2396  * Task run to resume receiving data from the client after
2397  * the client called #GNUNET_SERVICE_client_continue().
2398  *
2399  * @param cls our `struct GNUNET_SERVICE_Client`
2400  */
2401 static void
2402 resume_client_receive (void *cls)
2403 {
2404   struct GNUNET_SERVICE_Client *c = cls;
2405   int ret;
2406
2407   c->recv_task = NULL;
2408   /* first, check if there is still something in the buffer */
2409   ret = GNUNET_MST_next (c->mst,
2410                          GNUNET_YES);
2411   if (GNUNET_SYSERR == ret)
2412   {
2413     GNUNET_break (0);
2414     GNUNET_SERVICE_client_drop (c);
2415     return;
2416   }
2417   if (GNUNET_NO == ret)
2418     return; /* done processing, wait for more later */
2419   GNUNET_assert (GNUNET_OK == ret);
2420   if (GNUNET_YES == c->needs_continue)
2421     return; /* #GNUNET_MST_next() did give a message to the client */
2422   /* need to receive more data from the network first */
2423   if (NULL != c->recv_task)
2424     return;
2425   c->recv_task
2426     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2427                                      c->sock,
2428                                      &service_client_recv,
2429                                      c);
2430 }
2431
2432
2433 /**
2434  * Continue receiving further messages from the given client.
2435  * Must be called after each message received.
2436  *
2437  * @param c the client to continue receiving from
2438  */
2439 void
2440 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2441 {
2442   GNUNET_assert (GNUNET_YES == c->needs_continue);
2443   GNUNET_assert (NULL == c->recv_task);
2444   c->needs_continue = GNUNET_NO;
2445   if (NULL != c->warn_task)
2446   {
2447     GNUNET_SCHEDULER_cancel (c->warn_task);
2448     c->warn_task = NULL;
2449   }
2450   c->recv_task
2451     = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2452                                 c);
2453 }
2454
2455
2456 /**
2457  * Disable the warning the server issues if a message is not
2458  * acknowledged in a timely fashion.  Use this call if a client is
2459  * intentionally delayed for a while.  Only applies to the current
2460  * message.
2461  *
2462  * @param c client for which to disable the warning
2463  */
2464 void
2465 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2466 {
2467   GNUNET_break (NULL != c->warn_task);
2468   if (NULL != c->warn_task)
2469   {
2470     GNUNET_SCHEDULER_cancel (c->warn_task);
2471     c->warn_task = NULL;
2472   }
2473 }
2474
2475
2476 /**
2477  * Asynchronously finish dropping the client.
2478  *
2479  * @param cls the `struct GNUNET_SERVICE_Client`.
2480  */
2481 static void
2482 finish_client_drop (void *cls)
2483 {
2484   struct GNUNET_SERVICE_Client *c = cls;
2485   struct GNUNET_SERVICE_Handle *sh = c->sh;
2486
2487   GNUNET_MST_destroy (c->mst);
2488   GNUNET_MQ_destroy (c->mq);
2489   if (GNUNET_NO == c->persist)
2490   {
2491     GNUNET_break (GNUNET_OK ==
2492                   GNUNET_NETWORK_socket_close (c->sock));
2493   }
2494   else
2495   {
2496     GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2497   }
2498   GNUNET_free (c);
2499   if ( (GNUNET_YES == sh->got_shutdown) &&
2500        (GNUNET_NO == have_non_monitor_clients (sh)) )
2501     GNUNET_SERVICE_shutdown (sh);
2502 }
2503
2504
2505 /**
2506  * Ask the server to disconnect from the given client.  This is the
2507  * same as returning #GNUNET_SYSERR within the check procedure when
2508  * handling a message, wexcept that it allows dropping of a client even
2509  * when not handling a message from that client.  The `disconnect_cb`
2510  * will be called on @a c even if the application closes the connection
2511  * using this function.
2512  *
2513  * @param c client to disconnect now
2514  */
2515 void
2516 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2517 {
2518   struct GNUNET_SERVICE_Handle *sh = c->sh;
2519
2520   if (NULL != c->drop_task)
2521   {
2522     /* asked to drop twice! */
2523     GNUNET_break (0);
2524     return;
2525   }
2526   GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2527                                sh->clients_tail,
2528                                c);
2529   if (NULL != sh->disconnect_cb)
2530     sh->disconnect_cb (sh->cb_cls,
2531                        c,
2532                        c->user_context);
2533   if (NULL != c->warn_task)
2534   {
2535     GNUNET_SCHEDULER_cancel (c->warn_task);
2536     c->warn_task = NULL;
2537   }
2538   if (NULL != c->recv_task)
2539   {
2540     GNUNET_SCHEDULER_cancel (c->recv_task);
2541     c->recv_task = NULL;
2542   }
2543   if (NULL != c->send_task)
2544   {
2545     GNUNET_SCHEDULER_cancel (c->send_task);
2546     c->send_task = NULL;
2547   }
2548   c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2549                                            c);
2550 }
2551
2552
2553 /**
2554  * Explicitly stops the service.
2555  *
2556  * @param sh server to shutdown
2557  */
2558 void
2559 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2560 {
2561   struct GNUNET_SERVICE_Client *client;
2562
2563   GNUNET_SERVICE_suspend (sh);
2564   sh->got_shutdown = GNUNET_NO;
2565   while (NULL != (client = sh->clients_head))
2566     GNUNET_SERVICE_client_drop (client);
2567 }
2568
2569
2570 /**
2571  * Set the 'monitor' flag on this client.  Clients which have been
2572  * marked as 'monitors' won't prevent the server from shutting down
2573  * once #GNUNET_SERVICE_stop_listening() has been invoked.  The idea is
2574  * that for "normal" clients we likely want to allow them to process
2575  * their requests; however, monitor-clients are likely to 'never'
2576  * disconnect during shutdown and thus will not be considered when
2577  * determining if the server should continue to exist after
2578  * shutdown has been triggered.
2579  *
2580  * @param c client to mark as a monitor
2581  */
2582 void
2583 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2584 {
2585   c->is_monitor = GNUNET_YES;
2586   if ( (GNUNET_YES == c->sh->got_shutdown) &&
2587        (GNUNET_NO == have_non_monitor_clients (c->sh)) )
2588     GNUNET_SERVICE_shutdown (c->sh);
2589 }
2590
2591
2592 /**
2593  * Set the persist option on this client.  Indicates that the
2594  * underlying socket or fd should never really be closed.  Used for
2595  * indicating process death.
2596  *
2597  * @param c client to persist the socket (never to be closed)
2598  */
2599 void
2600 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2601 {
2602   c->persist = GNUNET_YES;
2603 }
2604
2605
2606 /**
2607  * Obtain the message queue of @a c.  Convenience function.
2608  *
2609  * @param c the client to continue receiving from
2610  * @return the message queue of @a c
2611  */
2612 struct GNUNET_MQ_Handle *
2613 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2614 {
2615   return c->mq;
2616 }
2617
2618
2619 /* end of service_new.c */