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