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