new convenience function to do operations on a configuration object to avoid repetiti...
[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 ==
1819         GNUNET_CONFIGURATION_load (cfg,
1820                                    opt_cfg_filename))
1821     {
1822       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1823                   _("Malformed configuration file `%s', exit ...\n"),
1824                   opt_cfg_filename);
1825       goto shutdown;
1826     }
1827   }
1828   else
1829   {
1830     if (GNUNET_SYSERR ==
1831         GNUNET_CONFIGURATION_load (cfg,
1832                                    NULL))
1833     {
1834       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1835                   _("Malformed configuration, exit ...\n"));
1836       goto shutdown;
1837     }
1838     if (0 != strcmp (opt_cfg_filename,
1839                      cfg_filename))
1840       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1841                   _("Could not access configuration file `%s'\n"),
1842                   opt_cfg_filename);
1843   }
1844   if (GNUNET_OK != setup_service (&sh))
1845     goto shutdown;
1846   if ( (1 == do_daemonize) &&
1847        (GNUNET_OK != detach_terminal (&sh)) )
1848   {
1849     GNUNET_break (0);
1850     goto shutdown;
1851   }
1852   if (GNUNET_OK != set_user_id (&sh))
1853     goto shutdown;
1854   LOG (GNUNET_ERROR_TYPE_DEBUG,
1855        "Service `%s' runs with configuration from `%s'\n",
1856        service_name,
1857        opt_cfg_filename);
1858   if ((GNUNET_OK ==
1859        GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1860                                               "TESTING",
1861                                               "SKEW_OFFSET",
1862                                               &skew_offset)) &&
1863       (GNUNET_OK ==
1864        GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1865                                               "TESTING",
1866                                               "SKEW_VARIANCE",
1867                                               &skew_variance)))
1868   {
1869     clock_offset = skew_offset - skew_variance;
1870     GNUNET_TIME_set_offset (clock_offset);
1871     LOG (GNUNET_ERROR_TYPE_DEBUG,
1872          "Skewing clock by %dll ms\n",
1873          clock_offset);
1874   }
1875   GNUNET_RESOLVER_connect (sh.cfg);
1876
1877   /* actually run service */
1878   err = 0;
1879   GNUNET_SCHEDULER_run (&service_main,
1880                         &sh);
1881   /* shutdown */
1882   if (1 == do_daemonize)
1883     pid_file_delete (&sh);
1884
1885 shutdown:
1886   if (-1 != sh.ready_confirm_fd)
1887   {
1888     if (1 != WRITE (sh.ready_confirm_fd,
1889                     err ? "I" : "S",
1890                     1))
1891       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1892                     "write");
1893     GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
1894   }
1895 #if HAVE_MALLINFO
1896   {
1897     char *counter;
1898
1899     if ( (GNUNET_YES ==
1900           GNUNET_CONFIGURATION_have_value (sh.cfg,
1901                                            service_name,
1902                                            "GAUGER_HEAP")) &&
1903          (GNUNET_OK ==
1904           GNUNET_CONFIGURATION_get_value_string (sh.cfg,
1905                                                  service_name,
1906                                                  "GAUGER_HEAP",
1907                                                  &counter)) )
1908     {
1909       struct mallinfo mi;
1910
1911       mi = mallinfo ();
1912       GAUGER (service_name,
1913               counter,
1914               mi.usmblks,
1915               "blocks");
1916       GNUNET_free (counter);
1917     }
1918   }
1919 #endif
1920   teardown_service (&sh);
1921   GNUNET_free_non_null (sh.handlers);
1922   GNUNET_SPEEDUP_stop_ ();
1923   GNUNET_CONFIGURATION_destroy (cfg);
1924   GNUNET_free_non_null (logfile);
1925   GNUNET_free_non_null (loglev);
1926   GNUNET_free (cfg_filename);
1927   GNUNET_free_non_null (opt_cfg_filename);
1928
1929   return err ? GNUNET_SYSERR : sh.ret;
1930 }
1931
1932
1933 /**
1934  * Suspend accepting connections from the listen socket temporarily.
1935  * Resume activity using #GNUNET_SERVICE_resume.
1936  *
1937  * @param sh service to stop accepting connections.
1938  */
1939 void
1940 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
1941 {
1942   struct ServiceListenContext *slc;
1943
1944   for (slc = sh->slc_head; NULL != slc; slc = slc->next)
1945   {
1946     if (NULL != slc->listen_task)
1947     {
1948       GNUNET_SCHEDULER_cancel (slc->listen_task);
1949       slc->listen_task = NULL;
1950     }
1951   }
1952 }
1953
1954
1955 /**
1956  * Task run when we are ready to transmit data to the
1957  * client.
1958  *
1959  * @param cls the `struct GNUNET_SERVICE_Client *` to send to
1960  */
1961 static void
1962 do_send (void *cls)
1963 {
1964   struct GNUNET_SERVICE_Client *client = cls;
1965   ssize_t ret;
1966   size_t left;
1967   const char *buf;
1968
1969   LOG (GNUNET_ERROR_TYPE_DEBUG,
1970        "service: sending message with type %u",
1971        ntohs(client->msg->type));
1972
1973
1974   client->send_task = NULL;
1975   buf = (const char *) client->msg;
1976   left = ntohs (client->msg->size) - client->msg_pos;
1977   ret = GNUNET_NETWORK_socket_send (client->sock,
1978                                     &buf[client->msg_pos],
1979                                     left);
1980   GNUNET_assert (ret <= (ssize_t) left);
1981   if (0 == ret)
1982   {
1983     LOG (GNUNET_ERROR_TYPE_DEBUG,
1984          "no data send");
1985     GNUNET_MQ_inject_error (client->mq,
1986                             GNUNET_MQ_ERROR_WRITE);
1987     return;
1988   }
1989   if (-1 == ret)
1990   {
1991     if ( (EAGAIN == errno) ||
1992          (EINTR == errno) )
1993     {
1994       /* ignore */
1995       ret = 0;
1996     }
1997     else
1998     {
1999       if (EPIPE != errno)
2000         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2001                              "send");
2002       LOG (GNUNET_ERROR_TYPE_DEBUG,
2003            "socket send returned with error code %i",
2004            errno);
2005       GNUNET_MQ_inject_error (client->mq,
2006                               GNUNET_MQ_ERROR_WRITE);
2007       return;
2008     }
2009   }
2010   if (0 == client->msg_pos)
2011   {
2012     GNUNET_MQ_impl_send_in_flight (client->mq);
2013   }
2014   client->msg_pos += ret;
2015   if (left > (size_t) ret)
2016   {
2017     GNUNET_assert (NULL == client->drop_task);
2018     client->send_task
2019       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2020                                         client->sock,
2021                                         &do_send,
2022                                         client);
2023     return;
2024   }
2025   GNUNET_MQ_impl_send_continue (client->mq);
2026 }
2027
2028
2029 /**
2030  * Signature of functions implementing the sending functionality of a
2031  * message queue.
2032  *
2033  * @param mq the message queue
2034  * @param msg the message to send
2035  * @param impl_state our `struct GNUNET_SERVICE_Client *`
2036  */
2037 static void
2038 service_mq_send (struct GNUNET_MQ_Handle *mq,
2039                  const struct GNUNET_MessageHeader *msg,
2040                  void *impl_state)
2041 {
2042   struct GNUNET_SERVICE_Client *client = impl_state;
2043
2044   (void) mq;
2045   if (NULL != client->drop_task)
2046     return; /* we're going down right now, do not try to send */
2047   GNUNET_assert (NULL == client->send_task);
2048   LOG (GNUNET_ERROR_TYPE_DEBUG,
2049        "Sending message of type %u and size %u to client\n",
2050        ntohs (msg->type),
2051        ntohs (msg->size));
2052   client->msg = msg;
2053   client->msg_pos = 0;
2054   client->send_task
2055     = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2056                                       client->sock,
2057                                       &do_send,
2058                                       client);
2059 }
2060
2061
2062 /**
2063  * Implementation function that cancels the currently sent message.
2064  *
2065  * @param mq message queue
2066  * @param impl_state state specific to the implementation
2067  */
2068 static void
2069 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
2070                    void *impl_state)
2071 {
2072   struct GNUNET_SERVICE_Client *client = impl_state;
2073
2074   (void) mq;
2075   GNUNET_assert (0 == client->msg_pos);
2076   client->msg = NULL;
2077   GNUNET_SCHEDULER_cancel (client->send_task);
2078   client->send_task = NULL;
2079 }
2080
2081
2082 /**
2083  * Generic error handler, called with the appropriate
2084  * error code and the same closure specified at the creation of
2085  * the message queue.
2086  * Not every message queue implementation supports an error handler.
2087  *
2088  * @param cls closure with our `struct GNUNET_SERVICE_Client`
2089  * @param error error code
2090  */
2091 static void
2092 service_mq_error_handler (void *cls,
2093                           enum GNUNET_MQ_Error error)
2094 {
2095   struct GNUNET_SERVICE_Client *client = cls;
2096   struct GNUNET_SERVICE_Handle *sh = client->sh;
2097
2098   if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
2099        (GNUNET_NO == sh->require_found) )
2100   {
2101     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102                 "No handler for message of type %u found\n",
2103                 (unsigned int) client->warn_type);
2104     GNUNET_SERVICE_client_continue (client);
2105     return; /* ignore error */
2106   }
2107   GNUNET_SERVICE_client_drop (client);
2108 }
2109
2110
2111 /**
2112  * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
2113  *
2114  * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
2115  */
2116 static void
2117 warn_no_client_continue (void *cls)
2118 {
2119   struct GNUNET_SERVICE_Client *client = cls;
2120
2121   GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
2122   client->warn_task
2123     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2124                                     &warn_no_client_continue,
2125                                     client);
2126   LOG (GNUNET_ERROR_TYPE_WARNING,
2127        _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
2128        (unsigned int) client->warn_type,
2129        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
2130                                                GNUNET_YES));
2131 }
2132
2133
2134 /**
2135  * Functions with this signature are called whenever a
2136  * complete message is received by the tokenizer for a client.
2137  *
2138  * Do not call #GNUNET_MST_destroy() from within
2139  * the scope of this callback.
2140  *
2141  * @param cls closure with the `struct GNUNET_SERVICE_Client *`
2142  * @param message the actual message
2143  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
2144  */
2145 static int
2146 service_client_mst_cb (void *cls,
2147                        const struct GNUNET_MessageHeader *message)
2148 {
2149   struct GNUNET_SERVICE_Client *client = cls;
2150
2151   LOG (GNUNET_ERROR_TYPE_DEBUG,
2152        "Received message of type %u and size %u from client\n",
2153        ntohs (message->type),
2154        ntohs (message->size));
2155   GNUNET_assert (GNUNET_NO == client->needs_continue);
2156   client->needs_continue = GNUNET_YES;
2157   client->warn_type = ntohs (message->type);
2158   client->warn_start = GNUNET_TIME_absolute_get ();
2159   GNUNET_assert (NULL == client->warn_task);
2160   client->warn_task
2161     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2162                                     &warn_no_client_continue,
2163                                     client);
2164   GNUNET_MQ_inject_message (client->mq,
2165                             message);
2166   if (NULL != client->drop_task)
2167     return GNUNET_SYSERR;
2168   return GNUNET_OK;
2169 }
2170
2171
2172 /**
2173  * A client sent us data. Receive and process it.  If we are done,
2174  * reschedule this task.
2175  *
2176  * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
2177  */
2178 static void
2179 service_client_recv (void *cls)
2180 {
2181   struct GNUNET_SERVICE_Client *client = cls;
2182   int ret;
2183
2184   client->recv_task = NULL;
2185   ret = GNUNET_MST_read (client->mst,
2186                          client->sock,
2187                          GNUNET_NO,
2188                          GNUNET_YES);
2189   if (GNUNET_SYSERR == ret)
2190   {
2191     /* client closed connection (or IO error) */
2192     if (NULL == client->drop_task)
2193     {
2194       GNUNET_assert (GNUNET_NO == client->needs_continue);
2195       GNUNET_SERVICE_client_drop (client);
2196     }
2197     return;
2198   }
2199   if (GNUNET_NO == ret)
2200     return; /* more messages in buffer, wait for application
2201                to be done processing */
2202   GNUNET_assert (GNUNET_OK == ret);
2203   if (GNUNET_YES == client->needs_continue)
2204     return;
2205   if (NULL != client->recv_task)
2206     return;
2207   /* MST needs more data, re-schedule read job */
2208   client->recv_task
2209     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2210                                      client->sock,
2211                                      &service_client_recv,
2212                                      client);
2213 }
2214
2215
2216 /**
2217  * We have successfully accepted a connection from a client.  Now
2218  * setup the client (with the scheduler) and tell the application.
2219  *
2220  * @param sh service that accepted the client
2221  * @param sock socket associated with the client
2222  */
2223 static void
2224 start_client (struct GNUNET_SERVICE_Handle *sh,
2225               struct GNUNET_NETWORK_Handle *csock)
2226 {
2227   struct GNUNET_SERVICE_Client *client;
2228
2229   client = GNUNET_new (struct GNUNET_SERVICE_Client);
2230   GNUNET_CONTAINER_DLL_insert (sh->clients_head,
2231                                sh->clients_tail,
2232                                client);
2233   client->sh = sh;
2234   client->sock = csock;
2235   client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
2236                                               NULL,
2237                                               &service_mq_cancel,
2238                                               client,
2239                                               sh->handlers,
2240                                               &service_mq_error_handler,
2241                                               client);
2242   client->mst = GNUNET_MST_create (&service_client_mst_cb,
2243                                    client);
2244   if (NULL != sh->connect_cb)
2245     client->user_context = sh->connect_cb (sh->cb_cls,
2246                                            client,
2247                                            client->mq);
2248   GNUNET_MQ_set_handlers_closure (client->mq,
2249                                   client->user_context);
2250   client->recv_task
2251     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2252                                      client->sock,
2253                                      &service_client_recv,
2254                                      client);
2255 }
2256
2257
2258 /**
2259  * Check if the given IP address is in the list of IP addresses.
2260  *
2261  * @param list a list of networks
2262  * @param add the IP to check (in network byte order)
2263  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2264  */
2265 static int
2266 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
2267                    const struct in_addr *add)
2268 {
2269   unsigned int i;
2270
2271   if (NULL == list)
2272     return GNUNET_NO;
2273   i = 0;
2274   while ( (0 != list[i].network.s_addr) ||
2275           (0 != list[i].netmask.s_addr) )
2276   {
2277     if ((add->s_addr & list[i].netmask.s_addr) ==
2278         (list[i].network.s_addr & list[i].netmask.s_addr))
2279       return GNUNET_YES;
2280     i++;
2281   }
2282   return GNUNET_NO;
2283 }
2284
2285
2286 /**
2287  * Check if the given IP address is in the list of IP addresses.
2288  *
2289  * @param list a list of networks
2290  * @param ip the IP to check (in network byte order)
2291  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2292  */
2293 static int
2294 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
2295                    const struct in6_addr *ip)
2296 {
2297   unsigned int i;
2298   unsigned int j;
2299   struct in6_addr zero;
2300
2301   if (NULL == list)
2302     return GNUNET_NO;
2303   memset (&zero,
2304           0,
2305           sizeof (struct in6_addr));
2306   i = 0;
2307 NEXT:
2308   while (0 != memcmp (&zero,
2309                       &list[i].network,
2310                       sizeof (struct in6_addr)))
2311   {
2312     for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
2313       if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
2314           (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
2315       {
2316         i++;
2317         goto NEXT;
2318       }
2319     return GNUNET_YES;
2320   }
2321   return GNUNET_NO;
2322 }
2323
2324
2325 /**
2326  * We have a client. Accept the incoming socket(s) (and reschedule
2327  * the listen task).
2328  *
2329  * @param cls the `struct ServiceListenContext` of the ready listen socket
2330  */
2331 static void
2332 accept_client (void *cls)
2333 {
2334   struct ServiceListenContext *slc = cls;
2335   struct GNUNET_SERVICE_Handle *sh = slc->sh;
2336
2337   slc->listen_task = NULL;
2338   while (1)
2339   {
2340     struct GNUNET_NETWORK_Handle *sock;
2341     const struct sockaddr_in *v4;
2342     const struct sockaddr_in6 *v6;
2343     struct sockaddr_storage sa;
2344     socklen_t addrlen;
2345     int ok;
2346
2347     addrlen = sizeof (sa);
2348     sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
2349                                          (struct sockaddr *) &sa,
2350                                          &addrlen);
2351     if (NULL == sock)
2352       break;
2353     switch (sa.ss_family)
2354     {
2355     case AF_INET:
2356       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2357       v4 = (const struct sockaddr_in *) &sa;
2358       ok = ( ( (NULL == sh->v4_allowed) ||
2359                (check_ipv4_listed (sh->v4_allowed,
2360                                    &v4->sin_addr))) &&
2361              ( (NULL == sh->v4_denied) ||
2362                (! check_ipv4_listed (sh->v4_denied,
2363                                      &v4->sin_addr)) ) );
2364       break;
2365     case AF_INET6:
2366       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2367       v6 = (const struct sockaddr_in6 *) &sa;
2368       ok = ( ( (NULL == sh->v6_allowed) ||
2369                (check_ipv6_listed (sh->v6_allowed,
2370                                    &v6->sin6_addr))) &&
2371              ( (NULL == sh->v6_denied) ||
2372                (! check_ipv6_listed (sh->v6_denied,
2373                                      &v6->sin6_addr)) ) );
2374       break;
2375 #ifndef WINDOWS
2376     case AF_UNIX:
2377       ok = GNUNET_OK;            /* controlled using file-system ACL now */
2378       break;
2379 #endif
2380     default:
2381       LOG (GNUNET_ERROR_TYPE_WARNING,
2382            _("Unknown address family %d\n"),
2383            sa.ss_family);
2384       return;
2385     }
2386     if (! ok)
2387     {
2388       LOG (GNUNET_ERROR_TYPE_DEBUG,
2389            "Service rejected incoming connection from %s due to policy.\n",
2390            GNUNET_a2s ((const struct sockaddr *) &sa,
2391                        addrlen));
2392       GNUNET_break (GNUNET_OK ==
2393                     GNUNET_NETWORK_socket_close (sock));
2394       continue;
2395     }
2396     LOG (GNUNET_ERROR_TYPE_DEBUG,
2397          "Service accepted incoming connection from %s.\n",
2398          GNUNET_a2s ((const struct sockaddr *) &sa,
2399                      addrlen));
2400     start_client (slc->sh,
2401                   sock);
2402   }
2403   slc->listen_task
2404     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2405                                      slc->listen_socket,
2406                                      &accept_client,
2407                                      slc);
2408 }
2409
2410
2411 /**
2412  * Resume accepting connections from the listen socket.
2413  *
2414  * @param sh service to resume accepting connections.
2415  */
2416 void
2417 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2418 {
2419   struct ServiceListenContext *slc;
2420
2421   for (slc = sh->slc_head; NULL != slc; slc = slc->next)
2422   {
2423     GNUNET_assert (NULL == slc->listen_task);
2424     slc->listen_task
2425       = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2426                                        slc->listen_socket,
2427                                        &accept_client,
2428                                        slc);
2429   }
2430 }
2431
2432
2433 /**
2434  * Task run to resume receiving data from the client after
2435  * the client called #GNUNET_SERVICE_client_continue().
2436  *
2437  * @param cls our `struct GNUNET_SERVICE_Client`
2438  */
2439 static void
2440 resume_client_receive (void *cls)
2441 {
2442   struct GNUNET_SERVICE_Client *c = cls;
2443   int ret;
2444
2445   c->recv_task = NULL;
2446   /* first, check if there is still something in the buffer */
2447   ret = GNUNET_MST_next (c->mst,
2448                          GNUNET_YES);
2449   if (GNUNET_SYSERR == ret)
2450   {
2451     if (NULL == c->drop_task)
2452       GNUNET_SERVICE_client_drop (c);
2453     return;
2454   }
2455   if (GNUNET_NO == ret)
2456     return; /* done processing, wait for more later */
2457   GNUNET_assert (GNUNET_OK == ret);
2458   if (GNUNET_YES == c->needs_continue)
2459     return; /* #GNUNET_MST_next() did give a message to the client */
2460   /* need to receive more data from the network first */
2461   if (NULL != c->recv_task)
2462     return;
2463   c->recv_task
2464     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2465                                      c->sock,
2466                                      &service_client_recv,
2467                                      c);
2468 }
2469
2470
2471 /**
2472  * Continue receiving further messages from the given client.
2473  * Must be called after each message received.
2474  *
2475  * @param c the client to continue receiving from
2476  */
2477 void
2478 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2479 {
2480   GNUNET_assert (NULL == c->drop_task);
2481   GNUNET_assert (GNUNET_YES == c->needs_continue);
2482   GNUNET_assert (NULL == c->recv_task);
2483   c->needs_continue = GNUNET_NO;
2484   if (NULL != c->warn_task)
2485   {
2486     GNUNET_SCHEDULER_cancel (c->warn_task);
2487     c->warn_task = NULL;
2488   }
2489   c->recv_task
2490     = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2491                                 c);
2492 }
2493
2494
2495 /**
2496  * Disable the warning the server issues if a message is not
2497  * acknowledged in a timely fashion.  Use this call if a client is
2498  * intentionally delayed for a while.  Only applies to the current
2499  * message.
2500  *
2501  * @param c client for which to disable the warning
2502  */
2503 void
2504 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2505 {
2506   GNUNET_break (NULL != c->warn_task);
2507   if (NULL != c->warn_task)
2508   {
2509     GNUNET_SCHEDULER_cancel (c->warn_task);
2510     c->warn_task = NULL;
2511   }
2512 }
2513
2514
2515 /**
2516  * Asynchronously finish dropping the client.
2517  *
2518  * @param cls the `struct GNUNET_SERVICE_Client`.
2519  */
2520 static void
2521 finish_client_drop (void *cls)
2522 {
2523   struct GNUNET_SERVICE_Client *c = cls;
2524   struct GNUNET_SERVICE_Handle *sh = c->sh;
2525
2526   c->drop_task = NULL;
2527   GNUNET_assert (NULL == c->send_task);
2528   GNUNET_assert (NULL == c->recv_task);
2529   GNUNET_assert (NULL == c->warn_task);
2530   GNUNET_MST_destroy (c->mst);
2531   GNUNET_MQ_destroy (c->mq);
2532   if (GNUNET_NO == c->persist)
2533   {
2534     GNUNET_break (GNUNET_OK ==
2535                   GNUNET_NETWORK_socket_close (c->sock));
2536   }
2537   else
2538   {
2539     GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2540   }
2541   GNUNET_free (c);
2542   if ( (GNUNET_YES == sh->got_shutdown) &&
2543        (GNUNET_NO == have_non_monitor_clients (sh)) )
2544     GNUNET_SERVICE_shutdown (sh);
2545 }
2546
2547
2548 /**
2549  * Ask the server to disconnect from the given client.  This is the
2550  * same as returning #GNUNET_SYSERR within the check procedure when
2551  * handling a message, wexcept that it allows dropping of a client even
2552  * when not handling a message from that client.  The `disconnect_cb`
2553  * will be called on @a c even if the application closes the connection
2554  * using this function.
2555  *
2556  * @param c client to disconnect now
2557  */
2558 void
2559 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2560 {
2561   struct GNUNET_SERVICE_Handle *sh = c->sh;
2562
2563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564               "Client dropped: %p (MQ: %p)\n",
2565               c,
2566               c->mq);
2567
2568 #if EXECINFO
2569   void *backtrace_array[MAX_TRACE_DEPTH];
2570   int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2571     char **backtrace_strings =
2572         backtrace_symbols (backtrace_array,
2573          t->num_backtrace_strings);
2574     for (unsigned int i = 0; i < num_backtrace_strings; i++)
2575       LOG (GNUNET_ERROR_TYPE_DEBUG,
2576      "client drop trace %u: %s\n",
2577      i,
2578      backtrace_strings[i]);
2579 #endif
2580
2581   if (NULL != c->drop_task)
2582   {
2583     /* asked to drop twice! */
2584     GNUNET_assert (0);
2585     return;
2586   }
2587   GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2588                                sh->clients_tail,
2589                                c);
2590   if (NULL != sh->disconnect_cb)
2591     sh->disconnect_cb (sh->cb_cls,
2592                        c,
2593                        c->user_context);
2594   if (NULL != c->warn_task)
2595   {
2596     GNUNET_SCHEDULER_cancel (c->warn_task);
2597     c->warn_task = NULL;
2598   }
2599   if (NULL != c->recv_task)
2600   {
2601     GNUNET_SCHEDULER_cancel (c->recv_task);
2602     c->recv_task = NULL;
2603   }
2604   if (NULL != c->send_task)
2605   {
2606     GNUNET_SCHEDULER_cancel (c->send_task);
2607     c->send_task = NULL;
2608   }
2609   c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2610                                            c);
2611 }
2612
2613
2614 /**
2615  * Explicitly stops the service.
2616  *
2617  * @param sh server to shutdown
2618  */
2619 void
2620 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2621 {
2622   struct GNUNET_SERVICE_Client *client;
2623
2624   GNUNET_SERVICE_suspend (sh);
2625   sh->got_shutdown = GNUNET_NO;
2626   while (NULL != (client = sh->clients_head))
2627     GNUNET_SERVICE_client_drop (client);
2628 }
2629
2630
2631 /**
2632  * Set the 'monitor' flag on this client.  Clients which have been
2633  * marked as 'monitors' won't prevent the server from shutting down
2634  * once #GNUNET_SERVICE_stop_listening() has been invoked.  The idea is
2635  * that for "normal" clients we likely want to allow them to process
2636  * their requests; however, monitor-clients are likely to 'never'
2637  * disconnect during shutdown and thus will not be considered when
2638  * determining if the server should continue to exist after
2639  * shutdown has been triggered.
2640  *
2641  * @param c client to mark as a monitor
2642  */
2643 void
2644 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2645 {
2646   c->is_monitor = GNUNET_YES;
2647   if ( (GNUNET_YES == c->sh->got_shutdown) &&
2648        (GNUNET_NO == have_non_monitor_clients (c->sh)) )
2649     GNUNET_SERVICE_shutdown (c->sh);
2650 }
2651
2652
2653 /**
2654  * Set the persist option on this client.  Indicates that the
2655  * underlying socket or fd should never really be closed.  Used for
2656  * indicating process death.
2657  *
2658  * @param c client to persist the socket (never to be closed)
2659  */
2660 void
2661 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2662 {
2663   c->persist = GNUNET_YES;
2664 }
2665
2666
2667 /**
2668  * Obtain the message queue of @a c.  Convenience function.
2669  *
2670  * @param c the client to continue receiving from
2671  * @return the message queue of @a c
2672  */
2673 struct GNUNET_MQ_Handle *
2674 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2675 {
2676   return c->mq;
2677 }
2678
2679
2680 /* end of service_new.c */