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