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