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