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