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