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