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