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