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