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