WiP
[oweals/gnunet.git] / src / util / server.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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_connection_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_server_lib.h"
32 #include "gnunet_time_lib.h"
33 #include "gnunet_disk_lib.h"
34 #include "gnunet_protocols.h"
35
36 #define DEBUG_SERVER GNUNET_NO
37
38 /**
39  * List of arrays of message handlers.
40  */
41 struct HandlerList
42 {
43   /**
44    * This is a linked list.
45    */
46   struct HandlerList *next;
47
48   /**
49    * NULL-terminated array of handlers.
50    */
51   const struct GNUNET_SERVER_MessageHandler *handlers;
52 };
53
54
55 /**
56  * List of arrays of message handlers.
57  */
58 struct NotifyList
59 {
60   /**
61    * This is a linked list.
62    */
63   struct NotifyList *next;
64
65   /**
66    * Function to call.
67    */
68   GNUNET_SERVER_DisconnectCallback callback;
69
70   /**
71    * Closure for callback.
72    */
73   void *callback_cls;
74 };
75
76
77 /**
78  * @brief handle for a server
79  */
80 struct GNUNET_SERVER_Handle
81 {
82   /**
83    * List of handlers for incoming messages.
84    */
85   struct HandlerList *handlers;
86
87   /**
88    * List of our current clients.
89    */
90   struct GNUNET_SERVER_Client *clients;
91
92   /**
93    * Linked list of functions to call on disconnects by clients.
94    */
95   struct NotifyList *disconnect_notify_list;
96
97   /**
98    * Function to call for access control.
99    */
100   GNUNET_CONNECTION_AccessCheck access;
101
102   /**
103    * Closure for access.
104    */
105   void *access_cls;
106
107   /**
108    * NULL-terminated array of sockets used to listen for new
109    * connections.
110    */
111   struct GNUNET_NETWORK_Handle **listen_sockets;
112
113   /**
114    * After how long should an idle connection time
115    * out (on write).
116    */
117   struct GNUNET_TIME_Relative idle_timeout;
118
119   /**
120    * Task scheduled to do the listening.
121    */
122   GNUNET_SCHEDULER_TaskIdentifier listen_task;
123
124   /**
125    * Do we ignore messages of types that we do not understand or do we
126    * require that a handler is found (and if not kill the connection)?
127    */
128   int require_found;
129
130   /**
131    * Should all of the clients of this server continue to process
132    * connections as usual even if we get a shutdown request? (the
133    * listen socket always ignores shutdown).
134    */
135   int clients_ignore_shutdown;
136
137 };
138
139
140 /**
141  * @brief handle for a client of the server
142  */
143 struct GNUNET_SERVER_Client
144 {
145
146   /**
147    * This is a linked list.
148    */
149   struct GNUNET_SERVER_Client *next;
150
151   /**
152    * Processing of incoming data.
153    */
154   struct GNUNET_SERVER_MessageStreamTokenizer *mst;
155
156   /**
157    * Server that this client belongs to.
158    */
159   struct GNUNET_SERVER_Handle *server;
160
161   /**
162    * Client closure for callbacks.
163    */
164   struct GNUNET_CONNECTION_Handle *connection;
165
166   /**
167    * ID of task used to restart processing.
168    */
169   GNUNET_SCHEDULER_TaskIdentifier restart_task;
170
171   /**
172    * Last activity on this socket (used to time it out
173    * if reference_count == 0).
174    */
175   struct GNUNET_TIME_Absolute last_activity;
176
177   /**
178    * Number of external entities with a reference to
179    * this client object.
180    */
181   unsigned int reference_count;
182
183   /**
184    * Was processing if incoming messages suspended while
185    * we were still processing data already received?
186    * This is a counter saying how often processing was
187    * suspended (once per handler invoked).
188    */
189   unsigned int suspended;
190
191   /**
192    * Are we currently in the "process_client_buffer" function (and
193    * will hence restart the receive job on exit if suspended == 0 once
194    * we are done?).  If this is set, then "receive_done" will
195    * essentially only decrement suspended; if this is not set, then
196    * "receive_done" may need to restart the receive process (either
197    * from the side-buffer or via select/recv).
198    */
199   int in_process_client_buffer;
200
201   /**
202    * We're about to close down this client due to some serious
203    * error.
204    */
205   int shutdown_now;
206
207   /**
208    * Are we currently trying to receive? (YES if we are, NO if we are not,
209    * SYSERR if data is already available in MST).
210    */
211   int receive_pending;
212
213   /**
214    * Persist the file handle for this client no matter what happens,
215    * force the OS to close once the process actually dies.  Should only
216    * be used in special cases!
217    */
218   int persist;
219 };
220
221
222 /**
223  * Scheduler says our listen socket is ready.  Process it!
224  *
225  * @param cls handle to our server for which we are processing the listen
226  *        socket
227  * @param tc reason why we are running right now
228  */
229 static void
230 process_listen_socket (void *cls,
231                        const struct GNUNET_SCHEDULER_TaskContext *tc)
232 {
233   struct GNUNET_SERVER_Handle *server = cls;
234   struct GNUNET_CONNECTION_Handle *sock;
235   struct GNUNET_SERVER_Client *client;
236   struct GNUNET_NETWORK_FDSet *r;
237   unsigned int i;
238
239   server->listen_task = GNUNET_SCHEDULER_NO_TASK;
240   r = GNUNET_NETWORK_fdset_create ();
241   i = 0;
242   while (NULL != server->listen_sockets[i])
243     GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
244   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
245     {
246       /* ignore shutdown, someone else will take care of it! */
247       server->listen_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
248                                                          GNUNET_SCHEDULER_NO_TASK,
249                                                          GNUNET_TIME_UNIT_FOREVER_REL,
250                                                          r, NULL,
251                                                          &process_listen_socket,
252                                                          server);
253       GNUNET_NETWORK_fdset_destroy (r);
254       return;
255     }
256   i = 0;
257   while (NULL != server->listen_sockets[i])
258     {
259       if (GNUNET_NETWORK_fdset_isset
260           (tc->read_ready, server->listen_sockets[i]))
261         {
262           sock =
263             GNUNET_CONNECTION_create_from_accept (server->access,
264                                                   server->access_cls,
265                                                   server->listen_sockets[i]);
266           if (sock != NULL)
267             {
268 #if DEBUG_SERVER
269               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
270                           "Server accepted incoming connection.\n");
271 #endif
272               client = GNUNET_SERVER_connect_socket (server, sock);
273               GNUNET_CONNECTION_ignore_shutdown (sock,
274                                                  server->clients_ignore_shutdown);
275               /* decrement reference count, we don't keep "client" alive */
276               GNUNET_SERVER_client_drop (client);
277             }
278         }
279       i++;
280     }
281   /* listen for more! */
282   server->listen_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
283                                                      GNUNET_SCHEDULER_NO_TASK,
284                                                      GNUNET_TIME_UNIT_FOREVER_REL,
285                                                      r, NULL,
286                                                      &process_listen_socket,
287                                                      server);
288   GNUNET_NETWORK_fdset_destroy (r);
289 }
290
291
292 /**
293  * Create and initialize a listen socket for the server.
294  *
295  * @param serverAddr address to listen on
296  * @param socklen length of address
297  * @return NULL on error, otherwise the listen socket
298  */
299 static struct GNUNET_NETWORK_Handle *
300 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
301 {
302   const static int on = 1;
303   struct GNUNET_NETWORK_Handle *sock;
304   uint16_t port;
305   int eno;
306
307   switch (serverAddr->sa_family)
308     {
309     case AF_INET:
310       port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
311       break;
312     case AF_INET6:
313       port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
314       break;
315     default:
316       port = 0;
317       break;
318     }
319   sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
320   if (NULL == sock)
321     {
322       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
323       errno = 0;
324       return NULL;
325     }
326   if (port != 0) 
327     {
328       if (GNUNET_NETWORK_socket_setsockopt
329           (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
330         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
331                              "setsockopt");
332 #ifdef IPV6_V6ONLY
333       if ( (serverAddr->sa_family == AF_INET6) &&
334            (GNUNET_NETWORK_socket_setsockopt
335             (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK) )
336         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
337                              "setsockopt");
338 #endif
339     }
340   /* bind the socket */
341   if (GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen) != GNUNET_OK)
342     {
343       eno = errno;
344       if (errno != EADDRINUSE)
345         {
346           /* we don't log 'EADDRINUSE' here since an IPv4 bind may
347              fail if we already took the port on IPv6; if both IPv4 and
348              IPv6 binds fail, then our caller will log using the
349              errno preserved in 'eno' */
350           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
351           if (port != 0)
352             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
353                         _
354                         ("`%s' failed for port %d (%s).\n"),
355                         "bind", port,
356                         (serverAddr->sa_family == AF_INET) ? "IPv4" : "IPv6");
357           eno = 0;
358         }
359       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
360       errno = eno;
361       return NULL;
362     }
363   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
364     {
365       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
366       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
367       errno = 0;
368       return NULL;
369     }
370 #if DEBUG_SERVER
371   if (port != 0)
372     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
373                 "Server starts to listen on port %u.\n", port);
374 #endif
375   return sock;
376 }
377
378
379 /**
380  * Create a new server.
381  *
382  * @param access function for access control
383  * @param access_cls closure for access
384  * @param lsocks NULL-terminated array of listen sockets
385  * @param idle_timeout after how long should we timeout idle connections?
386  * @param require_found if YES, connections sending messages of unknown type
387  *        will be closed
388  * @return handle for the new server, NULL on error
389  *         (typically, "port" already in use)
390  */
391 struct GNUNET_SERVER_Handle *
392 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
393                                    struct GNUNET_NETWORK_Handle **lsocks,
394                                    struct GNUNET_TIME_Relative
395                                    idle_timeout,
396                                    int require_found)
397 {
398   struct GNUNET_SERVER_Handle *ret;
399   struct GNUNET_NETWORK_FDSet *r;
400   int i;
401
402   ret = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
403   ret->idle_timeout = idle_timeout;
404   ret->listen_sockets = lsocks;
405   ret->access = access;
406   ret->access_cls = access_cls;
407   ret->require_found = require_found;
408   if (lsocks != NULL)
409     {
410       r = GNUNET_NETWORK_fdset_create ();
411       i = 0;
412       while (NULL != ret->listen_sockets[i])
413         GNUNET_NETWORK_fdset_set (r, ret->listen_sockets[i++]);
414       ret->listen_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
415                                                       GNUNET_SCHEDULER_NO_TASK,
416                                                       GNUNET_TIME_UNIT_FOREVER_REL,
417                                                       r, NULL,
418                                                       &process_listen_socket,
419                                                       ret);
420       GNUNET_NETWORK_fdset_destroy (r);
421     }
422   return ret;
423 }
424
425
426 /**
427  * Create a new server.
428  *
429  * @param access function for access control
430  * @param access_cls closure for access
431  * @param serverAddr address to listen on (including port), NULL terminated array
432  * @param socklen length of serverAddr
433  * @param idle_timeout after how long should we timeout idle connections?
434  * @param require_found if YES, connections sending messages of unknown type
435  *        will be closed
436  * @return handle for the new server, NULL on error
437  *         (typically, "port" already in use)
438  */
439 struct GNUNET_SERVER_Handle *
440 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access,
441                       void *access_cls,
442                       struct sockaddr *const *serverAddr,
443                       const socklen_t * socklen,
444                       struct GNUNET_TIME_Relative
445                       idle_timeout, int require_found)
446 {
447   struct GNUNET_NETWORK_Handle **lsocks;
448   unsigned int i;
449   unsigned int j;
450
451   i = 0;
452   while (serverAddr[i] != NULL)
453     i++;
454   if (i > 0)
455     {
456       lsocks =
457         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
458       i = 0;
459       j = 0;
460       while (serverAddr[i] != NULL)
461         {
462           lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
463           if (lsocks[j] != NULL)
464             j++;
465           i++;
466         }
467       if (j == 0)
468         {
469           if (errno != 0)
470             GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");          
471           GNUNET_free (lsocks);
472           lsocks = NULL;
473         }
474     }
475   else
476     {
477       lsocks = NULL;
478     }
479   return GNUNET_SERVER_create_with_sockets (access, access_cls,
480                                             lsocks,
481                                             idle_timeout,
482                                             require_found);
483 }
484
485
486 /**
487  * Free resources held by this server.
488  *
489  * @param s server to destroy
490  */
491 void
492 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *s)
493 {
494   struct HandlerList *hpos;
495   struct NotifyList *npos;
496   unsigned int i;
497
498 #if DEBUG_SERVER
499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
500 #endif
501   if (GNUNET_SCHEDULER_NO_TASK != s->listen_task)
502     {
503       GNUNET_SCHEDULER_cancel (s->listen_task);
504       s->listen_task = GNUNET_SCHEDULER_NO_TASK;
505     }
506   if (s->listen_sockets != NULL)
507     {
508       i = 0;
509       while (s->listen_sockets[i] != NULL)
510         GNUNET_break (GNUNET_OK ==
511                       GNUNET_NETWORK_socket_close (s->listen_sockets[i++]));
512       GNUNET_free (s->listen_sockets);
513       s->listen_sockets = NULL;
514     }
515   while (s->clients != NULL)
516     GNUNET_SERVER_client_disconnect (s->clients);
517   while (NULL != (hpos = s->handlers))
518     {
519       s->handlers = hpos->next;
520       GNUNET_free (hpos);
521     }
522   while (NULL != (npos = s->disconnect_notify_list))
523     {
524       npos->callback (npos->callback_cls, NULL);
525       s->disconnect_notify_list = npos->next;
526       GNUNET_free (npos);
527     }
528   GNUNET_free (s);
529 }
530
531
532 /**
533  * Add additional handlers to an existing server.
534  *
535  * @param server the server to add handlers to
536  * @param handlers array of message handlers for
537  *        incoming messages; the last entry must
538  *        have "NULL" for the "callback"; multiple
539  *        entries for the same type are allowed,
540  *        they will be called in order of occurence.
541  *        These handlers can be removed later;
542  *        the handlers array must exist until removed
543  *        (or server is destroyed).
544  */
545 void
546 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
547                             const struct GNUNET_SERVER_MessageHandler
548                             *handlers)
549 {
550   struct HandlerList *p;
551
552   p = GNUNET_malloc (sizeof (struct HandlerList));
553   p->handlers = handlers;
554   p->next = server->handlers;
555   server->handlers = p;
556 }
557
558
559 /**
560  * Inject a message into the server, pretend it came
561  * from the specified client.  Delivery of the message
562  * will happen instantly (if a handler is installed;
563  * otherwise the call does nothing).
564  *
565  * @param server the server receiving the message
566  * @param sender the "pretended" sender of the message
567  *        can be NULL!
568  * @param message message to transmit
569  * @return GNUNET_OK if the message was OK and the
570  *                   connection can stay open
571  *         GNUNET_SYSERR if the connection to the
572  *         client should be shut down
573  */
574 int
575 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
576                       struct GNUNET_SERVER_Client *sender,
577                       const struct GNUNET_MessageHeader *message)
578 {
579   struct HandlerList *pos;
580   const struct GNUNET_SERVER_MessageHandler *mh;
581   unsigned int i;
582   uint16_t type;
583   uint16_t size;
584   int found;
585
586   type = ntohs (message->type);
587   size = ntohs (message->size);
588 #if DEBUG_SERVER
589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
590               "Server schedules transmission of %u-byte message of type %u to client.\n",
591               size, type);
592 #endif
593   pos = server->handlers;
594   found = GNUNET_NO;
595   while (pos != NULL)
596     {
597       i = 0;
598       while (pos->handlers[i].callback != NULL)
599         {
600           mh = &pos->handlers[i];
601           if ( (mh->type == type) ||
602                (mh->type == GNUNET_MESSAGE_TYPE_ALL) )
603             {
604               if ((mh->expected_size != 0) && (mh->expected_size != size))
605                 {
606 #if GNUNET8_NETWORK_IS_DEAD
607                   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
608                               "Expected %u bytes for message of type %u, got %u\n",
609                               mh->expected_size,
610                               mh->type,
611                               size);
612                   GNUNET_break_op (0);
613 #endif
614                   return GNUNET_SYSERR;
615                 }
616               if (sender != NULL)
617                 sender->suspended++;
618               mh->callback (mh->callback_cls, sender, message);
619               found = GNUNET_YES;
620             }
621           i++;
622         }
623       pos = pos->next;
624     }
625   if (found == GNUNET_NO)
626     {
627       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
628                   "Received message of unknown type %d\n",
629                   type);
630       if (server->require_found == GNUNET_YES)
631         return GNUNET_SYSERR;
632     }
633   return GNUNET_OK;
634 }
635
636
637 /**
638  * We are receiving an incoming message.  Process it.
639  *
640  * @param cls our closure (handle for the client)
641  * @param buf buffer with data received from network
642  * @param available number of bytes available in buf
643  * @param addr address of the sender
644  * @param addrlen length of addr
645  * @param errCode code indicating errors receiving, 0 for success
646  */
647 static void
648 process_incoming (void *cls,
649                   const void *buf,
650                   size_t available,
651                   const struct sockaddr *addr, 
652                   socklen_t addrlen, int errCode);
653
654
655 /**
656  * Process messages from the client's message tokenizer until either
657  * the tokenizer is empty (and then schedule receiving more), or 
658  * until some handler is not immediately done (then wait for restart_processing)
659  * or shutdown.
660  *
661  * @param client the client to process, RC must have already been increased
662  *        using GNUNET_SERVER_client_keep and will be decreased by one in this
663  *        function
664  * @param ret GNUNET_NO to start processing from the buffer,
665  *            GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
666  *            GNUNET_SYSERR if we should instantly abort due to error in a previous step
667  */
668 static void
669 process_mst (struct GNUNET_SERVER_Client *client,
670              int ret)
671 {
672   while ( (ret != GNUNET_SYSERR) && 
673           (client->server != NULL) &&
674           (GNUNET_YES != client->shutdown_now) &&
675           (0 == client->suspended) )
676     {
677       if (ret == GNUNET_OK)
678         {
679           client->receive_pending = GNUNET_YES;
680 #if DEBUG_SERVER
681           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682                       "Server re-enters receive loop.\n");
683 #endif
684           GNUNET_CONNECTION_receive (client->connection,
685                                      GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
686                                      client->server->idle_timeout, 
687                                      &process_incoming, client);
688           break;
689         }
690 #if DEBUG_SERVER
691       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server processes additional messages instantly.\n");
692 #endif
693       ret = GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO, GNUNET_YES);
694     }
695 #if DEBUG_SERVER
696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
697               "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
698               ret,
699               client->server,
700               client->shutdown_now,
701               client->suspended);
702 #endif
703
704   if (ret == GNUNET_NO)
705     {
706 #if DEBUG_SERVER
707       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
708                   "Server has more data pending but is suspended.\n");
709 #endif
710       client->receive_pending = GNUNET_SYSERR; /* data pending */
711     }
712   if ( (ret == GNUNET_SYSERR) ||
713        (GNUNET_YES == client->shutdown_now) )
714     GNUNET_SERVER_client_disconnect (client);
715   GNUNET_SERVER_client_drop (client);
716 }
717
718
719 /**
720  * We are receiving an incoming message.  Process it.
721  *
722  * @param cls our closure (handle for the client)
723  * @param buf buffer with data received from network
724  * @param available number of bytes available in buf
725  * @param addr address of the sender
726  * @param addrlen length of addr
727  * @param errCode code indicating errors receiving, 0 for success
728  */
729 static void
730 process_incoming (void *cls,
731                   const void *buf,
732                   size_t available,
733                   const struct sockaddr *addr, 
734                   socklen_t addrlen, int errCode)
735 {
736   struct GNUNET_SERVER_Client *client = cls;
737   struct GNUNET_SERVER_Handle *server = client->server;
738   int ret;
739
740   GNUNET_assert (client->receive_pending == GNUNET_YES);
741   client->receive_pending = GNUNET_NO;
742   if ((buf == NULL) ||
743       (available == 0) ||
744       (errCode != 0) ||
745       (server == NULL) ||
746       (client->shutdown_now == GNUNET_YES) ||
747       (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
748     {
749       /* other side closed connection, error connecting, etc. */
750       GNUNET_SERVER_client_disconnect (client);
751       return;
752     }
753 #if DEBUG_SERVER
754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755               "Server receives %u bytes from `%s'.\n",
756               (unsigned int) available, 
757               GNUNET_a2s (addr, addrlen));
758 #endif
759   GNUNET_SERVER_client_keep (client);
760   client->last_activity = GNUNET_TIME_absolute_get ();
761   ret = GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO, GNUNET_YES);
762   process_mst (client, ret);
763 }
764
765
766 /**
767  * Task run to start again receiving from the network
768  * and process requests.
769  *
770  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
771  * @param tc scheduler context (unused)
772  */
773 static void
774 restart_processing (void *cls, 
775                     const struct GNUNET_SCHEDULER_TaskContext *tc)
776 {
777   struct GNUNET_SERVER_Client *client = cls;
778   struct GNUNET_SERVER_Handle *server = client->server;
779
780   client->restart_task = GNUNET_SCHEDULER_NO_TASK;
781   if ( (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) &&
782        (GNUNET_NO == server->clients_ignore_shutdown) )
783     {
784       GNUNET_SERVER_client_disconnect (client);
785       return;
786     }  
787   if (client->receive_pending == GNUNET_NO)
788     {
789 #if DEBUG_SERVER
790       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791                   "Server begins to read again from client.\n");
792 #endif
793       client->receive_pending = GNUNET_YES;
794       GNUNET_CONNECTION_receive (client->connection,
795                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
796                                  client->server->idle_timeout, &process_incoming, client);
797       return;
798     }
799 #if DEBUG_SERVER
800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801               "Server continues processing messages still in the buffer.\n");
802 #endif
803   GNUNET_SERVER_client_keep (client);
804   client->receive_pending = GNUNET_NO;
805   process_mst (client, GNUNET_NO);
806 }
807
808
809 /**
810  * This function is called whenever our inbound message tokenizer has
811  * received a complete message.
812  *
813  * @param cls closure (struct GNUNET_SERVER_Handle)
814  * @param client identification of the client (struct GNUNET_SERVER_Client*)
815  * @param message the actual message
816  */
817 static void
818 client_message_tokenizer_callback (void *cls,
819                                    void *client,
820                                    const struct GNUNET_MessageHeader *message)
821 {
822   struct GNUNET_SERVER_Handle *server = cls;
823   struct GNUNET_SERVER_Client *sender = client;
824   int ret;
825
826 #if DEBUG_SERVER
827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
828               "Tokenizer gives server message of type %u from client\n",
829               ntohs (message->type));
830 #endif
831   sender->in_process_client_buffer = GNUNET_YES;
832   ret = GNUNET_SERVER_inject (server, sender, message);
833   sender->in_process_client_buffer = GNUNET_NO;
834   if (GNUNET_OK != ret)
835     GNUNET_SERVER_client_disconnect (sender); 
836 }
837
838
839 /**
840  * Add a TCP socket-based connection to the set of handles managed by
841  * this server.  Use this function for outgoing (P2P) connections that
842  * we initiated (and where this server should process incoming
843  * messages).
844  *
845  * @param server the server to use
846  * @param connection the connection to manage (client must
847  *        stop using this connection from now on)
848  * @return the client handle (client should call
849  *         "client_drop" on the return value eventually)
850  */
851 struct GNUNET_SERVER_Client *
852 GNUNET_SERVER_connect_socket (struct
853                               GNUNET_SERVER_Handle
854                               *server,
855                               struct GNUNET_CONNECTION_Handle *connection)
856 {
857   struct GNUNET_SERVER_Client *client;
858
859   client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
860   client->connection = connection;
861   client->mst = GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
862                                           server);
863   client->reference_count = 1;
864   client->server = server;
865   client->last_activity = GNUNET_TIME_absolute_get ();
866   client->next = server->clients;
867   server->clients = client;
868   client->receive_pending = GNUNET_YES;
869   GNUNET_CONNECTION_receive (client->connection,
870                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
871                              server->idle_timeout, &process_incoming, client);
872   return client;
873 }
874
875
876 /**
877  * Notify the server that the given client handle should
878  * be kept (keeps the connection up if possible, increments
879  * the internal reference counter).
880  *
881  * @param client the client to keep
882  */
883 void
884 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
885 {
886   client->reference_count++;
887 }
888
889
890 /**
891  * Notify the server that the given client handle is no
892  * longer required.  Decrements the reference counter.  If
893  * that counter reaches zero an inactive connection maybe
894  * closed.
895  *
896  * @param client the client to drop
897  */
898 void
899 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
900 {
901   GNUNET_assert (client->reference_count > 0);
902   client->reference_count--;
903   if ( (client->shutdown_now == GNUNET_YES) && 
904        (client->reference_count == 0) )
905     GNUNET_SERVER_client_disconnect (client);
906 }
907
908
909 /**
910  * Obtain the network address of the other party.
911  *
912  * @param client the client to get the address for
913  * @param addr where to store the address
914  * @param addrlen where to store the length of the address
915  * @return GNUNET_OK on success
916  */
917 int
918 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
919                                   void **addr, size_t * addrlen)
920 {
921   return GNUNET_CONNECTION_get_address (client->connection,
922                                         addr, addrlen);
923 }
924
925
926 /**
927  * Ask the server to notify us whenever a client disconnects.
928  * This function is called whenever the actual network connection
929  * is closed; the reference count may be zero or larger than zero
930  * at this point.
931  *
932  * @param server the server manageing the clients
933  * @param callback function to call on disconnect
934  * @param callback_cls closure for callback
935  */
936 void
937 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
938                                  GNUNET_SERVER_DisconnectCallback callback,
939                                  void *callback_cls)
940 {
941   struct NotifyList *n;
942
943   n = GNUNET_malloc (sizeof (struct NotifyList));
944   n->callback = callback;
945   n->callback_cls = callback_cls;
946   n->next = server->disconnect_notify_list;
947   server->disconnect_notify_list = n;
948 }
949
950
951 /**
952  * Ask the server to stop notifying us whenever a client disconnects.
953  *
954  * @param server the server manageing the clients
955  * @param callback function to call on disconnect
956  * @param callback_cls closure for callback
957  */
958 void
959 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
960                                         GNUNET_SERVER_DisconnectCallback callback,
961                                         void *callback_cls)
962 {
963   struct NotifyList *pos;
964   struct NotifyList *prev;
965
966   prev = NULL;
967   pos = server->disconnect_notify_list;
968   while (pos != NULL)
969     {
970       if ( (pos->callback == callback) &&
971            (pos->callback_cls == callback_cls ) )
972         break;
973       prev = pos;
974       pos = pos->next;
975     }
976   if (pos == NULL)
977     {
978       GNUNET_break (0);
979       return;
980     }
981   if (prev == NULL)
982     server->disconnect_notify_list = pos->next;
983   else
984     prev->next = pos->next;
985   GNUNET_free (pos);
986 }
987
988
989 /**
990  * Ask the server to disconnect from the given client.
991  * This is the same as returning GNUNET_SYSERR from a message
992  * handler, except that it allows dropping of a client even
993  * when not handling a message from that client.
994  *
995  * @param client the client to disconnect from
996  */
997 void
998 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
999 {
1000   struct GNUNET_SERVER_Client *prev;
1001   struct GNUNET_SERVER_Client *pos;
1002   struct GNUNET_SERVER_Handle *server;
1003   struct NotifyList *n;
1004   unsigned int rc;
1005
1006 #if DEBUG_SERVER
1007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1008               "Client is being disconnected from the server.\n");
1009 #endif
1010   if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1011     {
1012       GNUNET_SCHEDULER_cancel (client->restart_task);
1013       client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1014     }
1015   if (GNUNET_YES == client->receive_pending)
1016     {
1017       GNUNET_CONNECTION_receive_cancel (client->connection);
1018       client->receive_pending = GNUNET_NO;
1019     }
1020
1021   rc = client->reference_count;  
1022   if (client->server != NULL)
1023     {
1024       server = client->server;
1025       client->server = NULL;
1026       client->shutdown_now = GNUNET_YES;
1027       prev = NULL;
1028       pos = server->clients;
1029       while ((pos != NULL) && (pos != client))
1030         {
1031           prev = pos;
1032           pos = pos->next;
1033         }
1034       GNUNET_assert (pos != NULL);
1035       if (prev == NULL)
1036         server->clients = pos->next;
1037       else
1038         prev->next = pos->next;
1039       if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1040         {
1041           GNUNET_SCHEDULER_cancel (client->restart_task);
1042           client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1043         }
1044       n = server->disconnect_notify_list;
1045       while (n != NULL)
1046         {
1047           n->callback (n->callback_cls, client);
1048           n = n->next;
1049         }
1050     }
1051   if (rc > 0)
1052     {
1053 #if DEBUG_SERVER
1054       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1055                   "RC still positive, not destroying everything.\n");
1056 #endif
1057       return;
1058     }
1059   if (client->in_process_client_buffer == GNUNET_YES)
1060     {
1061 #if DEBUG_SERVER
1062       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063                   "Still processing inputs, not destroying everything.\n");
1064 #endif
1065       return;
1066     }
1067
1068   if (client->persist == GNUNET_YES)
1069     GNUNET_CONNECTION_persist_ (client->connection);  
1070   GNUNET_CONNECTION_destroy (client->connection, GNUNET_NO);
1071   GNUNET_SERVER_mst_destroy (client->mst);
1072   GNUNET_free (client);  
1073 }
1074
1075
1076 /**
1077  * Notify us when the server has enough space to transmit
1078  * a message of the given size to the given client.
1079  *
1080  * @param client client to transmit message to
1081  * @param size requested amount of buffer space
1082  * @param timeout after how long should we give up (and call
1083  *        notify with buf NULL and size 0)?
1084  * @param callback function to call when space is available
1085  * @param callback_cls closure for callback
1086  * @return non-NULL if the notify callback was queued; can be used
1087  *           to cancel the request using
1088  *           GNUNET_CONNECTION_notify_transmit_ready_cancel.
1089  *         NULL if we are already going to notify someone else (busy)
1090  */
1091 struct GNUNET_CONNECTION_TransmitHandle *
1092 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1093                                      size_t size,
1094                                      struct GNUNET_TIME_Relative timeout,
1095                                      GNUNET_CONNECTION_TransmitReadyNotify
1096                                      callback, void *callback_cls)
1097 {
1098   return GNUNET_CONNECTION_notify_transmit_ready (client->connection,
1099                                                   size,
1100                                                   timeout, callback, callback_cls);
1101 }
1102
1103 /**
1104  * Set the persistent flag on this client, used to setup client connection
1105  * to only be killed when the service it's connected to is actually dead.
1106  *
1107  * @param client the client to set the persistent flag on
1108  */
1109 void
1110 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1111 {
1112   client->persist = GNUNET_YES;
1113 }
1114
1115 /**
1116  * Resume receiving from this client, we are done processing the
1117  * current request.  This function must be called from within each
1118  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1119  *
1120  * @param client client we were processing a message of
1121  * @param success GNUNET_OK to keep the connection open and
1122  *                          continue to receive
1123  *                GNUNET_NO to close the connection (normal behavior)
1124  *                GNUNET_SYSERR to close the connection (signal
1125  *                          serious error)
1126  */
1127 void
1128 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1129 {
1130   if (client == NULL)
1131     return;
1132   GNUNET_assert (client->suspended > 0);
1133   client->suspended--;
1134   if (success != GNUNET_OK)
1135     {
1136 #if DEBUG_SERVER
1137       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1138                   "GNUNET_SERVER_receive_done called with failure indication\n");
1139 #endif
1140       GNUNET_SERVER_client_disconnect (client);
1141       return;
1142     }
1143   if (client->suspended > 0)
1144     {
1145 #if DEBUG_SERVER
1146       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147                   "GNUNET_SERVER_receive_done called, but more clients pending\n");
1148 #endif
1149       return;
1150     }
1151   if (client->in_process_client_buffer == GNUNET_YES)
1152     {
1153 #if DEBUG_SERVER
1154       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1155                   "GNUNET_SERVER_receive_done called while still in processing loop\n");
1156 #endif
1157       return;
1158     }
1159   if (client->server == NULL)
1160     {
1161       GNUNET_SERVER_client_disconnect (client);
1162       return;
1163     }
1164 #if DEBUG_SERVER
1165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1166               "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1167 #endif
1168   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1169   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing,
1170                                                    client);
1171 }
1172
1173
1174 /**
1175  * Configure this server's connections to continue handling client
1176  * requests as usual even after we get a shutdown signal.  The change
1177  * only applies to clients that connect to the server from the outside
1178  * using TCP after this call.  Clients managed previously or those
1179  * added using GNUNET_SERVER_connect_socket and
1180  * GNUNET_SERVER_connect_callback are not affected by this option.
1181  *
1182  * @param h server handle
1183  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1184  */
1185 void
1186 GNUNET_SERVER_ignore_shutdown (struct GNUNET_SERVER_Handle *h, int do_ignore)
1187 {
1188   h->clients_ignore_shutdown = do_ignore;
1189 }
1190
1191 /* end of server.c */