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