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