504391bc7ef4689646a987f5e7c3759e44f01c9b
[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    *
189    */
190   GNUNET_CONNECTION_TransmitReadyNotify callback;
191
192   /**
193    * callback
194    */
195   void *callback_cls;
196
197   /**
198    * After how long should an idle connection time
199    * out (on write).
200    */
201   struct GNUNET_TIME_Relative idle_timeout;
202
203   /**
204    * Number of external entities with a reference to
205    * this client object.
206    */
207   unsigned int reference_count;
208
209   /**
210    * Was processing if incoming messages suspended while
211    * we were still processing data already received?
212    * This is a counter saying how often processing was
213    * suspended (once per handler invoked).
214    */
215   unsigned int suspended;
216
217   /**
218    * Are we currently in the "process_client_buffer" function (and
219    * will hence restart the receive job on exit if suspended == 0 once
220    * we are done?).  If this is set, then "receive_done" will
221    * essentially only decrement suspended; if this is not set, then
222    * "receive_done" may need to restart the receive process (either
223    * from the side-buffer or via select/recv).
224    */
225   int in_process_client_buffer;
226
227   /**
228    * We're about to close down this client due to some serious
229    * error.
230    */
231   int shutdown_now;
232
233   /**
234    * Are we currently trying to receive? (YES if we are, NO if we are not,
235    * SYSERR if data is already available in MST).
236    */
237   int receive_pending;
238
239   /**
240    * Persist the file handle for this client no matter what happens,
241    * force the OS to close once the process actually dies.  Should only
242    * be used in special cases!
243    */
244   int persist;
245
246   /**
247    * Type of last message processed (for warn_no_receive_done).
248    */
249   uint16_t warn_type;
250 };
251
252
253 /**
254  * Scheduler says our listen socket is ready.  Process it!
255  *
256  * @param cls handle to our server for which we are processing the listen
257  *        socket
258  * @param tc reason why we are running right now
259  */
260 static void
261 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
262 {
263   struct GNUNET_SERVER_Handle *server = cls;
264   struct GNUNET_CONNECTION_Handle *sock;
265   struct GNUNET_SERVER_Client *client;
266   struct GNUNET_NETWORK_FDSet *r;
267   unsigned int i;
268
269   server->listen_task = GNUNET_SCHEDULER_NO_TASK;
270   r = GNUNET_NETWORK_fdset_create ();
271   i = 0;
272   while (NULL != server->listen_sockets[i])
273     GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
274   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
275   {
276     /* ignore shutdown, someone else will take care of it! */
277     server->listen_task =
278         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
279                                      GNUNET_SCHEDULER_NO_TASK,
280                                      GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
281                                      &process_listen_socket, server);
282     GNUNET_NETWORK_fdset_destroy (r);
283     return;
284   }
285   i = 0;
286   while (NULL != server->listen_sockets[i])
287   {
288     if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
289     {
290       sock =
291           GNUNET_CONNECTION_create_from_accept (server->access,
292                                                 server->access_cls,
293                                                 server->listen_sockets[i]);
294       if (sock != NULL)
295       {
296 #if DEBUG_SERVER
297         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
298                     "Server accepted incoming connection.\n");
299 #endif
300         client = GNUNET_SERVER_connect_socket (server, sock);
301         GNUNET_CONNECTION_ignore_shutdown (sock,
302                                            server->clients_ignore_shutdown);
303         /* decrement reference count, we don't keep "client" alive */
304         GNUNET_SERVER_client_drop (client);
305       }
306     }
307     i++;
308   }
309   /* listen for more! */
310   server->listen_task =
311       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
312                                    GNUNET_SCHEDULER_NO_TASK,
313                                    GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
314                                    &process_listen_socket, server);
315   GNUNET_NETWORK_fdset_destroy (r);
316 }
317
318
319 /**
320  * Create and initialize a listen socket for the server.
321  *
322  * @param serverAddr address to listen on
323  * @param socklen length of address
324  * @return NULL on error, otherwise the listen socket
325  */
326 static struct GNUNET_NETWORK_Handle *
327 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
328 {
329   const static int on = 1;
330   struct GNUNET_NETWORK_Handle *sock;
331   uint16_t port;
332   int eno;
333
334   switch (serverAddr->sa_family)
335   {
336   case AF_INET:
337     port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
338     break;
339   case AF_INET6:
340     port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
341     break;
342   case AF_UNIX:
343     port = 0;
344     break;
345   default:
346     GNUNET_break (0);
347     port = 0;
348     break;
349   }
350   sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
351   if (NULL == sock)
352   {
353     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
354     errno = 0;
355     return NULL;
356   }
357   if (port != 0)
358   {
359     if (GNUNET_NETWORK_socket_setsockopt
360         (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
361       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
362                            "setsockopt");
363 #ifdef IPV6_V6ONLY
364     if ((serverAddr->sa_family == AF_INET6) &&
365         (GNUNET_NETWORK_socket_setsockopt
366          (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
367       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
368                            "setsockopt");
369 #endif
370   }
371   /* bind the socket */
372   if (GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen) != GNUNET_OK)
373   {
374     eno = errno;
375     if (errno != EADDRINUSE)
376     {
377       /* we don't log 'EADDRINUSE' here since an IPv4 bind may
378        * fail if we already took the port on IPv6; if both IPv4 and
379        * IPv6 binds fail, then our caller will log using the
380        * errno preserved in 'eno' */
381       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
382       if (port != 0)
383         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
384                     _("`%s' failed for port %d (%s).\n"), "bind", port,
385                     (serverAddr->sa_family == AF_INET) ? "IPv4" : "IPv6");
386       eno = 0;
387     }
388     else
389     {
390       if (port != 0)
391         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
392                     _("`%s' failed for port %d (%s): address already in use\n"),
393                     "bind", port,
394                     (serverAddr->sa_family == AF_INET) ? "IPv4" : "IPv6");
395       else if (serverAddr->sa_family == AF_UNIX)
396         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
397                     _("`%s' failed for `%s': address already in use\n"), "bind",
398                     ((const struct sockaddr_un *) serverAddr)->sun_path);
399
400     }
401     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
402     errno = eno;
403     return NULL;
404   }
405   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
406   {
407     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
408     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
409     errno = 0;
410     return NULL;
411   }
412 #if DEBUG_SERVER
413   if (port != 0)
414     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
415                 "Server starts to listen on port %u.\n", port);
416 #endif
417   return sock;
418 }
419
420
421 /**
422  * Create a new server.
423  *
424  * @param access function for access control
425  * @param access_cls closure for access
426  * @param lsocks NULL-terminated array of listen sockets
427  * @param idle_timeout after how long should we timeout idle connections?
428  * @param require_found if YES, connections sending messages of unknown type
429  *        will be closed
430  * @return handle for the new server, NULL on error
431  *         (typically, "port" already in use)
432  */
433 struct GNUNET_SERVER_Handle *
434 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
435                                    void *access_cls,
436                                    struct GNUNET_NETWORK_Handle **lsocks,
437                                    struct GNUNET_TIME_Relative idle_timeout,
438                                    int require_found)
439 {
440   struct GNUNET_SERVER_Handle *ret;
441   struct GNUNET_NETWORK_FDSet *r;
442   int i;
443
444   ret = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
445   ret->idle_timeout = idle_timeout;
446   ret->listen_sockets = lsocks;
447   ret->access = access;
448   ret->access_cls = access_cls;
449   ret->require_found = require_found;
450   if (lsocks != NULL)
451   {
452     r = GNUNET_NETWORK_fdset_create ();
453     i = 0;
454     while (NULL != ret->listen_sockets[i])
455       GNUNET_NETWORK_fdset_set (r, ret->listen_sockets[i++]);
456     ret->listen_task =
457         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
458                                      GNUNET_SCHEDULER_NO_TASK,
459                                      GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
460                                      &process_listen_socket, ret);
461     GNUNET_NETWORK_fdset_destroy (r);
462   }
463   return ret;
464 }
465
466
467 /**
468  * Create a new server.
469  *
470  * @param access function for access control
471  * @param access_cls closure for access
472  * @param serverAddr address to listen on (including port), NULL terminated array
473  * @param socklen length of serverAddr
474  * @param idle_timeout after how long should we timeout idle connections?
475  * @param require_found if YES, connections sending messages of unknown type
476  *        will be closed
477  * @return handle for the new server, NULL on error
478  *         (typically, "port" already in use)
479  */
480 struct GNUNET_SERVER_Handle *
481 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
482                       struct sockaddr *const *serverAddr,
483                       const socklen_t * socklen,
484                       struct GNUNET_TIME_Relative idle_timeout,
485                       int require_found)
486 {
487   struct GNUNET_NETWORK_Handle **lsocks;
488   unsigned int i;
489   unsigned int j;
490
491   i = 0;
492   while (serverAddr[i] != NULL)
493     i++;
494   if (i > 0)
495   {
496     lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
497     i = 0;
498     j = 0;
499     while (serverAddr[i] != NULL)
500     {
501       lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
502       if (lsocks[j] != NULL)
503         j++;
504       i++;
505     }
506     if (j == 0)
507     {
508       if (errno != 0)
509         GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
510       GNUNET_free (lsocks);
511       lsocks = NULL;
512     }
513   }
514   else
515   {
516     lsocks = NULL;
517   }
518   return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
519                                             idle_timeout, require_found);
520 }
521
522
523 /**
524  * Free resources held by this server.
525  *
526  * @param s server to destroy
527  */
528 void
529 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *s)
530 {
531   struct HandlerList *hpos;
532   struct NotifyList *npos;
533   unsigned int i;
534
535 #if DEBUG_SERVER
536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
537 #endif
538   if (GNUNET_SCHEDULER_NO_TASK != s->listen_task)
539   {
540     GNUNET_SCHEDULER_cancel (s->listen_task);
541     s->listen_task = GNUNET_SCHEDULER_NO_TASK;
542   }
543   if (s->listen_sockets != NULL)
544   {
545     i = 0;
546     while (s->listen_sockets[i] != NULL)
547       GNUNET_break (GNUNET_OK ==
548                     GNUNET_NETWORK_socket_close (s->listen_sockets[i++]));
549     GNUNET_free (s->listen_sockets);
550     s->listen_sockets = NULL;
551   }
552   while (s->clients != NULL)
553     GNUNET_SERVER_client_disconnect (s->clients);
554   while (NULL != (hpos = s->handlers))
555   {
556     s->handlers = hpos->next;
557     GNUNET_free (hpos);
558   }
559   while (NULL != (npos = s->disconnect_notify_list))
560   {
561     npos->callback (npos->callback_cls, NULL);
562     s->disconnect_notify_list = npos->next;
563     GNUNET_free (npos);
564   }
565   GNUNET_free (s);
566 }
567
568
569 /**
570  * Add additional handlers to an existing server.
571  *
572  * @param server the server to add handlers to
573  * @param handlers array of message handlers for
574  *        incoming messages; the last entry must
575  *        have "NULL" for the "callback"; multiple
576  *        entries for the same type are allowed,
577  *        they will be called in order of occurence.
578  *        These handlers can be removed later;
579  *        the handlers array must exist until removed
580  *        (or server is destroyed).
581  */
582 void
583 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
584                             const struct GNUNET_SERVER_MessageHandler *handlers)
585 {
586   struct HandlerList *p;
587
588   p = GNUNET_malloc (sizeof (struct HandlerList));
589   p->handlers = handlers;
590   p->next = server->handlers;
591   server->handlers = p;
592 }
593
594
595 /**
596  * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
597  *
598  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
599  * @param tc scheduler context (unused)
600  */
601 static void
602 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
603 {
604   struct GNUNET_SERVER_Client *client = cls;
605
606   client->warn_task =
607       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
608                                     &warn_no_receive_done, client);
609   if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
610     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
611                 _
612                 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
613                 (unsigned int) client->warn_type,
614                 (unsigned long long) GNUNET_TIME_absolute_get_duration (client->
615                                                                         warn_start).
616                 rel_value);
617 }
618
619
620 /**
621  * Disable the warning the server issues if a message is not acknowledged
622  * in a timely fashion.  Use this call if a client is intentionally delayed
623  * for a while.  Only applies to the current message.
624  *
625  * @param client client for which to disable the warning
626  */
627 void
628 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
629 {
630   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
631   {
632     GNUNET_SCHEDULER_cancel (client->warn_task);
633     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
634   }
635 }
636
637
638 /**
639  * Inject a message into the server, pretend it came
640  * from the specified client.  Delivery of the message
641  * will happen instantly (if a handler is installed;
642  * otherwise the call does nothing).
643  *
644  * @param server the server receiving the message
645  * @param sender the "pretended" sender of the message
646  *        can be NULL!
647  * @param message message to transmit
648  * @return GNUNET_OK if the message was OK and the
649  *                   connection can stay open
650  *         GNUNET_SYSERR if the connection to the
651  *         client should be shut down
652  */
653 int
654 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
655                       struct GNUNET_SERVER_Client *sender,
656                       const struct GNUNET_MessageHeader *message)
657 {
658   struct HandlerList *pos;
659   const struct GNUNET_SERVER_MessageHandler *mh;
660   unsigned int i;
661   uint16_t type;
662   uint16_t size;
663   int found;
664
665   type = ntohs (message->type);
666   size = ntohs (message->size);
667 #if DEBUG_SERVER
668
669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
670               "Server schedules transmission of %u-byte message of type %u to client.\n",
671               size, type);
672 #endif
673   pos = server->handlers;
674   found = GNUNET_NO;
675   while (pos != NULL)
676   {
677     i = 0;
678     while (pos->handlers[i].callback != NULL)
679     {
680       mh = &pos->handlers[i];
681       if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
682       {
683         if ((mh->expected_size != 0) && (mh->expected_size != size))
684         {
685 #if GNUNET8_NETWORK_IS_DEAD
686           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
687                       "Expected %u bytes for message of type %u, got %u\n",
688                       mh->expected_size, mh->type, size);
689           GNUNET_break_op (0);
690 #endif
691           return GNUNET_SYSERR;
692         }
693         if (sender != NULL)
694         {
695           if (0 == sender->suspended)
696           {
697             sender->warn_start = GNUNET_TIME_absolute_get ();
698             sender->warn_task =
699                 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
700                                               &warn_no_receive_done, sender);
701             sender->warn_type = type;
702           }
703           sender->suspended++;
704         }
705         mh->callback (mh->callback_cls, sender, message);
706         found = GNUNET_YES;
707       }
708       i++;
709     }
710     pos = pos->next;
711   }
712   if (found == GNUNET_NO)
713   {
714     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
715                 "Received message of unknown type %d\n", type);
716     if (server->require_found == GNUNET_YES)
717       return GNUNET_SYSERR;
718   }
719   return GNUNET_OK;
720 }
721
722
723 /**
724  * We are receiving an incoming message.  Process it.
725  *
726  * @param cls our closure (handle for the client)
727  * @param buf buffer with data received from network
728  * @param available number of bytes available in buf
729  * @param addr address of the sender
730  * @param addrlen length of addr
731  * @param errCode code indicating errors receiving, 0 for success
732  */
733 static void process_incoming (void *cls, const void *buf, size_t available,
734                               const struct sockaddr *addr, socklen_t addrlen,
735                               int errCode);
736
737
738 /**
739  * Process messages from the client's message tokenizer until either
740  * the tokenizer is empty (and then schedule receiving more), or 
741  * until some handler is not immediately done (then wait for restart_processing)
742  * or shutdown.
743  *
744  * @param client the client to process, RC must have already been increased
745  *        using GNUNET_SERVER_client_keep and will be decreased by one in this
746  *        function
747  * @param ret GNUNET_NO to start processing from the buffer,
748  *            GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
749  *            GNUNET_SYSERR if we should instantly abort due to error in a previous step
750  */
751 static void
752 process_mst (struct GNUNET_SERVER_Client *client, int ret)
753 {
754   while ((ret != GNUNET_SYSERR) && (client->server != NULL) &&
755          (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
756   {
757     if (ret == GNUNET_OK)
758     {
759       client->receive_pending = GNUNET_YES;
760 #if DEBUG_SERVER
761       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
762                   "Server re-enters receive loop, timeout: %llu.\n",
763                   client->idle_timeout.rel_value);
764 #endif
765       GNUNET_CONNECTION_receive (client->connection,
766                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
767                                  client->idle_timeout, &process_incoming,
768                                  client);
769       break;
770     }
771 #if DEBUG_SERVER
772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
773                 "Server processes additional messages instantly.\n");
774 #endif
775     ret =
776         GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
777                                    GNUNET_YES);
778   }
779 #if DEBUG_SERVER
780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
781               "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
782               ret, client->server, client->shutdown_now, client->suspended);
783 #endif
784
785   if (ret == GNUNET_NO)
786   {
787 #if DEBUG_SERVER
788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
789                 "Server has more data pending but is suspended.\n");
790 #endif
791     client->receive_pending = GNUNET_SYSERR;    /* data pending */
792   }
793   if ((ret == GNUNET_SYSERR) || (GNUNET_YES == client->shutdown_now))
794     GNUNET_SERVER_client_disconnect (client);
795   GNUNET_SERVER_client_drop (client);
796 }
797
798
799 /**
800  * We are receiving an incoming message.  Process it.
801  *
802  * @param cls our closure (handle for the client)
803  * @param buf buffer with data received from network
804  * @param available number of bytes available in buf
805  * @param addr address of the sender
806  * @param addrlen length of addr
807  * @param errCode code indicating errors receiving, 0 for success
808  */
809 static void
810 process_incoming (void *cls, const void *buf, size_t available,
811                   const struct sockaddr *addr, socklen_t addrlen, int errCode)
812 {
813   struct GNUNET_SERVER_Client *client = cls;
814   struct GNUNET_SERVER_Handle *server = client->server;
815   struct GNUNET_TIME_Absolute end;
816   struct GNUNET_TIME_Absolute now;
817   int ret;
818
819   GNUNET_assert (client->receive_pending == GNUNET_YES);
820   client->receive_pending = GNUNET_NO;
821   now = GNUNET_TIME_absolute_get ();
822   end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
823
824   if ((buf == NULL) && (available == 0) && (addr == NULL) && (errCode == 0) &&
825       (client->shutdown_now != GNUNET_YES) && (server != NULL) &&
826       (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
827       (end.abs_value > now.abs_value))
828   {
829     /* wait longer, timeout changed (i.e. due to us sending) */
830 #if DEBUG_SERVER
831     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832                 "Receive time out, but no disconnect due to sending (%p)\n",
833                 GNUNET_a2s (addr, addrlen));
834 #endif
835     client->receive_pending = GNUNET_YES;
836     GNUNET_CONNECTION_receive (client->connection,
837                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
838                                GNUNET_TIME_absolute_get_remaining (end),
839                                &process_incoming, client);
840     return;
841   }
842   if ((buf == NULL) || (available == 0) || (errCode != 0) || (server == NULL) ||
843       (client->shutdown_now == GNUNET_YES) ||
844       (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
845   {
846     /* other side closed connection, error connecting, etc. */
847     GNUNET_SERVER_client_disconnect (client);
848     return;
849   }
850 #if DEBUG_SERVER
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
852               (unsigned int) available, GNUNET_a2s (addr, addrlen));
853 #endif
854   GNUNET_SERVER_client_keep (client);
855   client->last_activity = now;
856   ret =
857       GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
858                                  GNUNET_YES);
859   process_mst (client, ret);
860 }
861
862
863 /**
864  * Task run to start again receiving from the network
865  * and process requests.
866  *
867  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
868  * @param tc scheduler context (unused)
869  */
870 static void
871 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
872 {
873   struct GNUNET_SERVER_Client *client = cls;
874   struct GNUNET_SERVER_Handle *server = client->server;
875
876   client->restart_task = GNUNET_SCHEDULER_NO_TASK;
877   if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) &&
878       (GNUNET_NO == server->clients_ignore_shutdown))
879   {
880     GNUNET_SERVER_client_disconnect (client);
881     return;
882   }
883   if (client->receive_pending == GNUNET_NO)
884   {
885 #if DEBUG_SERVER
886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887                 "Server begins to read again from client.\n");
888 #endif
889     client->receive_pending = GNUNET_YES;
890     GNUNET_CONNECTION_receive (client->connection,
891                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
892                                client->idle_timeout, &process_incoming, client);
893     return;
894   }
895 #if DEBUG_SERVER
896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897               "Server continues processing messages still in the buffer.\n");
898 #endif
899   GNUNET_SERVER_client_keep (client);
900   client->receive_pending = GNUNET_NO;
901   process_mst (client, GNUNET_NO);
902 }
903
904
905 /**
906  * This function is called whenever our inbound message tokenizer has
907  * received a complete message.
908  *
909  * @param cls closure (struct GNUNET_SERVER_Handle)
910  * @param client identification of the client (struct GNUNET_SERVER_Client*)
911  * @param message the actual message
912  */
913 static void
914 client_message_tokenizer_callback (void *cls, void *client,
915                                    const struct GNUNET_MessageHeader *message)
916 {
917   struct GNUNET_SERVER_Handle *server = cls;
918   struct GNUNET_SERVER_Client *sender = client;
919   int ret;
920
921 #if DEBUG_SERVER
922
923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924               "Tokenizer gives server message of type %u from client\n",
925               ntohs (message->type));
926 #endif
927   sender->in_process_client_buffer = GNUNET_YES;
928   ret = GNUNET_SERVER_inject (server, sender, message);
929   sender->in_process_client_buffer = GNUNET_NO;
930   if (GNUNET_OK != ret)
931     GNUNET_SERVER_client_disconnect (sender);
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 GNUNET_SERVER_Handle *server,
949                               struct GNUNET_CONNECTION_Handle *connection)
950 {
951   struct GNUNET_SERVER_Client *client;
952
953   client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
954   client->connection = connection;
955   client->mst =
956       GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
957   client->reference_count = 1;
958   client->server = server;
959   client->last_activity = GNUNET_TIME_absolute_get ();
960   client->next = server->clients;
961   client->idle_timeout = server->idle_timeout;
962   server->clients = client;
963   client->receive_pending = GNUNET_YES;
964   client->callback = NULL;
965   client->callback_cls = NULL;
966   GNUNET_CONNECTION_receive (client->connection,
967                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
968                              client->idle_timeout, &process_incoming, client);
969   return client;
970 }
971
972
973 /**
974  * Change the timeout for a particular client.  Decreasing the timeout
975  * may not go into effect immediately (only after the previous timeout
976  * times out or activity happens on the socket).
977  *
978  * @param client the client to update
979  * @param timeout new timeout for activities on the socket
980  */
981 void
982 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
983                                   struct GNUNET_TIME_Relative timeout)
984 {
985   client->idle_timeout = timeout;
986 }
987
988
989 /**
990  * Notify the server that the given client handle should
991  * be kept (keeps the connection up if possible, increments
992  * the internal reference counter).
993  *
994  * @param client the client to keep
995  */
996 void
997 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
998 {
999   client->reference_count++;
1000 }
1001
1002
1003 /**
1004  * Notify the server that the given client handle is no
1005  * longer required.  Decrements the reference counter.  If
1006  * that counter reaches zero an inactive connection maybe
1007  * closed.
1008  *
1009  * @param client the client to drop
1010  */
1011 void
1012 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1013 {
1014   GNUNET_assert (client->reference_count > 0);
1015   client->reference_count--;
1016   if ((client->shutdown_now == GNUNET_YES) && (client->reference_count == 0))
1017     GNUNET_SERVER_client_disconnect (client);
1018 }
1019
1020
1021 /**
1022  * Obtain the network address of the other party.
1023  *
1024  * @param client the client to get the address for
1025  * @param addr where to store the address
1026  * @param addrlen where to store the length of the address
1027  * @return GNUNET_OK on success
1028  */
1029 int
1030 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1031                                   void **addr, size_t * addrlen)
1032 {
1033   return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1034 }
1035
1036
1037 /**
1038  * Ask the server to notify us whenever a client disconnects.
1039  * This function is called whenever the actual network connection
1040  * is closed; the reference count may be zero or larger than zero
1041  * at this point.
1042  *
1043  * @param server the server manageing the clients
1044  * @param callback function to call on disconnect
1045  * @param callback_cls closure for callback
1046  */
1047 void
1048 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1049                                  GNUNET_SERVER_DisconnectCallback callback,
1050                                  void *callback_cls)
1051 {
1052   struct NotifyList *n;
1053
1054   n = GNUNET_malloc (sizeof (struct NotifyList));
1055   n->callback = callback;
1056   n->callback_cls = callback_cls;
1057   n->next = server->disconnect_notify_list;
1058   server->disconnect_notify_list = n;
1059 }
1060
1061
1062 /**
1063  * Ask the server to stop notifying us whenever a client disconnects.
1064  *
1065  * @param server the server manageing the clients
1066  * @param callback function to call on disconnect
1067  * @param callback_cls closure for callback
1068  */
1069 void
1070 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1071                                         GNUNET_SERVER_DisconnectCallback
1072                                         callback, void *callback_cls)
1073 {
1074   struct NotifyList *pos;
1075   struct NotifyList *prev;
1076
1077   prev = NULL;
1078   pos = server->disconnect_notify_list;
1079   while (pos != NULL)
1080   {
1081     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1082       break;
1083     prev = pos;
1084     pos = pos->next;
1085   }
1086   if (pos == NULL)
1087   {
1088     GNUNET_break (0);
1089     return;
1090   }
1091   if (prev == NULL)
1092     server->disconnect_notify_list = pos->next;
1093   else
1094     prev->next = pos->next;
1095   GNUNET_free (pos);
1096 }
1097
1098
1099 /**
1100  * Ask the server to disconnect from the given client.
1101  * This is the same as returning GNUNET_SYSERR from a message
1102  * handler, except that it allows dropping of a client even
1103  * when not handling a message from that client.
1104  *
1105  * @param client the client to disconnect from
1106  */
1107 void
1108 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1109 {
1110   struct GNUNET_SERVER_Client *prev;
1111   struct GNUNET_SERVER_Client *pos;
1112   struct GNUNET_SERVER_Handle *server;
1113   struct NotifyList *n;
1114   unsigned int rc;
1115
1116 #if DEBUG_SERVER
1117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1118               "Client is being disconnected from the server.\n");
1119 #endif
1120   if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1121   {
1122     GNUNET_SCHEDULER_cancel (client->restart_task);
1123     client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1124   }
1125   if (client->warn_task != GNUNET_SCHEDULER_NO_TASK)
1126   {
1127     GNUNET_SCHEDULER_cancel (client->warn_task);
1128     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1129   }
1130   if (GNUNET_YES == client->receive_pending)
1131   {
1132     GNUNET_CONNECTION_receive_cancel (client->connection);
1133     client->receive_pending = GNUNET_NO;
1134   }
1135
1136   rc = client->reference_count;
1137   if (client->server != NULL)
1138   {
1139     server = client->server;
1140     client->server = NULL;
1141     client->shutdown_now = GNUNET_YES;
1142     prev = NULL;
1143     pos = server->clients;
1144     while ((pos != NULL) && (pos != client))
1145     {
1146       prev = pos;
1147       pos = pos->next;
1148     }
1149     GNUNET_assert (pos != NULL);
1150     if (prev == NULL)
1151       server->clients = pos->next;
1152     else
1153       prev->next = pos->next;
1154     if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1155     {
1156       GNUNET_SCHEDULER_cancel (client->restart_task);
1157       client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1158     }
1159     if (client->warn_task != GNUNET_SCHEDULER_NO_TASK)
1160     {
1161       GNUNET_SCHEDULER_cancel (client->warn_task);
1162       client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1163     }
1164     n = server->disconnect_notify_list;
1165     while (n != NULL)
1166     {
1167       n->callback (n->callback_cls, client);
1168       n = n->next;
1169     }
1170   }
1171   if (rc > 0)
1172   {
1173 #if DEBUG_SERVER
1174     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175                 "RC still positive, not destroying everything.\n");
1176 #endif
1177     return;
1178   }
1179   if (client->in_process_client_buffer == GNUNET_YES)
1180   {
1181 #if DEBUG_SERVER
1182     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183                 "Still processing inputs, not destroying everything.\n");
1184 #endif
1185     return;
1186   }
1187
1188   if (client->persist == GNUNET_YES)
1189     GNUNET_CONNECTION_persist_ (client->connection);
1190   GNUNET_CONNECTION_destroy (client->connection, GNUNET_NO);
1191   GNUNET_SERVER_mst_destroy (client->mst);
1192   GNUNET_free (client);
1193 }
1194
1195
1196 /**
1197  * Disable the "CORK" feature for communication with the given client,
1198  * forcing the OS to immediately flush the buffer on transmission
1199  * instead of potentially buffering multiple messages.
1200  *
1201  * @param client handle to the client
1202  * @return GNUNET_OK on success
1203  */
1204 int
1205 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1206 {
1207   return GNUNET_CONNECTION_disable_corking (client->connection);
1208 }
1209
1210
1211 /**
1212  * Wrapper for transmission notification that calls the original
1213  * callback and update the last activity time for our connection.
1214  * 
1215  * @param cls the 'struct GNUNET_SERVER_Client'
1216  * @param size number of bytes we can transmit
1217  * @param buf where to copy the message 
1218  * @return number of bytes actually transmitted
1219  */
1220 static size_t
1221 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1222 {
1223   struct GNUNET_SERVER_Client *client = cls;
1224   size_t ret;
1225
1226   ret = client->callback (client->callback_cls, size, buf);
1227   if (ret > 0)
1228     client->last_activity = GNUNET_TIME_absolute_get ();
1229   return ret;
1230 }
1231
1232
1233 /**
1234  * Notify us when the server has enough space to transmit
1235  * a message of the given size to the given client.
1236  *
1237  * @param client client to transmit message to
1238  * @param size requested amount of buffer space
1239  * @param timeout after how long should we give up (and call
1240  *        notify with buf NULL and size 0)?
1241  * @param callback function to call when space is available
1242  * @param callback_cls closure for callback
1243  * @return non-NULL if the notify callback was queued; can be used
1244  *           to cancel the request using
1245  *           GNUNET_CONNECTION_notify_transmit_ready_cancel.
1246  *         NULL if we are already going to notify someone else (busy)
1247  */
1248 struct GNUNET_CONNECTION_TransmitHandle *
1249 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1250                                      size_t size,
1251                                      struct GNUNET_TIME_Relative timeout,
1252                                      GNUNET_CONNECTION_TransmitReadyNotify
1253                                      callback, void *callback_cls)
1254 {
1255   client->callback_cls = callback_cls;
1256   client->callback = callback;
1257   return GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1258                                                   timeout,
1259                                                   &transmit_ready_callback_wrapper,
1260                                                   client);
1261 }
1262
1263
1264 /**
1265  * Set the persistent flag on this client, used to setup client connection
1266  * to only be killed when the service it's connected to is actually dead.
1267  *
1268  * @param client the client to set the persistent flag on
1269  */
1270 void
1271 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1272 {
1273   client->persist = GNUNET_YES;
1274 }
1275
1276
1277 /**
1278  * Resume receiving from this client, we are done processing the
1279  * current request.  This function must be called from within each
1280  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1281  *
1282  * @param client client we were processing a message of
1283  * @param success GNUNET_OK to keep the connection open and
1284  *                          continue to receive
1285  *                GNUNET_NO to close the connection (normal behavior)
1286  *                GNUNET_SYSERR to close the connection (signal
1287  *                          serious error)
1288  */
1289 void
1290 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1291 {
1292   if (client == NULL)
1293     return;
1294   GNUNET_assert (client->suspended > 0);
1295   client->suspended--;
1296   if (success != GNUNET_OK)
1297   {
1298 #if DEBUG_SERVER
1299     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300                 "GNUNET_SERVER_receive_done called with failure indication\n");
1301 #endif
1302     GNUNET_SERVER_client_disconnect (client);
1303     return;
1304   }
1305   if (client->suspended > 0)
1306   {
1307 #if DEBUG_SERVER
1308     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1309                 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1310 #endif
1311     return;
1312   }
1313   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1314   {
1315     GNUNET_SCHEDULER_cancel (client->warn_task);
1316     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1317   }
1318   if (client->in_process_client_buffer == GNUNET_YES)
1319   {
1320 #if DEBUG_SERVER
1321     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1322                 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1323 #endif
1324     return;
1325   }
1326   if (client->server == NULL)
1327   {
1328     GNUNET_SERVER_client_disconnect (client);
1329     return;
1330   }
1331 #if DEBUG_SERVER
1332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333               "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1334 #endif
1335   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1336   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1337 }
1338
1339
1340 /**
1341  * Configure this server's connections to continue handling client
1342  * requests as usual even after we get a shutdown signal.  The change
1343  * only applies to clients that connect to the server from the outside
1344  * using TCP after this call.  Clients managed previously or those
1345  * added using GNUNET_SERVER_connect_socket and
1346  * GNUNET_SERVER_connect_callback are not affected by this option.
1347  *
1348  * @param h server handle
1349  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1350  */
1351 void
1352 GNUNET_SERVER_ignore_shutdown (struct GNUNET_SERVER_Handle *h, int do_ignore)
1353 {
1354   h->clients_ignore_shutdown = do_ignore;
1355 }
1356
1357 /* end of server.c */