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