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