small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[oweals/gnunet.git] / src / util / server.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      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      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/server.c
23  * @brief library for building GNUnet network servers
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
32
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
34
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
36
37
38 /**
39  * List of arrays of message handlers.
40  */
41 struct HandlerList
42 {
43   /**
44    * This is a linked list.
45    */
46   struct HandlerList *next;
47
48   /**
49    * NULL-terminated array of handlers.
50    */
51   const struct GNUNET_SERVER_MessageHandler *handlers;
52 };
53
54
55 /**
56  * List of arrays of message handlers.
57  */
58 struct NotifyList
59 {
60   /**
61    * This is a doubly linked list.
62    */
63   struct NotifyList *next;
64
65   /**
66    * This is a doubly linked list.
67    */
68   struct NotifyList *prev;
69
70   /**
71    * Function to call.
72    */
73   GNUNET_SERVER_DisconnectCallback callback;
74
75   /**
76    * Closure for callback.
77    */
78   void *callback_cls;
79 };
80
81
82 /**
83  * @brief handle for a server
84  */
85 struct GNUNET_SERVER_Handle
86 {
87   /**
88    * List of handlers for incoming messages.
89    */
90   struct HandlerList *handlers;
91
92   /**
93    * Head of list of our current clients.
94    */
95   struct GNUNET_SERVER_Client *clients_head;
96
97   /**
98    * Head of list of our current clients.
99    */
100   struct GNUNET_SERVER_Client *clients_tail;
101
102   /**
103    * Head of linked list of functions to call on disconnects by clients.
104    */
105   struct NotifyList *disconnect_notify_list_head;
106
107   /**
108    * Tail of linked list of functions to call on disconnects by clients.
109    */
110   struct NotifyList *disconnect_notify_list_tail;
111
112   /**
113    * Head of linked list of functions to call on connects by clients.
114    */
115   struct NotifyList *connect_notify_list_head;
116
117   /**
118    * Tail of linked list of functions to call on connects by clients.
119    */
120   struct NotifyList *connect_notify_list_tail;
121
122   /**
123    * Function to call for access control.
124    */
125   GNUNET_CONNECTION_AccessCheck access_cb;
126
127   /**
128    * Closure for @e access_cb.
129    */
130   void *access_cb_cls;
131
132   /**
133    * NULL-terminated array of sockets used to listen for new
134    * connections.
135    */
136   struct GNUNET_NETWORK_Handle **listen_sockets;
137
138   /**
139    * After how long should an idle connection time
140    * out (on write).
141    */
142   struct GNUNET_TIME_Relative idle_timeout;
143
144   /**
145    * Task scheduled to do the listening.
146    */
147   struct GNUNET_SCHEDULER_Task * listen_task;
148
149   /**
150    * Alternative function to create a MST instance.
151    */
152   GNUNET_SERVER_MstCreateCallback mst_create;
153
154   /**
155    * Alternative function to destroy a MST instance.
156    */
157   GNUNET_SERVER_MstDestroyCallback mst_destroy;
158
159   /**
160    * Alternative function to give data to a MST instance.
161    */
162   GNUNET_SERVER_MstReceiveCallback mst_receive;
163
164   /**
165    * Closure for 'mst_'-callbacks.
166    */
167   void *mst_cls;
168
169   /**
170    * Do we ignore messages of types that we do not understand or do we
171    * require that a handler is found (and if not kill the connection)?
172    */
173   int require_found;
174
175   /**
176    * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177    * all non-monitor clients to disconnect before we call
178    * #GNUNET_SERVER_destroy.  See test_monitor_clients().  Set to
179    * #GNUNET_SYSERR once the final destroy task has been scheduled
180    * (we cannot run it in the same task).
181    */
182   int in_soft_shutdown;
183 };
184
185
186 /**
187  * Handle server returns for aborting transmission to a client.
188  */
189 struct GNUNET_SERVER_TransmitHandle
190 {
191   /**
192    * Function to call to get the message.
193    */
194   GNUNET_CONNECTION_TransmitReadyNotify callback;
195
196   /**
197    * Closure for @e callback
198    */
199   void *callback_cls;
200
201   /**
202    * Active connection transmission handle.
203    */
204   struct GNUNET_CONNECTION_TransmitHandle *cth;
205
206 };
207
208
209 /**
210  * @brief handle for a client of the server
211  */
212 struct GNUNET_SERVER_Client
213 {
214
215   /**
216    * This is a doubly linked list.
217    */
218   struct GNUNET_SERVER_Client *next;
219
220   /**
221    * This is a doubly linked list.
222    */
223   struct GNUNET_SERVER_Client *prev;
224
225   /**
226    * Processing of incoming data.
227    */
228   void *mst;
229
230   /**
231    * Server that this client belongs to.
232    */
233   struct GNUNET_SERVER_Handle *server;
234
235   /**
236    * Client closure for callbacks.
237    */
238   struct GNUNET_CONNECTION_Handle *connection;
239
240   /**
241    * User context value, manipulated using
242    * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
243    */
244   void *user_context;
245
246   /**
247    * ID of task used to restart processing.
248    */
249   struct GNUNET_SCHEDULER_Task * restart_task;
250
251   /**
252    * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
253    */
254   struct GNUNET_SCHEDULER_Task * warn_task;
255
256   /**
257    * Time when the warn task was started.
258    */
259   struct GNUNET_TIME_Absolute warn_start;
260
261   /**
262    * Last activity on this socket (used to time it out
263    * if reference_count == 0).
264    */
265   struct GNUNET_TIME_Absolute last_activity;
266
267   /**
268    * Transmission handle we return for this client from
269    * #GNUNET_SERVER_notify_transmit_ready.
270    */
271   struct GNUNET_SERVER_TransmitHandle th;
272
273   /**
274    * After how long should an idle connection time
275    * out (on write).
276    */
277   struct GNUNET_TIME_Relative idle_timeout;
278
279   /**
280    * Number of external entities with a reference to
281    * this client object.
282    */
283   unsigned int reference_count;
284
285   /**
286    * Was processing if incoming messages suspended while
287    * we were still processing data already received?
288    * This is a counter saying how often processing was
289    * suspended (once per handler invoked).
290    */
291   unsigned int suspended;
292
293   /**
294    * Last size given when user context was initialized; used for
295    * sanity check.
296    */
297   size_t user_context_size;
298
299   /**
300    * Are we currently in the "process_client_buffer" function (and
301    * will hence restart the receive job on exit if suspended == 0 once
302    * we are done?).  If this is set, then "receive_done" will
303    * essentially only decrement suspended; if this is not set, then
304    * "receive_done" may need to restart the receive process (either
305    * from the side-buffer or via select/recv).
306    */
307   int in_process_client_buffer;
308
309   /**
310    * We're about to close down this client.
311    */
312   int shutdown_now;
313
314   /**
315    * Are we currently trying to receive? (#GNUNET_YES if we are,
316    * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
317    * available in MST).
318    */
319   int receive_pending;
320
321   /**
322    * Persist the file handle for this client no matter what happens,
323    * force the OS to close once the process actually dies.  Should only
324    * be used in special cases!
325    */
326   int persist;
327
328   /**
329    * Is this client a 'monitor' client that should not be counted
330    * when deciding on destroying the server during soft shutdown?
331    * (see also #GNUNET_SERVICE_start)
332    */
333   int is_monitor;
334
335   /**
336    * Type of last message processed (for warn_no_receive_done).
337    */
338   uint16_t warn_type;
339 };
340
341
342
343 /**
344  * Return user context associated with the given client.
345  * Note: you should probably use the macro (call without the underscore).
346  *
347  * @param client client to query
348  * @param size number of bytes in user context struct (for verification only)
349  * @return pointer to user context
350  */
351 void *
352 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
353                                         size_t size)
354 {
355   if ((0 == client->user_context_size) &&
356       (NULL == client->user_context))
357     return NULL; /* never set */
358   GNUNET_assert (size == client->user_context_size);
359   return client->user_context;
360 }
361
362
363 /**
364  * Set user context to be associated with the given client.
365  * Note: you should probably use the macro (call without the underscore).
366  *
367  * @param client client to query
368  * @param ptr pointer to user context
369  * @param size number of bytes in user context struct (for verification only)
370  */
371 void
372 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
373                                         void *ptr,
374                                         size_t size)
375 {
376   if (NULL == ptr)
377   {
378     client->user_context_size = 0;
379     client->user_context = ptr;
380     return;
381   }
382   client->user_context_size = size;
383   client->user_context = ptr;
384 }
385
386
387 /**
388  * Scheduler says our listen socket is ready.  Process it!
389  *
390  * @param cls handle to our server for which we are processing the listen
391  *        socket
392  */
393 static void
394 process_listen_socket (void *cls)
395 {
396   struct GNUNET_SERVER_Handle *server = cls;
397   const struct GNUNET_SCHEDULER_TaskContext *tc;
398   struct GNUNET_CONNECTION_Handle *sock;
399   unsigned int i;
400
401   server->listen_task = NULL;
402   tc = GNUNET_SCHEDULER_get_task_context ();
403   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
404   {
405     /* ignore shutdown, someone else will take care of it! */
406     GNUNET_SERVER_resume (server);
407     return;
408   }
409   for (i = 0; NULL != server->listen_sockets[i]; i++)
410   {
411     if (GNUNET_NETWORK_fdset_isset (tc->read_ready,
412                                     server->listen_sockets[i]))
413     {
414       sock =
415           GNUNET_CONNECTION_create_from_accept (server->access_cb,
416                                                 server->access_cb_cls,
417                                                 server->listen_sockets[i]);
418       if (NULL != sock)
419       {
420         LOG (GNUNET_ERROR_TYPE_DEBUG,
421              "Server accepted incoming connection.\n");
422         (void) GNUNET_SERVER_connect_socket (server,
423                                              sock);
424       }
425     }
426   }
427   /* listen for more! */
428   GNUNET_SERVER_resume (server);
429 }
430
431
432 /**
433  * Create and initialize a listen socket for the server.
434  *
435  * @param server_addr address to listen on
436  * @param socklen length of @a server_addr
437  * @return NULL on error, otherwise the listen socket
438  */
439 static struct GNUNET_NETWORK_Handle *
440 open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
441 {
442   struct GNUNET_NETWORK_Handle *sock;
443   uint16_t port;
444   int eno;
445
446   switch (server_addr->sa_family)
447   {
448   case AF_INET:
449     port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
450     break;
451   case AF_INET6:
452     port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
453     break;
454   case AF_UNIX:
455     port = 0;
456     break;
457   default:
458     GNUNET_break (0);
459     port = 0;
460     break;
461   }
462   sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
463   if (NULL == sock)
464   {
465     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
466     errno = 0;
467     return NULL;
468   }
469   /* bind the socket */
470   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
471   {
472     eno = errno;
473     if (EADDRINUSE != errno)
474     {
475       /* we don't log 'EADDRINUSE' here since an IPv4 bind may
476        * fail if we already took the port on IPv6; if both IPv4 and
477        * IPv6 binds fail, then our caller will log using the
478        * errno preserved in 'eno' */
479       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
480                     "bind");
481       if (0 != port)
482         LOG (GNUNET_ERROR_TYPE_ERROR,
483              _("`%s' failed for port %d (%s).\n"),
484              "bind",
485              port,
486              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
487       eno = 0;
488     }
489     else
490     {
491       if (0 != port)
492         LOG (GNUNET_ERROR_TYPE_WARNING,
493              _("`%s' failed for port %d (%s): address already in use\n"),
494              "bind", port,
495              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
496       else if (AF_UNIX == server_addr->sa_family)
497       {
498         LOG (GNUNET_ERROR_TYPE_WARNING,
499              _("`%s' failed for `%s': address already in use\n"),
500              "bind",
501              GNUNET_a2s (server_addr, socklen));
502       }
503     }
504     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
505     errno = eno;
506     return NULL;
507   }
508   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
509   {
510     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
511                   "listen");
512     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
513     errno = 0;
514     return NULL;
515   }
516   if (0 != port)
517     LOG (GNUNET_ERROR_TYPE_DEBUG,
518          "Server starts to listen on port %u.\n",
519          port);
520   return sock;
521 }
522
523
524 /**
525  * Create a new server.
526  *
527  * @param access_cb function for access control
528  * @param access_cb_cls closure for @a access_cb
529  * @param lsocks NULL-terminated array of listen sockets
530  * @param idle_timeout after how long should we timeout idle connections?
531  * @param require_found if #GNUNET_YES, connections sending messages of unknown type
532  *        will be closed
533  * @return handle for the new server, NULL on error
534  *         (typically, "port" already in use)
535  */
536 struct GNUNET_SERVER_Handle *
537 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access_cb,
538                                    void *access_cb_cls,
539                                    struct GNUNET_NETWORK_Handle **lsocks,
540                                    struct GNUNET_TIME_Relative idle_timeout,
541                                    int require_found)
542 {
543   struct GNUNET_SERVER_Handle *server;
544
545   server = GNUNET_new (struct GNUNET_SERVER_Handle);
546   server->idle_timeout = idle_timeout;
547   server->listen_sockets = lsocks;
548   server->access_cb = access_cb;
549   server->access_cb_cls = access_cb_cls;
550   server->require_found = require_found;
551   if (NULL != lsocks)
552     GNUNET_SERVER_resume (server);
553   return server;
554 }
555
556
557 /**
558  * Create a new server.
559  *
560  * @param access_cb function for access control
561  * @param access_cb_cls closure for @a access_cb
562  * @param server_addr address to listen on (including port), NULL terminated array
563  * @param socklen length of server_addr
564  * @param idle_timeout after how long should we timeout idle connections?
565  * @param require_found if YES, connections sending messages of unknown type
566  *        will be closed
567  * @return handle for the new server, NULL on error
568  *         (typically, "port" already in use)
569  */
570 struct GNUNET_SERVER_Handle *
571 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access_cb,
572                       void *access_cb_cls,
573                       struct sockaddr *const *server_addr,
574                       const socklen_t * socklen,
575                       struct GNUNET_TIME_Relative idle_timeout,
576                       int require_found)
577 {
578   struct GNUNET_NETWORK_Handle **lsocks;
579   unsigned int i;
580   unsigned int j;
581   unsigned int k;
582   int seen;
583
584   i = 0;
585   while (NULL != server_addr[i])
586     i++;
587   if (i > 0)
588   {
589     lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
590     i = 0;
591     j = 0;
592     while (NULL != server_addr[i])
593     {
594       seen = 0;
595       for (k=0;k<i;k++)
596         if ( (socklen[k] == socklen[i]) &&
597              (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
598         {
599           seen = 1;
600           break;
601         }
602       if (0 != seen)
603       {
604         /* duplicate address, skip */
605         i++;
606         continue;
607       }
608       lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
609       if (NULL != lsocks[j])
610         j++;
611       i++;
612     }
613     if (0 == j)
614     {
615       if (0 != errno)
616         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
617       GNUNET_free (lsocks);
618       lsocks = NULL;
619     }
620   }
621   else
622   {
623     lsocks = NULL;
624   }
625   return GNUNET_SERVER_create_with_sockets (access_cb,
626                                             access_cb_cls,
627                                             lsocks,
628                                             idle_timeout,
629                                             require_found);
630 }
631
632
633 /**
634  * Set the 'monitor' flag on this client.  Clients which have been
635  * marked as 'monitors' won't prevent the server from shutting down
636  * once '#GNUNET_SERVER_stop_listening()' has been invoked.  The idea is
637  * that for "normal" clients we likely want to allow them to process
638  * their requests; however, monitor-clients are likely to 'never'
639  * disconnect during shutdown and thus will not be considered when
640  * determining if the server should continue to exist after
641  * #GNUNET_SERVER_destroy() has been called.
642  *
643  * @param client the client to set the 'monitor' flag on
644  */
645 void
646 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
647 {
648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649               "Marking client as monitor!\n");
650   client->is_monitor = GNUNET_YES;
651 }
652
653
654 /**
655  * Helper function for #test_monitor_clients() to trigger
656  * #GNUNET_SERVER_destroy() after the stack has unwound.
657  *
658  * @param cls the `struct GNUNET_SERVER_Handle *` to destroy
659  */
660 static void
661 do_destroy (void *cls)
662 {
663   struct GNUNET_SERVER_Handle *server = cls;
664
665   GNUNET_SERVER_destroy (server);
666 }
667
668
669 /**
670  * Check if only 'monitor' clients are left.  If so, destroy the
671  * server completely.
672  *
673  * @param server server to test for full shutdown
674  */
675 static void
676 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
677 {
678   struct GNUNET_SERVER_Client *client;
679
680   if (GNUNET_YES != server->in_soft_shutdown)
681     return;
682   for (client = server->clients_head; NULL != client; client = client->next)
683     if (GNUNET_NO == client->is_monitor)
684       return; /* not done yet */
685   server->in_soft_shutdown = GNUNET_SYSERR;
686   GNUNET_SCHEDULER_add_now (&do_destroy, server);
687 }
688
689
690 /**
691  * Suspend accepting connections from the listen socket temporarily.
692  *
693  * @param server server to stop accepting connections.
694  */
695 void
696 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
697 {
698   if (NULL != server->listen_task)
699   {
700     GNUNET_SCHEDULER_cancel (server->listen_task);
701     server->listen_task = NULL;
702   }
703 }
704
705
706 /**
707  * Resume accepting connections from the listen socket.
708  *
709  * @param server server to stop accepting connections.
710  */
711 void
712 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
713 {
714   struct GNUNET_NETWORK_FDSet *r;
715   unsigned int i;
716
717   if (NULL == server->listen_sockets)
718     return;
719   if (NULL == server->listen_sockets[0])
720     return; /* nothing to do, no listen sockets! */
721   if (NULL == server->listen_sockets[1])
722   {
723     /* simplified method: no fd set needed; this is then much simpler and
724        much more efficient */
725     server->listen_task =
726       GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
727                                                    GNUNET_SCHEDULER_PRIORITY_HIGH,
728                                                    server->listen_sockets[0],
729                                                    &process_listen_socket, server);
730     return;
731   }
732   r = GNUNET_NETWORK_fdset_create ();
733   i = 0;
734   while (NULL != server->listen_sockets[i])
735     GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
736   server->listen_task =
737     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
738                                  GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
739                                  &process_listen_socket, server);
740   GNUNET_NETWORK_fdset_destroy (r);
741 }
742
743
744 /**
745  * Stop the listen socket and get ready to shutdown the server
746  * once only 'monitor' clients are left.
747  *
748  * @param server server to stop listening on
749  */
750 void
751 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
752 {
753   unsigned int i;
754
755   LOG (GNUNET_ERROR_TYPE_DEBUG,
756        "Server in soft shutdown\n");
757   if (NULL != server->listen_task)
758   {
759     GNUNET_SCHEDULER_cancel (server->listen_task);
760     server->listen_task = NULL;
761   }
762   if (NULL != server->listen_sockets)
763   {
764     i = 0;
765     while (NULL != server->listen_sockets[i])
766       GNUNET_break (GNUNET_OK ==
767                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
768     GNUNET_free (server->listen_sockets);
769     server->listen_sockets = NULL;
770   }
771   if (GNUNET_NO == server->in_soft_shutdown)
772     server->in_soft_shutdown = GNUNET_YES;
773   test_monitor_clients (server);
774 }
775
776
777 /**
778  * Free resources held by this server.
779  *
780  * @param server server to destroy
781  */
782 void
783 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
784 {
785   struct HandlerList *hpos;
786   struct NotifyList *npos;
787   unsigned int i;
788
789   LOG (GNUNET_ERROR_TYPE_DEBUG,
790        "Server shutting down.\n");
791   if (NULL != server->listen_task)
792   {
793     GNUNET_SCHEDULER_cancel (server->listen_task);
794     server->listen_task = NULL;
795   }
796   if (NULL != server->listen_sockets)
797   {
798     i = 0;
799     while (NULL != server->listen_sockets[i])
800       GNUNET_break (GNUNET_OK ==
801                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
802     GNUNET_free (server->listen_sockets);
803     server->listen_sockets = NULL;
804   }
805   while (NULL != server->clients_head)
806     GNUNET_SERVER_client_disconnect (server->clients_head);
807   while (NULL != (hpos = server->handlers))
808   {
809     server->handlers = hpos->next;
810     GNUNET_free (hpos);
811   }
812   while (NULL != (npos = server->disconnect_notify_list_head))
813   {
814     npos->callback (npos->callback_cls,
815                     NULL);
816     GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
817                                  server->disconnect_notify_list_tail,
818                                  npos);
819     GNUNET_free (npos);
820   }
821   while (NULL != (npos = server->connect_notify_list_head))
822   {
823     npos->callback (npos->callback_cls,
824                     NULL);
825     GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
826                                  server->connect_notify_list_tail,
827                                  npos);
828     GNUNET_free (npos);
829   }
830   GNUNET_free (server);
831 }
832
833
834 /**
835  * Add additional handlers to an existing server.
836  *
837  * @param server the server to add handlers to
838  * @param handlers array of message handlers for
839  *        incoming messages; the last entry must
840  *        have "NULL" for the "callback"; multiple
841  *        entries for the same type are allowed,
842  *        they will be called in order of occurence.
843  *        These handlers can be removed later;
844  *        the handlers array must exist until removed
845  *        (or server is destroyed).
846  */
847 void
848 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
849                             const struct GNUNET_SERVER_MessageHandler *handlers)
850 {
851   struct HandlerList *p;
852
853   p = GNUNET_new (struct HandlerList);
854   p->handlers = handlers;
855   p->next = server->handlers;
856   server->handlers = p;
857 }
858
859
860 /**
861  * Change functions used by the server to tokenize the message stream.
862  * (very rarely used).
863  *
864  * @param server server to modify
865  * @param create new tokenizer initialization function
866  * @param destroy new tokenizer destruction function
867  * @param receive new tokenizer receive function
868  * @param cls closure for @a create, @a receive, @a destroy
869  */
870 void
871 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
872                              GNUNET_SERVER_MstCreateCallback create,
873                              GNUNET_SERVER_MstDestroyCallback destroy,
874                              GNUNET_SERVER_MstReceiveCallback receive,
875                              void *cls)
876 {
877   server->mst_create = create;
878   server->mst_destroy = destroy;
879   server->mst_receive = receive;
880   server->mst_cls = cls;
881 }
882
883
884 /**
885  * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
886  *
887  * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
888  */
889 static void
890 warn_no_receive_done (void *cls)
891 {
892   struct GNUNET_SERVER_Client *client = cls;
893   const struct GNUNET_SCHEDULER_TaskContext *tc;
894
895   GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
896   client->warn_task =
897       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
898                                     &warn_no_receive_done, client);
899   tc = GNUNET_SCHEDULER_get_task_context ();
900   if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
901     LOG (GNUNET_ERROR_TYPE_WARNING,
902          _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
903          (unsigned int) client->warn_type,
904          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
905 }
906
907
908 /**
909  * Disable the warning the server issues if a message is not acknowledged
910  * in a timely fashion.  Use this call if a client is intentionally delayed
911  * for a while.  Only applies to the current message.
912  *
913  * @param client client for which to disable the warning
914  */
915 void
916 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
917 {
918   if (NULL != client->warn_task)
919   {
920     GNUNET_SCHEDULER_cancel (client->warn_task);
921     client->warn_task = NULL;
922   }
923 }
924
925
926 /**
927  * Inject a message into the server, pretend it came
928  * from the specified client.  Delivery of the message
929  * will happen instantly (if a handler is installed;
930  * otherwise the call does nothing).
931  *
932  * @param server the server receiving the message
933  * @param sender the "pretended" sender of the message
934  *        can be NULL!
935  * @param message message to transmit
936  * @return #GNUNET_OK if the message was OK and the
937  *                   connection can stay open
938  *         #GNUNET_SYSERR if the connection to the
939  *         client should be shut down
940  */
941 int
942 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
943                       struct GNUNET_SERVER_Client *sender,
944                       const struct GNUNET_MessageHeader *message)
945 {
946   struct HandlerList *pos;
947   const struct GNUNET_SERVER_MessageHandler *mh;
948   unsigned int i;
949   uint16_t type;
950   uint16_t size;
951   int found;
952
953   type = ntohs (message->type);
954   size = ntohs (message->size);
955   LOG (GNUNET_ERROR_TYPE_DEBUG,
956        "Server schedules transmission of %u-byte message of type %u to client.\n",
957        size, type);
958   found = GNUNET_NO;
959   for (pos = server->handlers; NULL != pos; pos = pos->next)
960   {
961     i = 0;
962     while (pos->handlers[i].callback != NULL)
963     {
964       mh = &pos->handlers[i];
965       if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
966       {
967         if ((0 != mh->expected_size) && (mh->expected_size != size))
968         {
969 #if GNUNET8_NETWORK_IS_DEAD
970           LOG (GNUNET_ERROR_TYPE_WARNING,
971                "Expected %u bytes for message of type %u, got %u\n",
972                mh->expected_size, mh->type, size);
973           GNUNET_break_op (0);
974 #else
975           LOG (GNUNET_ERROR_TYPE_DEBUG,
976                "Expected %u bytes for message of type %u, got %u\n",
977                mh->expected_size, mh->type, size);
978 #endif
979           return GNUNET_SYSERR;
980         }
981         if (NULL != sender)
982         {
983           if ( (0 == sender->suspended) &&
984                (NULL == sender->warn_task) )
985           {
986             GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
987             sender->warn_start = GNUNET_TIME_absolute_get ();
988             sender->warn_task =
989                 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
990                                               &warn_no_receive_done, sender);
991             sender->warn_type = type;
992           }
993           sender->suspended++;
994         }
995         mh->callback (mh->callback_cls, sender, message);
996         found = GNUNET_YES;
997       }
998       i++;
999     }
1000   }
1001   if (GNUNET_NO == found)
1002   {
1003     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1004          "Received message of unknown type %d\n", type);
1005     if (GNUNET_YES == server->require_found)
1006       return GNUNET_SYSERR;
1007   }
1008   return GNUNET_OK;
1009 }
1010
1011
1012 /**
1013  * We are receiving an incoming message.  Process it.
1014  *
1015  * @param cls our closure (handle for the client)
1016  * @param buf buffer with data received from network
1017  * @param available number of bytes available in buf
1018  * @param addr address of the sender
1019  * @param addrlen length of @a addr
1020  * @param errCode code indicating errors receiving, 0 for success
1021  */
1022 static void
1023 process_incoming (void *cls,
1024                   const void *buf,
1025                   size_t available,
1026                   const struct sockaddr *addr,
1027                   socklen_t addrlen,
1028                   int errCode);
1029
1030
1031 /**
1032  * Process messages from the client's message tokenizer until either
1033  * the tokenizer is empty (and then schedule receiving more), or
1034  * until some handler is not immediately done (then wait for restart_processing)
1035  * or shutdown.
1036  *
1037  * @param client the client to process, RC must have already been increased
1038  *        using #GNUNET_SERVER_client_keep and will be decreased by one in this
1039  *        function
1040  * @param ret #GNUNET_NO to start processing from the buffer,
1041  *            #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1042  *            #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1043  */
1044 static void
1045 process_mst (struct GNUNET_SERVER_Client *client,
1046              int ret)
1047 {
1048   while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1049          (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1050   {
1051     if (GNUNET_OK == ret)
1052     {
1053       LOG (GNUNET_ERROR_TYPE_DEBUG,
1054            "Server re-enters receive loop, timeout: %s.\n",
1055            GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1056       client->receive_pending = GNUNET_YES;
1057       GNUNET_CONNECTION_receive (client->connection,
1058                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1059                                  client->idle_timeout,
1060                                  &process_incoming,
1061                                  client);
1062       break;
1063     }
1064     LOG (GNUNET_ERROR_TYPE_DEBUG,
1065          "Server processes additional messages instantly.\n");
1066     if (NULL != client->server->mst_receive)
1067       ret =
1068           client->server->mst_receive (client->server->mst_cls, client->mst,
1069                                        client, NULL, 0, GNUNET_NO, GNUNET_YES);
1070     else
1071       ret =
1072           GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1073                                      GNUNET_YES);
1074   }
1075   LOG (GNUNET_ERROR_TYPE_DEBUG,
1076        "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1077        ret, client->server,
1078        client->shutdown_now,
1079        client->suspended);
1080   if (GNUNET_NO == ret)
1081   {
1082     LOG (GNUNET_ERROR_TYPE_DEBUG,
1083          "Server has more data pending but is suspended.\n");
1084     client->receive_pending = GNUNET_SYSERR;    /* data pending */
1085   }
1086   if ( (GNUNET_SYSERR == ret) ||
1087        (GNUNET_YES == client->shutdown_now) )
1088     GNUNET_SERVER_client_disconnect (client);
1089 }
1090
1091
1092 /**
1093  * We are receiving an incoming message.  Process it.
1094  *
1095  * @param cls our closure (handle for the client)
1096  * @param buf buffer with data received from network
1097  * @param available number of bytes available in buf
1098  * @param addr address of the sender
1099  * @param addrlen length of @a addr
1100  * @param errCode code indicating errors receiving, 0 for success
1101  */
1102 static void
1103 process_incoming (void *cls,
1104                   const void *buf,
1105                   size_t available,
1106                   const struct sockaddr *addr,
1107                   socklen_t addrlen,
1108                   int errCode)
1109 {
1110   struct GNUNET_SERVER_Client *client = cls;
1111   struct GNUNET_SERVER_Handle *server = client->server;
1112   struct GNUNET_TIME_Absolute end;
1113   struct GNUNET_TIME_Absolute now;
1114   int ret;
1115
1116   GNUNET_assert (GNUNET_YES == client->receive_pending);
1117   client->receive_pending = GNUNET_NO;
1118   now = GNUNET_TIME_absolute_get ();
1119   end = GNUNET_TIME_absolute_add (client->last_activity,
1120                                   client->idle_timeout);
1121
1122   if ( (NULL == buf) &&
1123        (0 == available) &&
1124        (NULL == addr) &&
1125        (0 == errCode) &&
1126        (GNUNET_YES != client->shutdown_now) &&
1127        (NULL != server) &&
1128        (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1129        (end.abs_value_us > now.abs_value_us) )
1130   {
1131     /* wait longer, timeout changed (i.e. due to us sending) */
1132     LOG (GNUNET_ERROR_TYPE_DEBUG,
1133          "Receive time out, but no disconnect due to sending (%p)\n",
1134          client);
1135     client->receive_pending = GNUNET_YES;
1136     GNUNET_CONNECTION_receive (client->connection,
1137                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1138                                GNUNET_TIME_absolute_get_remaining (end),
1139                                &process_incoming,
1140                                client);
1141     return;
1142   }
1143   if ( (NULL == buf) ||
1144        (0 == available) ||
1145        (0 != errCode) ||
1146        (NULL == server) ||
1147        (GNUNET_YES == client->shutdown_now) ||
1148        (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)) )
1149   {
1150     /* other side closed connection, error connecting, etc. */
1151     LOG (GNUNET_ERROR_TYPE_DEBUG,
1152          "Failed to connect or other side closed connection (%p)\n",
1153          client);
1154     GNUNET_SERVER_client_disconnect (client);
1155     return;
1156   }
1157   LOG (GNUNET_ERROR_TYPE_DEBUG,
1158        "Server receives %u bytes from `%s'.\n",
1159        (unsigned int) available,
1160        GNUNET_a2s (addr, addrlen));
1161   GNUNET_SERVER_client_keep (client);
1162   client->last_activity = now;
1163
1164   if (NULL != server->mst_receive)
1165   {
1166     ret = client->server->mst_receive (client->server->mst_cls,
1167                                        client->mst,
1168                                        client,
1169                                        buf,
1170                                        available,
1171                                        GNUNET_NO,
1172                                        GNUNET_YES);
1173   }
1174   else if (NULL != client->mst)
1175   {
1176     ret =
1177         GNUNET_SERVER_mst_receive (client->mst,
1178                                    client,
1179                                    buf,
1180                                    available,
1181                                    GNUNET_NO,
1182                                    GNUNET_YES);
1183   }
1184   else
1185   {
1186     GNUNET_break (0);
1187     return;
1188   }
1189   process_mst (client,
1190                ret);
1191   GNUNET_SERVER_client_drop (client);
1192 }
1193
1194
1195 /**
1196  * Task run to start again receiving from the network
1197  * and process requests.
1198  *
1199  * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
1200  */
1201 static void
1202 restart_processing (void *cls)
1203 {
1204   struct GNUNET_SERVER_Client *client = cls;
1205
1206   GNUNET_assert (GNUNET_YES != client->shutdown_now);
1207   client->restart_task = NULL;
1208   if (GNUNET_NO == client->receive_pending)
1209   {
1210     LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1211     client->receive_pending = GNUNET_YES;
1212     GNUNET_CONNECTION_receive (client->connection,
1213                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1214                                client->idle_timeout,
1215                                &process_incoming,
1216                                client);
1217     return;
1218   }
1219   LOG (GNUNET_ERROR_TYPE_DEBUG,
1220        "Server continues processing messages still in the buffer.\n");
1221   GNUNET_SERVER_client_keep (client);
1222   client->receive_pending = GNUNET_NO;
1223   process_mst (client,
1224                GNUNET_NO);
1225   GNUNET_SERVER_client_drop (client);
1226 }
1227
1228
1229 /**
1230  * This function is called whenever our inbound message tokenizer has
1231  * received a complete message.
1232  *
1233  * @param cls closure (struct GNUNET_SERVER_Handle)
1234  * @param client identification of the client (`struct GNUNET_SERVER_Client *`)
1235  * @param message the actual message
1236  *
1237  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1238  */
1239 static int
1240 client_message_tokenizer_callback (void *cls,
1241                                    void *client,
1242                                    const struct GNUNET_MessageHeader *message)
1243 {
1244   struct GNUNET_SERVER_Handle *server = cls;
1245   struct GNUNET_SERVER_Client *sender = client;
1246   int ret;
1247
1248   LOG (GNUNET_ERROR_TYPE_DEBUG,
1249        "Tokenizer gives server message of type %u from client\n",
1250        ntohs (message->type));
1251   sender->in_process_client_buffer = GNUNET_YES;
1252   ret = GNUNET_SERVER_inject (server, sender, message);
1253   sender->in_process_client_buffer = GNUNET_NO;
1254   if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1255   {
1256     GNUNET_SERVER_client_disconnect (sender);
1257     return GNUNET_SYSERR;
1258   }
1259   return GNUNET_OK;
1260 }
1261
1262
1263 /**
1264  * Add a TCP socket-based connection to the set of handles managed by
1265  * this server.  Use this function for outgoing (P2P) connections that
1266  * we initiated (and where this server should process incoming
1267  * messages).
1268  *
1269  * @param server the server to use
1270  * @param connection the connection to manage (client must
1271  *        stop using this connection from now on)
1272  * @return the client handle
1273  */
1274 struct GNUNET_SERVER_Client *
1275 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1276                               struct GNUNET_CONNECTION_Handle *connection)
1277 {
1278   struct GNUNET_SERVER_Client *client;
1279   struct NotifyList *n;
1280
1281   client = GNUNET_new (struct GNUNET_SERVER_Client);
1282   client->connection = connection;
1283   client->server = server;
1284   client->last_activity = GNUNET_TIME_absolute_get ();
1285   client->idle_timeout = server->idle_timeout;
1286   GNUNET_CONTAINER_DLL_insert (server->clients_head,
1287                                server->clients_tail,
1288                                client);
1289   if (NULL != server->mst_create)
1290     client->mst =
1291         server->mst_create (server->mst_cls, client);
1292   else
1293     client->mst =
1294         GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
1295                                   server);
1296   GNUNET_assert (NULL != client->mst);
1297   for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1298     n->callback (n->callback_cls, client);
1299   client->receive_pending = GNUNET_YES;
1300   GNUNET_CONNECTION_receive (client->connection,
1301                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1302                              client->idle_timeout,
1303                              &process_incoming,
1304                              client);
1305   return client;
1306 }
1307
1308
1309 /**
1310  * Change the timeout for a particular client.  Decreasing the timeout
1311  * may not go into effect immediately (only after the previous timeout
1312  * times out or activity happens on the socket).
1313  *
1314  * @param client the client to update
1315  * @param timeout new timeout for activities on the socket
1316  */
1317 void
1318 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1319                                   struct GNUNET_TIME_Relative timeout)
1320 {
1321   client->idle_timeout = timeout;
1322 }
1323
1324
1325 /**
1326  * Notify the server that the given client handle should
1327  * be kept (keeps the connection up if possible, increments
1328  * the internal reference counter).
1329  *
1330  * @param client the client to keep
1331  */
1332 void
1333 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1334 {
1335   client->reference_count++;
1336 }
1337
1338
1339 /**
1340  * Notify the server that the given client handle is no
1341  * longer required.  Decrements the reference counter.  If
1342  * that counter reaches zero an inactive connection maybe
1343  * closed.
1344  *
1345  * @param client the client to drop
1346  */
1347 void
1348 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1349 {
1350   GNUNET_assert (client->reference_count > 0);
1351   client->reference_count--;
1352   if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1353     GNUNET_SERVER_client_disconnect (client);
1354 }
1355
1356
1357 /**
1358  * Obtain the network address of the other party.
1359  *
1360  * @param client the client to get the address for
1361  * @param addr where to store the address
1362  * @param addrlen where to store the length of the @a addr
1363  * @return #GNUNET_OK on success
1364  */
1365 int
1366 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1367                                   void **addr, size_t * addrlen)
1368 {
1369   return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1370 }
1371
1372
1373 /**
1374  * Ask the server to notify us whenever a client disconnects.
1375  * This function is called whenever the actual network connection
1376  * is closed; the reference count may be zero or larger than zero
1377  * at this point.
1378  *
1379  * @param server the server manageing the clients
1380  * @param callback function to call on disconnect
1381  * @param callback_cls closure for @a callback
1382  */
1383 void
1384 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1385                                  GNUNET_SERVER_DisconnectCallback callback,
1386                                  void *callback_cls)
1387 {
1388   struct NotifyList *n;
1389
1390   n = GNUNET_new (struct NotifyList);
1391   n->callback = callback;
1392   n->callback_cls = callback_cls;
1393   GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1394                                server->disconnect_notify_list_tail,
1395                                n);
1396 }
1397
1398
1399 /**
1400  * Ask the server to notify us whenever a client connects.
1401  * This function is called whenever the actual network connection
1402  * is opened. If the server is destroyed before this
1403  * notification is explicitly cancelled, the 'callback' will
1404  * once be called with a 'client' argument of NULL to indicate
1405  * that the server itself is now gone (and that the callback
1406  * won't be called anymore and also can no longer be cancelled).
1407  *
1408  * @param server the server manageing the clients
1409  * @param callback function to call on sconnect
1410  * @param callback_cls closure for @a callback
1411  */
1412 void
1413 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1414                               GNUNET_SERVER_ConnectCallback callback,
1415                               void *callback_cls)
1416 {
1417   struct NotifyList *n;
1418   struct GNUNET_SERVER_Client *client;
1419
1420   n = GNUNET_new (struct NotifyList);
1421   n->callback = callback;
1422   n->callback_cls = callback_cls;
1423   GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1424                                server->connect_notify_list_tail,
1425                                n);
1426   for (client = server->clients_head; NULL != client; client = client->next)
1427     callback (callback_cls, client);
1428 }
1429
1430
1431 /**
1432  * Ask the server to stop notifying us whenever a client connects.
1433  *
1434  * @param server the server manageing the clients
1435  * @param callback function to call on connect
1436  * @param callback_cls closure for @a callback
1437  */
1438 void
1439 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1440                                         GNUNET_SERVER_DisconnectCallback callback,
1441                                         void *callback_cls)
1442 {
1443   struct NotifyList *pos;
1444
1445   for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1446     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1447       break;
1448   if (NULL == pos)
1449   {
1450     GNUNET_break (0);
1451     return;
1452   }
1453   GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1454                                server->disconnect_notify_list_tail,
1455                                pos);
1456   GNUNET_free (pos);
1457 }
1458
1459
1460 /**
1461  * Ask the server to stop notifying us whenever a client disconnects.
1462  *
1463  * @param server the server manageing the clients
1464  * @param callback function to call on disconnect
1465  * @param callback_cls closure for @a callback
1466  */
1467 void
1468 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1469                                      GNUNET_SERVER_ConnectCallback callback,
1470                                      void *callback_cls)
1471 {
1472   struct NotifyList *pos;
1473
1474   for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1475     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1476       break;
1477   if (NULL == pos)
1478   {
1479     GNUNET_break (0);
1480     return;
1481   }
1482   GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1483                                server->connect_notify_list_tail,
1484                                pos);
1485   GNUNET_free (pos);
1486 }
1487
1488
1489 /**
1490  * Destroy the connection that is passed in via @a cls.  Used
1491  * as calling #GNUNET_CONNECTION_destroy from within a function
1492  * that was itself called from within process_notify() of
1493  * 'connection.c' is not allowed (see #2329).
1494  *
1495  * @param cls connection to destroy
1496  */
1497 static void
1498 destroy_connection (void *cls)
1499 {
1500   struct GNUNET_CONNECTION_Handle *connection = cls;
1501
1502   GNUNET_CONNECTION_destroy (connection);
1503 }
1504
1505
1506 /**
1507  * Ask the server to disconnect from the given client.
1508  * This is the same as returning #GNUNET_SYSERR from a message
1509  * handler, except that it allows dropping of a client even
1510  * when not handling a message from that client.
1511  *
1512  * @param client the client to disconnect from
1513  */
1514 void
1515 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1516 {
1517   struct GNUNET_SERVER_Handle *server = client->server;
1518   struct NotifyList *n;
1519
1520   LOG (GNUNET_ERROR_TYPE_DEBUG,
1521        "Client is being disconnected from the server.\n");
1522   if (NULL != client->restart_task)
1523   {
1524     GNUNET_SCHEDULER_cancel (client->restart_task);
1525     client->restart_task = NULL;
1526   }
1527   if (NULL != client->warn_task)
1528   {
1529     GNUNET_SCHEDULER_cancel (client->warn_task);
1530     client->warn_task = NULL;
1531   }
1532   if (GNUNET_YES == client->receive_pending)
1533   {
1534     GNUNET_CONNECTION_receive_cancel (client->connection);
1535     client->receive_pending = GNUNET_NO;
1536   }
1537   client->shutdown_now = GNUNET_YES;
1538   client->reference_count++; /* make sure nobody else clean up client... */
1539   if ( (NULL != client->mst) &&
1540        (NULL != server) )
1541   {
1542     GNUNET_CONTAINER_DLL_remove (server->clients_head,
1543                                  server->clients_tail,
1544                                  client);
1545     if (NULL != server->mst_destroy)
1546       server->mst_destroy (server->mst_cls,
1547                            client->mst);
1548     else
1549       GNUNET_SERVER_mst_destroy (client->mst);
1550     client->mst = NULL;
1551     for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1552       n->callback (n->callback_cls,
1553                    client);
1554   }
1555   client->reference_count--;
1556   if (client->reference_count > 0)
1557   {
1558     LOG (GNUNET_ERROR_TYPE_DEBUG,
1559          "RC of %p still positive, not destroying everything.\n",
1560          client);
1561     client->server = NULL;
1562     return;
1563   }
1564   if (GNUNET_YES == client->in_process_client_buffer)
1565   {
1566     LOG (GNUNET_ERROR_TYPE_DEBUG,
1567          "Still processing inputs of %p, not destroying everything.\n",
1568          client);
1569     return;
1570   }
1571   LOG (GNUNET_ERROR_TYPE_DEBUG,
1572        "RC of %p now zero, destroying everything.\n",
1573        client);
1574   if (GNUNET_YES == client->persist)
1575     GNUNET_CONNECTION_persist_ (client->connection);
1576   if (NULL != client->th.cth)
1577     GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1578   (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1579                                    client->connection);
1580   /* need to cancel again, as it might have been re-added
1581      in the meantime (i.e. during callbacks) */
1582   if (NULL != client->warn_task)
1583   {
1584     GNUNET_SCHEDULER_cancel (client->warn_task);
1585     client->warn_task = NULL;
1586   }
1587   if (GNUNET_YES == client->receive_pending)
1588   {
1589     GNUNET_CONNECTION_receive_cancel (client->connection);
1590     client->receive_pending = GNUNET_NO;
1591   }
1592   GNUNET_free (client);
1593   /* we might be in soft-shutdown, test if we're done */
1594   if (NULL != server)
1595     test_monitor_clients (server);
1596 }
1597
1598
1599 /**
1600  * Disable the "CORK" feature for communication with the given client,
1601  * forcing the OS to immediately flush the buffer on transmission
1602  * instead of potentially buffering multiple messages.
1603  *
1604  * @param client handle to the client
1605  * @return #GNUNET_OK on success
1606  */
1607 int
1608 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1609 {
1610   return GNUNET_CONNECTION_disable_corking (client->connection);
1611 }
1612
1613
1614 /**
1615  * Wrapper for transmission notification that calls the original
1616  * callback and update the last activity time for our connection.
1617  *
1618  * @param cls the `struct GNUNET_SERVER_Client *`
1619  * @param size number of bytes we can transmit
1620  * @param buf where to copy the message
1621  * @return number of bytes actually transmitted
1622  */
1623 static size_t
1624 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1625 {
1626   struct GNUNET_SERVER_Client *client = cls;
1627   GNUNET_CONNECTION_TransmitReadyNotify callback;
1628
1629   client->th.cth = NULL;
1630   callback = client->th.callback;
1631   client->th.callback = NULL;
1632   client->last_activity = GNUNET_TIME_absolute_get ();
1633   return callback (client->th.callback_cls, size, buf);
1634 }
1635
1636
1637 /**
1638  * Notify us when the server has enough space to transmit
1639  * a message of the given size to the given client.
1640  *
1641  * @param client client to transmit message to
1642  * @param size requested amount of buffer space
1643  * @param timeout after how long should we give up (and call
1644  *        notify with buf NULL and size 0)?
1645  * @param callback function to call when space is available
1646  * @param callback_cls closure for @a callback
1647  * @return non-NULL if the notify callback was queued; can be used
1648  *         to cancel the request using
1649  *         #GNUNET_SERVER_notify_transmit_ready_cancel().
1650  *         NULL if we are already going to notify someone else (busy)
1651  */
1652 struct GNUNET_SERVER_TransmitHandle *
1653 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1654                                      size_t size,
1655                                      struct GNUNET_TIME_Relative timeout,
1656                                      GNUNET_CONNECTION_TransmitReadyNotify callback,
1657                                      void *callback_cls)
1658 {
1659   if (NULL != client->th.callback)
1660     return NULL;
1661   client->th.callback_cls = callback_cls;
1662   client->th.callback = callback;
1663   client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1664                                                             timeout,
1665                                                             &transmit_ready_callback_wrapper,
1666                                                             client);
1667   return &client->th;
1668 }
1669
1670
1671 /**
1672  * Abort transmission request.
1673  *
1674  * @param th request to abort
1675  */
1676 void
1677 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1678 {
1679   GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1680   th->cth = NULL;
1681   th->callback = NULL;
1682 }
1683
1684
1685 /**
1686  * Set the persistent flag on this client, used to setup client connection
1687  * to only be killed when the service it's connected to is actually dead.
1688  *
1689  * @param client the client to set the persistent flag on
1690  */
1691 void
1692 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1693 {
1694   client->persist = GNUNET_YES;
1695 }
1696
1697
1698 /**
1699  * Resume receiving from this client, we are done processing the
1700  * current request.  This function must be called from within each
1701  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1702  *
1703  * @param client client we were processing a message of
1704  * @param success #GNUNET_OK to keep the connection open and
1705  *                          continue to receive
1706  *                #GNUNET_NO to close the connection (normal behavior)
1707  *                #GNUNET_SYSERR to close the connection (signal
1708  *                          serious error)
1709  */
1710 void
1711 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1712                             int success)
1713 {
1714   if (NULL == client)
1715     return;
1716   GNUNET_assert (client->suspended > 0);
1717   client->suspended--;
1718   if (GNUNET_OK != success)
1719   {
1720     LOG (GNUNET_ERROR_TYPE_DEBUG,
1721          "GNUNET_SERVER_receive_done called with failure indication\n");
1722     if ( (client->reference_count > 0) || (client->suspended > 0) )
1723       client->shutdown_now = GNUNET_YES;
1724     else
1725       GNUNET_SERVER_client_disconnect (client);
1726     return;
1727   }
1728   if (client->suspended > 0)
1729   {
1730     LOG (GNUNET_ERROR_TYPE_DEBUG,
1731          "GNUNET_SERVER_receive_done called, but more clients pending\n");
1732     return;
1733   }
1734   if (NULL != client->warn_task)
1735   {
1736     GNUNET_SCHEDULER_cancel (client->warn_task);
1737     client->warn_task = NULL;
1738   }
1739   if (GNUNET_YES == client->in_process_client_buffer)
1740   {
1741     LOG (GNUNET_ERROR_TYPE_DEBUG,
1742          "GNUNET_SERVER_receive_done called while still in processing loop\n");
1743     return;
1744   }
1745   if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1746   {
1747     GNUNET_SERVER_client_disconnect (client);
1748     return;
1749   }
1750   LOG (GNUNET_ERROR_TYPE_DEBUG,
1751        "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1752   GNUNET_assert (NULL == client->restart_task);
1753   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing,
1754                                                    client);
1755 }
1756
1757
1758 /* end of server.c */