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