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