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