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