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