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