-fixes
[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   unsigned int k;
544   int seen;
545
546   i = 0;
547   while (NULL != serverAddr[i])
548     i++;
549   if (i > 0)
550   {
551     lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
552     i = 0;
553     j = 0;
554     while (NULL != serverAddr[i])
555     {
556       seen = 0;
557       if (i > 0)
558         for (k=0;k<i-1;k++)
559           if ( (socklen[k] == socklen[i]) &&
560                (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
561           {
562             seen = 1;
563             break;
564           }
565       if (0 != seen)
566       {
567         /* duplicate address, skip */
568         i++;
569         continue;
570       }
571       lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
572       if (NULL != lsocks[j])
573         j++;
574       i++;
575     }
576     if (0 == j)
577     {
578       if (0 != errno)
579         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
580       GNUNET_free (lsocks);
581       lsocks = NULL;
582     }
583   }
584   else
585   {
586     lsocks = NULL;
587   }
588   return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
589                                             idle_timeout, require_found);
590 }
591
592
593 /**
594  * Set the 'monitor' flag on this client.  Clients which have been
595  * marked as 'monitors' won't prevent the server from shutting down
596  * once 'GNUNET_SERVER_stop_listening' has been invoked.  The idea is
597  * that for "normal" clients we likely want to allow them to process
598  * their requests; however, monitor-clients are likely to 'never'
599  * disconnect during shutdown and thus will not be considered when
600  * determining if the server should continue to exist after
601  * 'GNUNET_SERVER_destroy' has been called.
602  *
603  * @param client the client to set the 'monitor' flag on
604  */
605 void
606 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
607 {
608   client->is_monitor = GNUNET_YES;
609 }
610
611
612 /**
613  * Helper function for 'test_monitor_clients' to trigger
614  * 'GNUNET_SERVER_destroy' after the stack has unwound.
615  *
616  * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
617  * @param tc unused
618  */
619 static void
620 do_destroy (void *cls,
621             const struct GNUNET_SCHEDULER_TaskContext *tc)
622 {
623   struct GNUNET_SERVER_Handle *server = cls;
624   GNUNET_SERVER_destroy (server);
625 }
626
627
628 /**
629  * Check if only 'monitor' clients are left.  If so, destroy the
630  * server completely.
631  *
632  * @param server server to test for full shutdown
633  */
634 static void
635 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
636 {
637   struct GNUNET_SERVER_Client *client;
638
639   if (GNUNET_YES != server->in_soft_shutdown)
640     return;
641   for (client = server->clients; NULL != client; client = client->next)
642     if (GNUNET_NO == client->is_monitor)
643       return; /* not done yet */
644   server->in_soft_shutdown = GNUNET_SYSERR;
645   GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
646                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
647 }
648
649
650 /**
651  * Stop the listen socket and get ready to shutdown the server
652  * once only 'monitor' clients are left.
653  *
654  * @param server server to stop listening on
655  */
656 void
657 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
658 {
659   unsigned int i;
660
661   LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
662   if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
663   {
664     GNUNET_SCHEDULER_cancel (server->listen_task);
665     server->listen_task = GNUNET_SCHEDULER_NO_TASK;
666   }
667   if (NULL != server->listen_sockets)
668   {
669     i = 0;
670     while (NULL != server->listen_sockets[i])
671       GNUNET_break (GNUNET_OK ==
672                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
673     GNUNET_free (server->listen_sockets);
674     server->listen_sockets = NULL;
675   }
676   if (GNUNET_NO == server->in_soft_shutdown)
677     server->in_soft_shutdown = GNUNET_YES;
678   test_monitor_clients (server);
679 }
680
681
682 /**
683  * Free resources held by this server.
684  *
685  * @param server server to destroy
686  */
687 void
688 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
689 {
690   struct HandlerList *hpos;
691   struct NotifyList *npos;
692   unsigned int i;
693
694   LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
695   if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
696   {
697     GNUNET_SCHEDULER_cancel (server->listen_task);
698     server->listen_task = GNUNET_SCHEDULER_NO_TASK;
699   }
700   if (NULL != server->listen_sockets)
701   {
702     i = 0;
703     while (NULL != server->listen_sockets[i])
704       GNUNET_break (GNUNET_OK ==
705                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
706     GNUNET_free (server->listen_sockets);
707     server->listen_sockets = NULL;
708   }
709   while (NULL != server->clients)
710     GNUNET_SERVER_client_disconnect (server->clients);
711   while (NULL != (hpos = server->handlers))
712   {
713     server->handlers = hpos->next;
714     GNUNET_free (hpos);
715   }
716   while (NULL != (npos = server->disconnect_notify_list_head))
717   {
718     npos->callback (npos->callback_cls, NULL);
719     GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
720                                  server->disconnect_notify_list_tail,
721                                  npos);
722     GNUNET_free (npos);
723   }
724   GNUNET_free (server);
725 }
726
727
728 /**
729  * Add additional handlers to an existing server.
730  *
731  * @param server the server to add handlers to
732  * @param handlers array of message handlers for
733  *        incoming messages; the last entry must
734  *        have "NULL" for the "callback"; multiple
735  *        entries for the same type are allowed,
736  *        they will be called in order of occurence.
737  *        These handlers can be removed later;
738  *        the handlers array must exist until removed
739  *        (or server is destroyed).
740  */
741 void
742 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
743                             const struct GNUNET_SERVER_MessageHandler *handlers)
744 {
745   struct HandlerList *p;
746
747   p = GNUNET_malloc (sizeof (struct HandlerList));
748   p->handlers = handlers;
749   p->next = server->handlers;
750   server->handlers = p;
751 }
752
753
754 /**
755  * Change functions used by the server to tokenize the message stream.
756  * (very rarely used).
757  *
758  * @param server server to modify
759  * @param create new tokenizer initialization function
760  * @param destroy new tokenizer destruction function
761  * @param receive new tokenizer receive function
762  * @param cls closure for 'create', 'receive', 'destroy' 
763  */
764 void
765 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
766                              GNUNET_SERVER_MstCreateCallback create,
767                              GNUNET_SERVER_MstDestroyCallback destroy,
768                              GNUNET_SERVER_MstReceiveCallback receive,
769                              void *cls)
770 {
771   server->mst_create = create;
772   server->mst_destroy = destroy;
773   server->mst_receive = receive;
774   server->mst_cls = cls;
775 }
776
777
778 /**
779  * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
780  *
781  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
782  * @param tc scheduler context (unused)
783  */
784 static void
785 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
786 {
787   struct GNUNET_SERVER_Client *client = cls;
788
789   client->warn_task =
790       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
791                                     &warn_no_receive_done, client);
792   if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
793     LOG (GNUNET_ERROR_TYPE_WARNING,
794          _
795          ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
796          (unsigned int) client->warn_type,
797          (unsigned long long)
798          GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
799 }
800
801
802 /**
803  * Disable the warning the server issues if a message is not acknowledged
804  * in a timely fashion.  Use this call if a client is intentionally delayed
805  * for a while.  Only applies to the current message.
806  *
807  * @param client client for which to disable the warning
808  */
809 void
810 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
811 {
812   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
813   {
814     GNUNET_SCHEDULER_cancel (client->warn_task);
815     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
816   }
817 }
818
819
820 /**
821  * Inject a message into the server, pretend it came
822  * from the specified client.  Delivery of the message
823  * will happen instantly (if a handler is installed;
824  * otherwise the call does nothing).
825  *
826  * @param server the server receiving the message
827  * @param sender the "pretended" sender of the message
828  *        can be NULL!
829  * @param message message to transmit
830  * @return GNUNET_OK if the message was OK and the
831  *                   connection can stay open
832  *         GNUNET_SYSERR if the connection to the
833  *         client should be shut down
834  */
835 int
836 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
837                       struct GNUNET_SERVER_Client *sender,
838                       const struct GNUNET_MessageHeader *message)
839 {
840   struct HandlerList *pos;
841   const struct GNUNET_SERVER_MessageHandler *mh;
842   unsigned int i;
843   uint16_t type;
844   uint16_t size;
845   int found;
846
847   type = ntohs (message->type);
848   size = ntohs (message->size);
849   LOG (GNUNET_ERROR_TYPE_DEBUG,
850        "Server schedules transmission of %u-byte message of type %u to client.\n",
851        size, type);
852   found = GNUNET_NO;
853   for (pos = server->handlers; NULL != pos; pos = pos->next)
854   {
855     i = 0;
856     while (pos->handlers[i].callback != NULL)
857     {
858       mh = &pos->handlers[i];
859       if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
860       {
861         if ((0 != mh->expected_size) && (mh->expected_size != size))
862         {
863 #if GNUNET8_NETWORK_IS_DEAD
864           LOG (GNUNET_ERROR_TYPE_WARNING,
865                "Expected %u bytes for message of type %u, got %u\n",
866                mh->expected_size, mh->type, size);
867           GNUNET_break_op (0);
868 #endif
869           return GNUNET_SYSERR;
870         }
871         if (NULL != sender)
872         {
873           if (0 == sender->suspended)
874           {
875             sender->warn_start = GNUNET_TIME_absolute_get ();
876             sender->warn_task =
877                 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
878                                               &warn_no_receive_done, sender);
879             sender->warn_type = type;
880           }
881           sender->suspended++;
882         }
883         mh->callback (mh->callback_cls, sender, message);
884         found = GNUNET_YES;
885       }
886       i++;
887     }
888   }
889   if (GNUNET_NO == found)
890   {
891     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
892          "Received message of unknown type %d\n", type);
893     if (GNUNET_YES == server->require_found)
894       return GNUNET_SYSERR;
895   }
896   return GNUNET_OK;
897 }
898
899
900 /**
901  * We are receiving an incoming message.  Process it.
902  *
903  * @param cls our closure (handle for the client)
904  * @param buf buffer with data received from network
905  * @param available number of bytes available in buf
906  * @param addr address of the sender
907  * @param addrlen length of addr
908  * @param errCode code indicating errors receiving, 0 for success
909  */
910 static void
911 process_incoming (void *cls, const void *buf, size_t available,
912                   const struct sockaddr *addr, socklen_t addrlen, int errCode);
913
914
915 /**
916  * Process messages from the client's message tokenizer until either
917  * the tokenizer is empty (and then schedule receiving more), or
918  * until some handler is not immediately done (then wait for restart_processing)
919  * or shutdown.
920  *
921  * @param client the client to process, RC must have already been increased
922  *        using GNUNET_SERVER_client_keep and will be decreased by one in this
923  *        function
924  * @param ret GNUNET_NO to start processing from the buffer,
925  *            GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
926  *            GNUNET_SYSERR if we should instantly abort due to error in a previous step
927  */
928 static void
929 process_mst (struct GNUNET_SERVER_Client *client, int ret)
930 {
931   while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
932          (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
933   {
934     if (GNUNET_OK == ret)
935     {
936       LOG (GNUNET_ERROR_TYPE_DEBUG,
937            "Server re-enters receive loop, timeout: %llu.\n",
938            client->idle_timeout.rel_value);
939       client->receive_pending = GNUNET_YES;
940       GNUNET_CONNECTION_receive (client->connection,
941                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
942                                  client->idle_timeout, &process_incoming,
943                                  client);
944       break;
945     }
946     LOG (GNUNET_ERROR_TYPE_DEBUG,
947          "Server processes additional messages instantly.\n");
948     if (NULL != client->server->mst_receive)
949       ret =
950           client->server->mst_receive (client->server->mst_cls, client->mst,
951                                        client, NULL, 0, GNUNET_NO, GNUNET_YES);
952     else
953       ret =
954           GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
955                                      GNUNET_YES);
956   }
957   LOG (GNUNET_ERROR_TYPE_DEBUG,
958        "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
959        ret, client->server, client->shutdown_now, client->suspended);
960   if (GNUNET_NO == ret)
961   {
962     LOG (GNUNET_ERROR_TYPE_DEBUG,
963          "Server has more data pending but is suspended.\n");
964     client->receive_pending = GNUNET_SYSERR;    /* data pending */
965   }
966   if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
967     GNUNET_SERVER_client_disconnect (client);
968   GNUNET_SERVER_client_drop (client);
969 }
970
971
972 /**
973  * We are receiving an incoming message.  Process it.
974  *
975  * @param cls our closure (handle for the client)
976  * @param buf buffer with data received from network
977  * @param available number of bytes available in buf
978  * @param addr address of the sender
979  * @param addrlen length of addr
980  * @param errCode code indicating errors receiving, 0 for success
981  */
982 static void
983 process_incoming (void *cls, const void *buf, size_t available,
984                   const struct sockaddr *addr, socklen_t addrlen, int errCode)
985 {
986   struct GNUNET_SERVER_Client *client = cls;
987   struct GNUNET_SERVER_Handle *server = client->server;
988   struct GNUNET_TIME_Absolute end;
989   struct GNUNET_TIME_Absolute now;
990   int ret;
991
992   GNUNET_assert (GNUNET_YES == client->receive_pending);
993   client->receive_pending = GNUNET_NO;
994   now = GNUNET_TIME_absolute_get ();
995   end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
996
997   if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
998       (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
999       (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1000       (end.abs_value > now.abs_value))
1001   {
1002     /* wait longer, timeout changed (i.e. due to us sending) */
1003     LOG (GNUNET_ERROR_TYPE_DEBUG,
1004          "Receive time out, but no disconnect due to sending (%p)\n",
1005          GNUNET_a2s (addr, addrlen));
1006     client->receive_pending = GNUNET_YES;
1007     GNUNET_CONNECTION_receive (client->connection,
1008                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1009                                GNUNET_TIME_absolute_get_remaining (end),
1010                                &process_incoming, client);
1011     return;
1012   }
1013   if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1014       (GNUNET_YES == client->shutdown_now) ||
1015       (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1016   {
1017     /* other side closed connection, error connecting, etc. */
1018     GNUNET_SERVER_client_disconnect (client);
1019     return;
1020   }
1021   LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1022        (unsigned int) available, GNUNET_a2s (addr, addrlen));
1023   GNUNET_SERVER_client_keep (client);
1024   client->last_activity = now;
1025
1026   if (NULL != server->mst_receive)
1027     ret =
1028         client->server->mst_receive (client->server->mst_cls, client->mst,
1029                                      client, buf, available, GNUNET_NO, GNUNET_YES);
1030   else
1031     ret =
1032         GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1033                                    GNUNET_YES);
1034   process_mst (client, ret);
1035 }
1036
1037
1038 /**
1039  * Task run to start again receiving from the network
1040  * and process requests.
1041  *
1042  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1043  * @param tc scheduler context (unused)
1044  */
1045 static void
1046 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1047 {
1048   struct GNUNET_SERVER_Client *client = cls;
1049
1050   client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1051   if (GNUNET_NO == client->receive_pending)
1052   {
1053     LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1054     client->receive_pending = GNUNET_YES;
1055     GNUNET_CONNECTION_receive (client->connection,
1056                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1057                                client->idle_timeout, &process_incoming, client);
1058     return;
1059   }
1060   LOG (GNUNET_ERROR_TYPE_DEBUG,
1061        "Server continues processing messages still in the buffer.\n");
1062   GNUNET_SERVER_client_keep (client);
1063   client->receive_pending = GNUNET_NO;
1064   process_mst (client, GNUNET_NO);
1065 }
1066
1067
1068 /**
1069  * This function is called whenever our inbound message tokenizer has
1070  * received a complete message.
1071  *
1072  * @param cls closure (struct GNUNET_SERVER_Handle)
1073  * @param client identification of the client (struct GNUNET_SERVER_Client*)
1074  * @param message the actual message
1075  */
1076 static void
1077 client_message_tokenizer_callback (void *cls, void *client,
1078                                    const struct GNUNET_MessageHeader *message)
1079 {
1080   struct GNUNET_SERVER_Handle *server = cls;
1081   struct GNUNET_SERVER_Client *sender = client;
1082   int ret;
1083
1084   LOG (GNUNET_ERROR_TYPE_DEBUG,
1085        "Tokenizer gives server message of type %u from client\n",
1086        ntohs (message->type));
1087   sender->in_process_client_buffer = GNUNET_YES;
1088   ret = GNUNET_SERVER_inject (server, sender, message);
1089   sender->in_process_client_buffer = GNUNET_NO;
1090   if (GNUNET_OK != ret)
1091     GNUNET_SERVER_client_disconnect (sender);
1092 }
1093
1094
1095 /**
1096  * Add a TCP socket-based connection to the set of handles managed by
1097  * this server.  Use this function for outgoing (P2P) connections that
1098  * we initiated (and where this server should process incoming
1099  * messages).
1100  *
1101  * @param server the server to use
1102  * @param connection the connection to manage (client must
1103  *        stop using this connection from now on)
1104  * @return the client handle (client should call
1105  *         "client_drop" on the return value eventually)
1106  */
1107 struct GNUNET_SERVER_Client *
1108 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1109                               struct GNUNET_CONNECTION_Handle *connection)
1110 {
1111   struct GNUNET_SERVER_Client *client;
1112
1113   client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1114   client->connection = connection;
1115   client->reference_count = 1;
1116   client->server = server;
1117   client->last_activity = GNUNET_TIME_absolute_get ();
1118   client->next = server->clients;
1119   client->idle_timeout = server->idle_timeout;
1120   server->clients = client;
1121   if (NULL != server->mst_create)
1122     client->mst =
1123         server->mst_create (server->mst_cls, client);
1124   else
1125     client->mst =
1126         GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1127   client->receive_pending = GNUNET_YES;
1128   GNUNET_CONNECTION_receive (client->connection,
1129                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1130                              client->idle_timeout, &process_incoming, client);
1131   return client;
1132 }
1133
1134
1135 /**
1136  * Change the timeout for a particular client.  Decreasing the timeout
1137  * may not go into effect immediately (only after the previous timeout
1138  * times out or activity happens on the socket).
1139  *
1140  * @param client the client to update
1141  * @param timeout new timeout for activities on the socket
1142  */
1143 void
1144 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1145                                   struct GNUNET_TIME_Relative timeout)
1146 {
1147   client->idle_timeout = timeout;
1148 }
1149
1150
1151 /**
1152  * Notify the server that the given client handle should
1153  * be kept (keeps the connection up if possible, increments
1154  * the internal reference counter).
1155  *
1156  * @param client the client to keep
1157  */
1158 void
1159 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1160 {
1161   client->reference_count++;
1162 }
1163
1164
1165 /**
1166  * Notify the server that the given client handle is no
1167  * longer required.  Decrements the reference counter.  If
1168  * that counter reaches zero an inactive connection maybe
1169  * closed.
1170  *
1171  * @param client the client to drop
1172  */
1173 void
1174 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1175 {
1176   GNUNET_assert (client->reference_count > 0);
1177   client->reference_count--;
1178   if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1179     GNUNET_SERVER_client_disconnect (client);
1180 }
1181
1182
1183 /**
1184  * Obtain the network address of the other party.
1185  *
1186  * @param client the client to get the address for
1187  * @param addr where to store the address
1188  * @param addrlen where to store the length of the address
1189  * @return GNUNET_OK on success
1190  */
1191 int
1192 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1193                                   void **addr, size_t * addrlen)
1194 {
1195   return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1196 }
1197
1198
1199 /**
1200  * Ask the server to notify us whenever a client disconnects.
1201  * This function is called whenever the actual network connection
1202  * is closed; the reference count may be zero or larger than zero
1203  * at this point.
1204  *
1205  * @param server the server manageing the clients
1206  * @param callback function to call on disconnect
1207  * @param callback_cls closure for callback
1208  */
1209 void
1210 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1211                                  GNUNET_SERVER_DisconnectCallback callback,
1212                                  void *callback_cls)
1213 {
1214   struct NotifyList *n;
1215
1216   n = GNUNET_malloc (sizeof (struct NotifyList));
1217   n->callback = callback;
1218   n->callback_cls = callback_cls;
1219   GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1220                                server->disconnect_notify_list_tail,
1221                                n);
1222 }
1223
1224
1225 /**
1226  * Ask the server to stop notifying us whenever a client disconnects.
1227  *
1228  * @param server the server manageing the clients
1229  * @param callback function to call on disconnect
1230  * @param callback_cls closure for callback
1231  */
1232 void
1233 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1234                                         GNUNET_SERVER_DisconnectCallback
1235                                         callback, void *callback_cls)
1236 {
1237   struct NotifyList *pos;
1238
1239   for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1240     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1241       break;
1242   if (NULL == pos)
1243   {
1244     GNUNET_break (0);
1245     return;
1246   }
1247   GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1248                                server->disconnect_notify_list_tail,
1249                                pos);
1250   GNUNET_free (pos);
1251 }
1252
1253
1254 /**
1255  * Ask the server to disconnect from the given client.
1256  * This is the same as returning GNUNET_SYSERR from a message
1257  * handler, except that it allows dropping of a client even
1258  * when not handling a message from that client.
1259  *
1260  * @param client the client to disconnect from
1261  */
1262 void
1263 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1264 {
1265   struct GNUNET_SERVER_Client *prev;
1266   struct GNUNET_SERVER_Client *pos;
1267   struct GNUNET_SERVER_Handle *server;
1268   struct NotifyList *n;
1269   unsigned int rc;
1270
1271   LOG (GNUNET_ERROR_TYPE_DEBUG,
1272        "Client is being disconnected from the server.\n");
1273   if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1274   {
1275     GNUNET_SCHEDULER_cancel (client->restart_task);
1276     client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1277   }
1278   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1279   {
1280     GNUNET_SCHEDULER_cancel (client->warn_task);
1281     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1282   }
1283   if (GNUNET_YES == client->receive_pending)
1284   {
1285     GNUNET_CONNECTION_receive_cancel (client->connection);
1286     client->receive_pending = GNUNET_NO;
1287   }
1288   server = client->server;
1289   rc = client->reference_count;
1290   if (GNUNET_YES != client->shutdown_now)
1291   {
1292     client->shutdown_now = GNUNET_YES;
1293     prev = NULL;
1294     pos = server->clients;
1295     while ((NULL != pos) && (pos != client))
1296     {
1297       prev = pos;
1298       pos = pos->next;
1299     }
1300     GNUNET_assert (NULL != pos);
1301     if (NULL == prev)
1302       server->clients = pos->next;
1303     else
1304       prev->next = pos->next;
1305     if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1306     {
1307       GNUNET_SCHEDULER_cancel (client->restart_task);
1308       client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1309     }
1310     if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1311     {
1312       GNUNET_SCHEDULER_cancel (client->warn_task);
1313       client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1314     }
1315     for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1316       n->callback (n->callback_cls, client);
1317   }
1318   if (rc > 0)
1319   {
1320     LOG (GNUNET_ERROR_TYPE_DEBUG,
1321          "RC still positive, not destroying everything.\n");
1322     return;
1323   }
1324   if (GNUNET_YES == client->in_process_client_buffer)
1325   {
1326     LOG (GNUNET_ERROR_TYPE_DEBUG,
1327          "Still processing inputs, not destroying everything.\n");
1328     return;
1329   }
1330
1331   if (GNUNET_YES == client->persist)
1332     GNUNET_CONNECTION_persist_ (client->connection);
1333   if (NULL != client->th.cth)
1334     GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1335   GNUNET_CONNECTION_destroy (client->connection);
1336
1337   if (NULL != server->mst_destroy)
1338     server->mst_destroy (server->mst_cls, client->mst);
1339   else
1340     GNUNET_SERVER_mst_destroy (client->mst);
1341   GNUNET_free (client);
1342   /* we might be in soft-shutdown, test if we're done */
1343   test_monitor_clients (server);
1344 }
1345
1346
1347 /**
1348  * Disable the "CORK" feature for communication with the given client,
1349  * forcing the OS to immediately flush the buffer on transmission
1350  * instead of potentially buffering multiple messages.
1351  *
1352  * @param client handle to the client
1353  * @return GNUNET_OK on success
1354  */
1355 int
1356 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1357 {
1358   return GNUNET_CONNECTION_disable_corking (client->connection);
1359 }
1360
1361
1362 /**
1363  * Wrapper for transmission notification that calls the original
1364  * callback and update the last activity time for our connection.
1365  *
1366  * @param cls the 'struct GNUNET_SERVER_Client'
1367  * @param size number of bytes we can transmit
1368  * @param buf where to copy the message
1369  * @return number of bytes actually transmitted
1370  */
1371 static size_t
1372 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1373 {
1374   struct GNUNET_SERVER_Client *client = cls;
1375   GNUNET_CONNECTION_TransmitReadyNotify callback;
1376   size_t ret;
1377
1378   client->th.cth = NULL;
1379   callback = client->th.callback;
1380   client->th.callback = NULL;
1381   ret = callback (client->th.callback_cls, size, buf);
1382   if (ret > 0)
1383     client->last_activity = GNUNET_TIME_absolute_get ();
1384   return ret;
1385 }
1386
1387
1388 /**
1389  * Notify us when the server has enough space to transmit
1390  * a message of the given size to the given client.
1391  *
1392  * @param client client to transmit message to
1393  * @param size requested amount of buffer space
1394  * @param timeout after how long should we give up (and call
1395  *        notify with buf NULL and size 0)?
1396  * @param callback function to call when space is available
1397  * @param callback_cls closure for callback
1398  * @return non-NULL if the notify callback was queued; can be used
1399  *           to cancel the request using
1400  *           GNUNET_SERVER_notify_transmit_ready_cancel.
1401  *         NULL if we are already going to notify someone else (busy)
1402  */
1403 struct GNUNET_SERVER_TransmitHandle *
1404 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1405                                      size_t size,
1406                                      struct GNUNET_TIME_Relative timeout,
1407                                      GNUNET_CONNECTION_TransmitReadyNotify
1408                                      callback, void *callback_cls)
1409 {
1410   if (NULL != client->th.callback)
1411     return NULL;
1412   client->th.callback_cls = callback_cls;
1413   client->th.callback = callback;
1414   client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1415                                                             timeout,
1416                                                             &transmit_ready_callback_wrapper,
1417                                                             client);
1418   return &client->th;
1419 }
1420
1421
1422 /**
1423  * Abort transmission request.
1424  *
1425  * @param th request to abort
1426  */
1427 void
1428 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1429 {
1430   GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1431   th->cth = NULL;
1432   th->callback = NULL;
1433 }
1434
1435
1436 /**
1437  * Set the persistent flag on this client, used to setup client connection
1438  * to only be killed when the service it's connected to is actually dead.
1439  *
1440  * @param client the client to set the persistent flag on
1441  */
1442 void
1443 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1444 {
1445   client->persist = GNUNET_YES;
1446 }
1447
1448
1449 /**
1450  * Resume receiving from this client, we are done processing the
1451  * current request.  This function must be called from within each
1452  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1453  *
1454  * @param client client we were processing a message of
1455  * @param success GNUNET_OK to keep the connection open and
1456  *                          continue to receive
1457  *                GNUNET_NO to close the connection (normal behavior)
1458  *                GNUNET_SYSERR to close the connection (signal
1459  *                          serious error)
1460  */
1461 void
1462 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1463 {
1464   if (NULL == client)
1465     return;
1466   GNUNET_assert (client->suspended > 0);
1467   client->suspended--;
1468   if (GNUNET_OK != success)
1469   {
1470     LOG (GNUNET_ERROR_TYPE_DEBUG,
1471          "GNUNET_SERVER_receive_done called with failure indication\n");
1472     GNUNET_SERVER_client_disconnect (client);
1473     return;
1474   }
1475   if (client->suspended > 0)
1476   {
1477     LOG (GNUNET_ERROR_TYPE_DEBUG,
1478          "GNUNET_SERVER_receive_done called, but more clients pending\n");
1479     return;
1480   }
1481   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1482   {
1483     GNUNET_SCHEDULER_cancel (client->warn_task);
1484     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1485   }
1486   if (GNUNET_YES == client->in_process_client_buffer)
1487   {
1488     LOG (GNUNET_ERROR_TYPE_DEBUG,
1489          "GNUNET_SERVER_receive_done called while still in processing loop\n");
1490     return;
1491   }
1492   if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1493   {
1494     GNUNET_SERVER_client_disconnect (client);
1495     return;
1496   }
1497   LOG (GNUNET_ERROR_TYPE_DEBUG,
1498        "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1499   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1500   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1501 }
1502
1503
1504 /* end of server.c */