-fix (C) notices
[oweals/gnunet.git] / src / util / server.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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_util_lib.h"
29 #include "gnunet_protocols.h"
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
32
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
34
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
36
37
38 /**
39  * List of arrays of message handlers.
40  */
41 struct HandlerList
42 {
43   /**
44    * This is a linked list.
45    */
46   struct HandlerList *next;
47
48   /**
49    * NULL-terminated array of handlers.
50    */
51   const struct GNUNET_SERVER_MessageHandler *handlers;
52 };
53
54
55 /**
56  * List of arrays of message handlers.
57  */
58 struct NotifyList
59 {
60   /**
61    * This is a doubly linked list.
62    */
63   struct NotifyList *next;
64
65   /**
66    * This is a doubly linked list.
67    */
68   struct NotifyList *prev;
69
70   /**
71    * Function to call.
72    */
73   GNUNET_SERVER_DisconnectCallback callback;
74
75   /**
76    * Closure for callback.
77    */
78   void *callback_cls;
79 };
80
81
82 /**
83  * @brief handle for a server
84  */
85 struct GNUNET_SERVER_Handle
86 {
87   /**
88    * List of handlers for incoming messages.
89    */
90   struct HandlerList *handlers;
91
92   /**
93    * Head of list of our current clients.
94    */
95   struct GNUNET_SERVER_Client *clients_head;
96
97   /**
98    * Head of list of our current clients.
99    */
100   struct GNUNET_SERVER_Client *clients_tail;
101
102   /**
103    * Head of linked list of functions to call on disconnects by clients.
104    */
105   struct NotifyList *disconnect_notify_list_head;
106
107   /**
108    * Tail of linked list of functions to call on disconnects by clients.
109    */
110   struct NotifyList *disconnect_notify_list_tail;
111
112   /**
113    * Head of linked list of functions to call on connects by clients.
114    */
115   struct NotifyList *connect_notify_list_head;
116
117   /**
118    * Tail of linked list of functions to call on connects by clients.
119    */
120   struct NotifyList *connect_notify_list_tail;
121
122   /**
123    * Function to call for access control.
124    */
125   GNUNET_CONNECTION_AccessCheck access_cb;
126
127   /**
128    * Closure for @e access_cb.
129    */
130   void *access_cb_cls;
131
132   /**
133    * NULL-terminated array of sockets used to listen for new
134    * connections.
135    */
136   struct GNUNET_NETWORK_Handle **listen_sockets;
137
138   /**
139    * After how long should an idle connection time
140    * out (on write).
141    */
142   struct GNUNET_TIME_Relative idle_timeout;
143
144   /**
145    * Task scheduled to do the listening.
146    */
147   struct GNUNET_SCHEDULER_Task * listen_task;
148
149   /**
150    * Alternative function to create a MST instance.
151    */
152   GNUNET_SERVER_MstCreateCallback mst_create;
153
154   /**
155    * Alternative function to destroy a MST instance.
156    */
157   GNUNET_SERVER_MstDestroyCallback mst_destroy;
158
159   /**
160    * Alternative function to give data to a MST instance.
161    */
162   GNUNET_SERVER_MstReceiveCallback mst_receive;
163
164   /**
165    * Closure for 'mst_'-callbacks.
166    */
167   void *mst_cls;
168
169   /**
170    * Do we ignore messages of types that we do not understand or do we
171    * require that a handler is found (and if not kill the connection)?
172    */
173   int require_found;
174
175   /**
176    * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177    * all non-monitor clients to disconnect before we call
178    * #GNUNET_SERVER_destroy.  See test_monitor_clients().  Set to
179    * #GNUNET_SYSERR once the final destroy task has been scheduled
180    * (we cannot run it in the same task).
181    */
182   int in_soft_shutdown;
183 };
184
185
186 /**
187  * Handle server returns for aborting transmission to a client.
188  */
189 struct GNUNET_SERVER_TransmitHandle
190 {
191   /**
192    * Function to call to get the message.
193    */
194   GNUNET_CONNECTION_TransmitReadyNotify callback;
195
196   /**
197    * Closure for @e callback
198    */
199   void *callback_cls;
200
201   /**
202    * Active connection transmission handle.
203    */
204   struct GNUNET_CONNECTION_TransmitHandle *cth;
205
206 };
207
208
209 /**
210  * @brief handle for a client of the server
211  */
212 struct GNUNET_SERVER_Client
213 {
214
215   /**
216    * This is a doubly linked list.
217    */
218   struct GNUNET_SERVER_Client *next;
219
220   /**
221    * This is a doubly linked list.
222    */
223   struct GNUNET_SERVER_Client *prev;
224
225   /**
226    * Processing of incoming data.
227    */
228   void *mst;
229
230   /**
231    * Server that this client belongs to.
232    */
233   struct GNUNET_SERVER_Handle *server;
234
235   /**
236    * Client closure for callbacks.
237    */
238   struct GNUNET_CONNECTION_Handle *connection;
239
240   /**
241    * User context value, manipulated using
242    * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
243    */
244   void *user_context;
245
246   /**
247    * ID of task used to restart processing.
248    */
249   struct GNUNET_SCHEDULER_Task * restart_task;
250
251   /**
252    * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
253    */
254   struct GNUNET_SCHEDULER_Task * warn_task;
255
256   /**
257    * Time when the warn task was started.
258    */
259   struct GNUNET_TIME_Absolute warn_start;
260
261   /**
262    * Last activity on this socket (used to time it out
263    * if reference_count == 0).
264    */
265   struct GNUNET_TIME_Absolute last_activity;
266
267   /**
268    * Transmission handle we return for this client from
269    * #GNUNET_SERVER_notify_transmit_ready.
270    */
271   struct GNUNET_SERVER_TransmitHandle th;
272
273   /**
274    * After how long should an idle connection time
275    * out (on write).
276    */
277   struct GNUNET_TIME_Relative idle_timeout;
278
279   /**
280    * Number of external entities with a reference to
281    * this client object.
282    */
283   unsigned int reference_count;
284
285   /**
286    * Was processing if incoming messages suspended while
287    * we were still processing data already received?
288    * This is a counter saying how often processing was
289    * suspended (once per handler invoked).
290    */
291   unsigned int suspended;
292
293   /**
294    * Last size given when user context was initialized; used for
295    * sanity check.
296    */
297   size_t user_context_size;
298
299   /**
300    * Are we currently in the "process_client_buffer" function (and
301    * will hence restart the receive job on exit if suspended == 0 once
302    * we are done?).  If this is set, then "receive_done" will
303    * essentially only decrement suspended; if this is not set, then
304    * "receive_done" may need to restart the receive process (either
305    * from the side-buffer or via select/recv).
306    */
307   int in_process_client_buffer;
308
309   /**
310    * We're about to close down this client.
311    */
312   int shutdown_now;
313
314   /**
315    * Are we currently trying to receive? (#GNUNET_YES if we are,
316    * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
317    * available in MST).
318    */
319   int receive_pending;
320
321   /**
322    * Persist the file handle for this client no matter what happens,
323    * force the OS to close once the process actually dies.  Should only
324    * be used in special cases!
325    */
326   int persist;
327
328   /**
329    * Is this client a 'monitor' client that should not be counted
330    * when deciding on destroying the server during soft shutdown?
331    * (see also #GNUNET_SERVICE_start)
332    */
333   int is_monitor;
334
335   /**
336    * Type of last message processed (for warn_no_receive_done).
337    */
338   uint16_t warn_type;
339 };
340
341
342
343 /**
344  * Return user context associated with the given client.
345  * Note: you should probably use the macro (call without the underscore).
346  *
347  * @param client client to query
348  * @param size number of bytes in user context struct (for verification only)
349  * @return pointer to user context
350  */
351 void *
352 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
353                                         size_t size)
354 {
355   if ((0 == client->user_context_size) &&
356       (NULL == client->user_context))
357     return NULL; /* never set */
358   GNUNET_assert (size == client->user_context_size);
359   return client->user_context;
360 }
361
362
363 /**
364  * Set user context to be associated with the given client.
365  * Note: you should probably use the macro (call without the underscore).
366  *
367  * @param client client to query
368  * @param ptr pointer to user context
369  * @param size number of bytes in user context struct (for verification only)
370  */
371 void
372 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
373                                         void *ptr,
374                                         size_t size)
375 {
376   if (NULL == ptr)
377   {
378     client->user_context_size = 0;
379     client->user_context = ptr;
380     return;
381   }
382   client->user_context_size = size;
383   client->user_context = ptr;
384 }
385
386
387 /**
388  * Scheduler says our listen socket is ready.  Process it!
389  *
390  * @param cls handle to our server for which we are processing the listen
391  *        socket
392  * @param tc reason why we are running right now
393  */
394 static void
395 process_listen_socket (void *cls,
396                        const struct GNUNET_SCHEDULER_TaskContext *tc)
397 {
398   struct GNUNET_SERVER_Handle *server = cls;
399   struct GNUNET_CONNECTION_Handle *sock;
400   unsigned int i;
401
402   server->listen_task = NULL;
403   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
404   {
405     /* ignore shutdown, someone else will take care of it! */
406     GNUNET_SERVER_resume (server);
407     return;
408   }
409   for (i = 0; NULL != server->listen_sockets[i]; i++)
410   {
411     if (GNUNET_NETWORK_fdset_isset (tc->read_ready,
412                                     server->listen_sockets[i]))
413     {
414       sock =
415           GNUNET_CONNECTION_create_from_accept (server->access_cb,
416                                                 server->access_cb_cls,
417                                                 server->listen_sockets[i]);
418       if (NULL != sock)
419       {
420         LOG (GNUNET_ERROR_TYPE_DEBUG,
421              "Server accepted incoming connection.\n");
422         (void) GNUNET_SERVER_connect_socket (server,
423                                              sock);
424       }
425     }
426   }
427   /* listen for more! */
428   GNUNET_SERVER_resume (server);
429 }
430
431
432 /**
433  * Create and initialize a listen socket for the server.
434  *
435  * @param server_addr address to listen on
436  * @param socklen length of @a server_addr
437  * @return NULL on error, otherwise the listen socket
438  */
439 static struct GNUNET_NETWORK_Handle *
440 open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
441 {
442   struct GNUNET_NETWORK_Handle *sock;
443   uint16_t port;
444   int eno;
445
446   switch (server_addr->sa_family)
447   {
448   case AF_INET:
449     port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
450     break;
451   case AF_INET6:
452     port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
453     break;
454   case AF_UNIX:
455     port = 0;
456     break;
457   default:
458     GNUNET_break (0);
459     port = 0;
460     break;
461   }
462   sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
463   if (NULL == sock)
464   {
465     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
466     errno = 0;
467     return NULL;
468   }
469   /* bind the socket */
470   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
471   {
472     eno = errno;
473     if (EADDRINUSE != errno)
474     {
475       /* we don't log 'EADDRINUSE' here since an IPv4 bind may
476        * fail if we already took the port on IPv6; if both IPv4 and
477        * IPv6 binds fail, then our caller will log using the
478        * errno preserved in 'eno' */
479       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
480                     "bind");
481       if (0 != port)
482         LOG (GNUNET_ERROR_TYPE_ERROR,
483              _("`%s' failed for port %d (%s).\n"),
484              "bind",
485              port,
486              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
487       eno = 0;
488     }
489     else
490     {
491       if (0 != port)
492         LOG (GNUNET_ERROR_TYPE_WARNING,
493              _("`%s' failed for port %d (%s): address already in use\n"),
494              "bind", port,
495              (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
496       else if (AF_UNIX == server_addr->sa_family)
497       {
498         LOG (GNUNET_ERROR_TYPE_WARNING,
499              _("`%s' failed for `%s': address already in use\n"),
500              "bind",
501              GNUNET_a2s (server_addr, socklen));
502       }
503     }
504     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
505     errno = eno;
506     return NULL;
507   }
508   if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
509   {
510     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
511                   "listen");
512     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
513     errno = 0;
514     return NULL;
515   }
516   if (0 != port)
517     LOG (GNUNET_ERROR_TYPE_DEBUG,
518          "Server starts to listen on port %u.\n",
519          port);
520   return sock;
521 }
522
523
524 /**
525  * Create a new server.
526  *
527  * @param access_cb function for access control
528  * @param access_cb_cls closure for @a access_cb
529  * @param lsocks NULL-terminated array of listen sockets
530  * @param idle_timeout after how long should we timeout idle connections?
531  * @param require_found if #GNUNET_YES, connections sending messages of unknown type
532  *        will be closed
533  * @return handle for the new server, NULL on error
534  *         (typically, "port" already in use)
535  */
536 struct GNUNET_SERVER_Handle *
537 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access_cb,
538                                    void *access_cb_cls,
539                                    struct GNUNET_NETWORK_Handle **lsocks,
540                                    struct GNUNET_TIME_Relative idle_timeout,
541                                    int require_found)
542 {
543   struct GNUNET_SERVER_Handle *server;
544
545   server = GNUNET_new (struct GNUNET_SERVER_Handle);
546   server->idle_timeout = idle_timeout;
547   server->listen_sockets = lsocks;
548   server->access_cb = access_cb;
549   server->access_cb_cls = access_cb_cls;
550   server->require_found = require_found;
551   if (NULL != lsocks)
552     GNUNET_SERVER_resume (server);
553   return server;
554 }
555
556
557 /**
558  * Create a new server.
559  *
560  * @param access_cb function for access control
561  * @param access_cb_cls closure for @a access_cb
562  * @param server_addr address to listen on (including port), NULL terminated array
563  * @param socklen length of server_addr
564  * @param idle_timeout after how long should we timeout idle connections?
565  * @param require_found if YES, connections sending messages of unknown type
566  *        will be closed
567  * @return handle for the new server, NULL on error
568  *         (typically, "port" already in use)
569  */
570 struct GNUNET_SERVER_Handle *
571 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access_cb,
572                       void *access_cb_cls,
573                       struct sockaddr *const *server_addr,
574                       const socklen_t * socklen,
575                       struct GNUNET_TIME_Relative idle_timeout,
576                       int require_found)
577 {
578   struct GNUNET_NETWORK_Handle **lsocks;
579   unsigned int i;
580   unsigned int j;
581   unsigned int k;
582   int seen;
583
584   i = 0;
585   while (NULL != server_addr[i])
586     i++;
587   if (i > 0)
588   {
589     lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
590     i = 0;
591     j = 0;
592     while (NULL != server_addr[i])
593     {
594       seen = 0;
595       for (k=0;k<i;k++)
596         if ( (socklen[k] == socklen[i]) &&
597              (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
598         {
599           seen = 1;
600           break;
601         }
602       if (0 != seen)
603       {
604         /* duplicate address, skip */
605         i++;
606         continue;
607       }
608       lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
609       if (NULL != lsocks[j])
610         j++;
611       i++;
612     }
613     if (0 == j)
614     {
615       if (0 != errno)
616         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
617       GNUNET_free (lsocks);
618       lsocks = NULL;
619     }
620   }
621   else
622   {
623     lsocks = NULL;
624   }
625   return GNUNET_SERVER_create_with_sockets (access_cb,
626                                             access_cb_cls,
627                                             lsocks,
628                                             idle_timeout,
629                                             require_found);
630 }
631
632
633 /**
634  * Set the 'monitor' flag on this client.  Clients which have been
635  * marked as 'monitors' won't prevent the server from shutting down
636  * once '#GNUNET_SERVER_stop_listening()' has been invoked.  The idea is
637  * that for "normal" clients we likely want to allow them to process
638  * their requests; however, monitor-clients are likely to 'never'
639  * disconnect during shutdown and thus will not be considered when
640  * determining if the server should continue to exist after
641  * #GNUNET_SERVER_destroy() has been called.
642  *
643  * @param client the client to set the 'monitor' flag on
644  */
645 void
646 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
647 {
648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649               "Marking client as monitor!\n");
650   client->is_monitor = GNUNET_YES;
651 }
652
653
654 /**
655  * Helper function for #test_monitor_clients() to trigger
656  * #GNUNET_SERVER_destroy() after the stack has unwound.
657  *
658  * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
659  * @param tc unused
660  */
661 static void
662 do_destroy (void *cls,
663             const struct GNUNET_SCHEDULER_TaskContext *tc)
664 {
665   struct GNUNET_SERVER_Handle *server = cls;
666
667   GNUNET_SERVER_destroy (server);
668 }
669
670
671 /**
672  * Check if only 'monitor' clients are left.  If so, destroy the
673  * server completely.
674  *
675  * @param server server to test for full shutdown
676  */
677 static void
678 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
679 {
680   struct GNUNET_SERVER_Client *client;
681
682   if (GNUNET_YES != server->in_soft_shutdown)
683     return;
684   for (client = server->clients_head; NULL != client; client = client->next)
685     if (GNUNET_NO == client->is_monitor)
686       return; /* not done yet */
687   server->in_soft_shutdown = GNUNET_SYSERR;
688   GNUNET_SCHEDULER_add_now (&do_destroy, server);
689 }
690
691
692 /**
693  * Suspend accepting connections from the listen socket temporarily.
694  *
695  * @param server server to stop accepting connections.
696  */
697 void
698 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
699 {
700   if (NULL != server->listen_task)
701   {
702     GNUNET_SCHEDULER_cancel (server->listen_task);
703     server->listen_task = NULL;
704   }
705 }
706
707
708 /**
709  * Resume accepting connections from the listen socket.
710  *
711  * @param server server to stop accepting connections.
712  */
713 void
714 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
715 {
716   struct GNUNET_NETWORK_FDSet *r;
717   unsigned int i;
718
719   if (NULL == server->listen_sockets)
720     return;
721   if (NULL == server->listen_sockets[0])
722     return; /* nothing to do, no listen sockets! */
723   if (NULL == server->listen_sockets[1])
724   {
725     /* simplified method: no fd set needed; this is then much simpler and
726        much more efficient */
727     server->listen_task =
728       GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
729                                                    GNUNET_SCHEDULER_PRIORITY_HIGH,
730                                                    server->listen_sockets[0],
731                                                    &process_listen_socket, server);
732     return;
733   }
734   r = GNUNET_NETWORK_fdset_create ();
735   i = 0;
736   while (NULL != server->listen_sockets[i])
737     GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
738   server->listen_task =
739     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
740                                  GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
741                                  &process_listen_socket, server);
742   GNUNET_NETWORK_fdset_destroy (r);
743 }
744
745
746 /**
747  * Stop the listen socket and get ready to shutdown the server
748  * once only 'monitor' clients are left.
749  *
750  * @param server server to stop listening on
751  */
752 void
753 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
754 {
755   unsigned int i;
756
757   LOG (GNUNET_ERROR_TYPE_DEBUG,
758        "Server in soft shutdown\n");
759   if (NULL != server->listen_task)
760   {
761     GNUNET_SCHEDULER_cancel (server->listen_task);
762     server->listen_task = NULL;
763   }
764   if (NULL != server->listen_sockets)
765   {
766     i = 0;
767     while (NULL != server->listen_sockets[i])
768       GNUNET_break (GNUNET_OK ==
769                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
770     GNUNET_free (server->listen_sockets);
771     server->listen_sockets = NULL;
772   }
773   if (GNUNET_NO == server->in_soft_shutdown)
774     server->in_soft_shutdown = GNUNET_YES;
775   test_monitor_clients (server);
776 }
777
778
779 /**
780  * Free resources held by this server.
781  *
782  * @param server server to destroy
783  */
784 void
785 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
786 {
787   struct HandlerList *hpos;
788   struct NotifyList *npos;
789   unsigned int i;
790
791   LOG (GNUNET_ERROR_TYPE_DEBUG,
792        "Server shutting down.\n");
793   if (NULL != server->listen_task)
794   {
795     GNUNET_SCHEDULER_cancel (server->listen_task);
796     server->listen_task = NULL;
797   }
798   if (NULL != server->listen_sockets)
799   {
800     i = 0;
801     while (NULL != server->listen_sockets[i])
802       GNUNET_break (GNUNET_OK ==
803                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
804     GNUNET_free (server->listen_sockets);
805     server->listen_sockets = NULL;
806   }
807   while (NULL != server->clients_head)
808     GNUNET_SERVER_client_disconnect (server->clients_head);
809   while (NULL != (hpos = server->handlers))
810   {
811     server->handlers = hpos->next;
812     GNUNET_free (hpos);
813   }
814   while (NULL != (npos = server->disconnect_notify_list_head))
815   {
816     npos->callback (npos->callback_cls,
817                     NULL);
818     GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
819                                  server->disconnect_notify_list_tail,
820                                  npos);
821     GNUNET_free (npos);
822   }
823   while (NULL != (npos = server->connect_notify_list_head))
824   {
825     npos->callback (npos->callback_cls,
826                     NULL);
827     GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
828                                  server->connect_notify_list_tail,
829                                  npos);
830     GNUNET_free (npos);
831   }
832   GNUNET_free (server);
833 }
834
835
836 /**
837  * Add additional handlers to an existing server.
838  *
839  * @param server the server to add handlers to
840  * @param handlers array of message handlers for
841  *        incoming messages; the last entry must
842  *        have "NULL" for the "callback"; multiple
843  *        entries for the same type are allowed,
844  *        they will be called in order of occurence.
845  *        These handlers can be removed later;
846  *        the handlers array must exist until removed
847  *        (or server is destroyed).
848  */
849 void
850 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
851                             const struct GNUNET_SERVER_MessageHandler *handlers)
852 {
853   struct HandlerList *p;
854
855   p = GNUNET_new (struct HandlerList);
856   p->handlers = handlers;
857   p->next = server->handlers;
858   server->handlers = p;
859 }
860
861
862 /**
863  * Change functions used by the server to tokenize the message stream.
864  * (very rarely used).
865  *
866  * @param server server to modify
867  * @param create new tokenizer initialization function
868  * @param destroy new tokenizer destruction function
869  * @param receive new tokenizer receive function
870  * @param cls closure for @a create, @a receive, @a destroy
871  */
872 void
873 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
874                              GNUNET_SERVER_MstCreateCallback create,
875                              GNUNET_SERVER_MstDestroyCallback destroy,
876                              GNUNET_SERVER_MstReceiveCallback receive,
877                              void *cls)
878 {
879   server->mst_create = create;
880   server->mst_destroy = destroy;
881   server->mst_receive = receive;
882   server->mst_cls = cls;
883 }
884
885
886 /**
887  * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
888  *
889  * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
890  * @param tc scheduler context (unused)
891  */
892 static void
893 warn_no_receive_done (void *cls,
894                       const struct GNUNET_SCHEDULER_TaskContext *tc)
895 {
896   struct GNUNET_SERVER_Client *client = cls;
897
898   GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
899   client->warn_task =
900       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
901                                     &warn_no_receive_done, client);
902   if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
903     LOG (GNUNET_ERROR_TYPE_WARNING,
904          _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
905          (unsigned int) client->warn_type,
906          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
907 }
908
909
910 /**
911  * Disable the warning the server issues if a message is not acknowledged
912  * in a timely fashion.  Use this call if a client is intentionally delayed
913  * for a while.  Only applies to the current message.
914  *
915  * @param client client for which to disable the warning
916  */
917 void
918 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
919 {
920   if (NULL != client->warn_task)
921   {
922     GNUNET_SCHEDULER_cancel (client->warn_task);
923     client->warn_task = NULL;
924   }
925 }
926
927
928 /**
929  * Inject a message into the server, pretend it came
930  * from the specified client.  Delivery of the message
931  * will happen instantly (if a handler is installed;
932  * otherwise the call does nothing).
933  *
934  * @param server the server receiving the message
935  * @param sender the "pretended" sender of the message
936  *        can be NULL!
937  * @param message message to transmit
938  * @return #GNUNET_OK if the message was OK and the
939  *                   connection can stay open
940  *         #GNUNET_SYSERR if the connection to the
941  *         client should be shut down
942  */
943 int
944 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
945                       struct GNUNET_SERVER_Client *sender,
946                       const struct GNUNET_MessageHeader *message)
947 {
948   struct HandlerList *pos;
949   const struct GNUNET_SERVER_MessageHandler *mh;
950   unsigned int i;
951   uint16_t type;
952   uint16_t size;
953   int found;
954
955   type = ntohs (message->type);
956   size = ntohs (message->size);
957   LOG (GNUNET_ERROR_TYPE_DEBUG,
958        "Server schedules transmission of %u-byte message of type %u to client.\n",
959        size, type);
960   found = GNUNET_NO;
961   for (pos = server->handlers; NULL != pos; pos = pos->next)
962   {
963     i = 0;
964     while (pos->handlers[i].callback != NULL)
965     {
966       mh = &pos->handlers[i];
967       if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
968       {
969         if ((0 != mh->expected_size) && (mh->expected_size != size))
970         {
971 #if GNUNET8_NETWORK_IS_DEAD
972           LOG (GNUNET_ERROR_TYPE_WARNING,
973                "Expected %u bytes for message of type %u, got %u\n",
974                mh->expected_size, mh->type, size);
975           GNUNET_break_op (0);
976 #else
977           LOG (GNUNET_ERROR_TYPE_DEBUG,
978                "Expected %u bytes for message of type %u, got %u\n",
979                mh->expected_size, mh->type, size);
980 #endif
981           return GNUNET_SYSERR;
982         }
983         if (NULL != sender)
984         {
985           if ( (0 == sender->suspended) &&
986                (NULL == sender->warn_task) )
987           {
988             GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
989             sender->warn_start = GNUNET_TIME_absolute_get ();
990             sender->warn_task =
991                 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
992                                               &warn_no_receive_done, sender);
993             sender->warn_type = type;
994           }
995           sender->suspended++;
996         }
997         mh->callback (mh->callback_cls, sender, message);
998         found = GNUNET_YES;
999       }
1000       i++;
1001     }
1002   }
1003   if (GNUNET_NO == found)
1004   {
1005     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1006          "Received message of unknown type %d\n", type);
1007     if (GNUNET_YES == server->require_found)
1008       return GNUNET_SYSERR;
1009   }
1010   return GNUNET_OK;
1011 }
1012
1013
1014 /**
1015  * We are receiving an incoming message.  Process it.
1016  *
1017  * @param cls our closure (handle for the client)
1018  * @param buf buffer with data received from network
1019  * @param available number of bytes available in buf
1020  * @param addr address of the sender
1021  * @param addrlen length of @a addr
1022  * @param errCode code indicating errors receiving, 0 for success
1023  */
1024 static void
1025 process_incoming (void *cls,
1026                   const void *buf,
1027                   size_t available,
1028                   const struct sockaddr *addr,
1029                   socklen_t addrlen,
1030                   int errCode);
1031
1032
1033 /**
1034  * Process messages from the client's message tokenizer until either
1035  * the tokenizer is empty (and then schedule receiving more), or
1036  * until some handler is not immediately done (then wait for restart_processing)
1037  * or shutdown.
1038  *
1039  * @param client the client to process, RC must have already been increased
1040  *        using #GNUNET_SERVER_client_keep and will be decreased by one in this
1041  *        function
1042  * @param ret #GNUNET_NO to start processing from the buffer,
1043  *            #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1044  *            #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1045  */
1046 static void
1047 process_mst (struct GNUNET_SERVER_Client *client,
1048              int ret)
1049 {
1050   while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1051          (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1052   {
1053     if (GNUNET_OK == ret)
1054     {
1055       LOG (GNUNET_ERROR_TYPE_DEBUG,
1056            "Server re-enters receive loop, timeout: %s.\n",
1057            GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1058       client->receive_pending = GNUNET_YES;
1059       GNUNET_CONNECTION_receive (client->connection,
1060                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1061                                  client->idle_timeout,
1062                                  &process_incoming,
1063                                  client);
1064       break;
1065     }
1066     LOG (GNUNET_ERROR_TYPE_DEBUG,
1067          "Server processes additional messages instantly.\n");
1068     if (NULL != client->server->mst_receive)
1069       ret =
1070           client->server->mst_receive (client->server->mst_cls, client->mst,
1071                                        client, NULL, 0, GNUNET_NO, GNUNET_YES);
1072     else
1073       ret =
1074           GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1075                                      GNUNET_YES);
1076   }
1077   LOG (GNUNET_ERROR_TYPE_DEBUG,
1078        "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1079        ret, client->server,
1080        client->shutdown_now,
1081        client->suspended);
1082   if (GNUNET_NO == ret)
1083   {
1084     LOG (GNUNET_ERROR_TYPE_DEBUG,
1085          "Server has more data pending but is suspended.\n");
1086     client->receive_pending = GNUNET_SYSERR;    /* data pending */
1087   }
1088   if ( (GNUNET_SYSERR == ret) ||
1089        (GNUNET_YES == client->shutdown_now) )
1090     GNUNET_SERVER_client_disconnect (client);
1091 }
1092
1093
1094 /**
1095  * We are receiving an incoming message.  Process it.
1096  *
1097  * @param cls our closure (handle for the client)
1098  * @param buf buffer with data received from network
1099  * @param available number of bytes available in buf
1100  * @param addr address of the sender
1101  * @param addrlen length of @a addr
1102  * @param errCode code indicating errors receiving, 0 for success
1103  */
1104 static void
1105 process_incoming (void *cls,
1106                   const void *buf,
1107                   size_t available,
1108                   const struct sockaddr *addr,
1109                   socklen_t addrlen,
1110                   int errCode)
1111 {
1112   struct GNUNET_SERVER_Client *client = cls;
1113   struct GNUNET_SERVER_Handle *server = client->server;
1114   struct GNUNET_TIME_Absolute end;
1115   struct GNUNET_TIME_Absolute now;
1116   int ret;
1117
1118   GNUNET_assert (GNUNET_YES == client->receive_pending);
1119   client->receive_pending = GNUNET_NO;
1120   now = GNUNET_TIME_absolute_get ();
1121   end = GNUNET_TIME_absolute_add (client->last_activity,
1122                                   client->idle_timeout);
1123
1124   if ( (NULL == buf) &&
1125        (0 == available) &&
1126        (NULL == addr) &&
1127        (0 == errCode) &&
1128        (GNUNET_YES != client->shutdown_now) &&
1129        (NULL != server) &&
1130        (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1131        (end.abs_value_us > now.abs_value_us) )
1132   {
1133     /* wait longer, timeout changed (i.e. due to us sending) */
1134     LOG (GNUNET_ERROR_TYPE_DEBUG,
1135          "Receive time out, but no disconnect due to sending (%p)\n",
1136          client);
1137     client->receive_pending = GNUNET_YES;
1138     GNUNET_CONNECTION_receive (client->connection,
1139                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1140                                GNUNET_TIME_absolute_get_remaining (end),
1141                                &process_incoming,
1142                                client);
1143     return;
1144   }
1145   if ( (NULL == buf) ||
1146        (0 == available) ||
1147        (0 != errCode) ||
1148        (NULL == server) ||
1149        (GNUNET_YES == client->shutdown_now) ||
1150        (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)) )
1151   {
1152     /* other side closed connection, error connecting, etc. */
1153     LOG (GNUNET_ERROR_TYPE_DEBUG,
1154          "Failed to connect or other side closed connection (%p)\n",
1155          client);
1156     GNUNET_SERVER_client_disconnect (client);
1157     return;
1158   }
1159   LOG (GNUNET_ERROR_TYPE_DEBUG,
1160        "Server receives %u bytes from `%s'.\n",
1161        (unsigned int) available,
1162        GNUNET_a2s (addr, addrlen));
1163   GNUNET_SERVER_client_keep (client);
1164   client->last_activity = now;
1165
1166   if (NULL != server->mst_receive)
1167   {
1168     ret = client->server->mst_receive (client->server->mst_cls,
1169                                        client->mst,
1170                                        client,
1171                                        buf,
1172                                        available,
1173                                        GNUNET_NO,
1174                                        GNUNET_YES);
1175   }
1176   else if (NULL != client->mst)
1177   {
1178     ret =
1179         GNUNET_SERVER_mst_receive (client->mst,
1180                                    client,
1181                                    buf,
1182                                    available,
1183                                    GNUNET_NO,
1184                                    GNUNET_YES);
1185   }
1186   else
1187   {
1188     GNUNET_break (0);
1189     return;
1190   }
1191   process_mst (client,
1192                ret);
1193   GNUNET_SERVER_client_drop (client);
1194 }
1195
1196
1197 /**
1198  * Task run to start again receiving from the network
1199  * and process requests.
1200  *
1201  * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
1202  * @param tc scheduler context (unused)
1203  */
1204 static void
1205 restart_processing (void *cls,
1206                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1207 {
1208   struct GNUNET_SERVER_Client *client = cls;
1209
1210   GNUNET_assert (GNUNET_YES != client->shutdown_now);
1211   client->restart_task = NULL;
1212   if (GNUNET_NO == client->receive_pending)
1213   {
1214     LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1215     client->receive_pending = GNUNET_YES;
1216     GNUNET_CONNECTION_receive (client->connection,
1217                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1218                                client->idle_timeout,
1219                                &process_incoming,
1220                                client);
1221     return;
1222   }
1223   LOG (GNUNET_ERROR_TYPE_DEBUG,
1224        "Server continues processing messages still in the buffer.\n");
1225   GNUNET_SERVER_client_keep (client);
1226   client->receive_pending = GNUNET_NO;
1227   process_mst (client,
1228                GNUNET_NO);
1229   GNUNET_SERVER_client_drop (client);
1230 }
1231
1232
1233 /**
1234  * This function is called whenever our inbound message tokenizer has
1235  * received a complete message.
1236  *
1237  * @param cls closure (struct GNUNET_SERVER_Handle)
1238  * @param client identification of the client (`struct GNUNET_SERVER_Client *`)
1239  * @param message the actual message
1240  *
1241  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1242  */
1243 static int
1244 client_message_tokenizer_callback (void *cls,
1245                                    void *client,
1246                                    const struct GNUNET_MessageHeader *message)
1247 {
1248   struct GNUNET_SERVER_Handle *server = cls;
1249   struct GNUNET_SERVER_Client *sender = client;
1250   int ret;
1251
1252   LOG (GNUNET_ERROR_TYPE_DEBUG,
1253        "Tokenizer gives server message of type %u from client\n",
1254        ntohs (message->type));
1255   sender->in_process_client_buffer = GNUNET_YES;
1256   ret = GNUNET_SERVER_inject (server, sender, message);
1257   sender->in_process_client_buffer = GNUNET_NO;
1258   if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1259   {
1260     GNUNET_SERVER_client_disconnect (sender);
1261     return GNUNET_SYSERR;
1262   }
1263   return GNUNET_OK;
1264 }
1265
1266
1267 /**
1268  * Add a TCP socket-based connection to the set of handles managed by
1269  * this server.  Use this function for outgoing (P2P) connections that
1270  * we initiated (and where this server should process incoming
1271  * messages).
1272  *
1273  * @param server the server to use
1274  * @param connection the connection to manage (client must
1275  *        stop using this connection from now on)
1276  * @return the client handle
1277  */
1278 struct GNUNET_SERVER_Client *
1279 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1280                               struct GNUNET_CONNECTION_Handle *connection)
1281 {
1282   struct GNUNET_SERVER_Client *client;
1283   struct NotifyList *n;
1284
1285   client = GNUNET_new (struct GNUNET_SERVER_Client);
1286   client->connection = connection;
1287   client->server = server;
1288   client->last_activity = GNUNET_TIME_absolute_get ();
1289   client->idle_timeout = server->idle_timeout;
1290   GNUNET_CONTAINER_DLL_insert (server->clients_head,
1291                                server->clients_tail,
1292                                client);
1293   if (NULL != server->mst_create)
1294     client->mst =
1295         server->mst_create (server->mst_cls, client);
1296   else
1297     client->mst =
1298         GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
1299                                   server);
1300   GNUNET_assert (NULL != client->mst);
1301   for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1302     n->callback (n->callback_cls, client);
1303   client->receive_pending = GNUNET_YES;
1304   GNUNET_CONNECTION_receive (client->connection,
1305                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1306                              client->idle_timeout,
1307                              &process_incoming,
1308                              client);
1309   return client;
1310 }
1311
1312
1313 /**
1314  * Change the timeout for a particular client.  Decreasing the timeout
1315  * may not go into effect immediately (only after the previous timeout
1316  * times out or activity happens on the socket).
1317  *
1318  * @param client the client to update
1319  * @param timeout new timeout for activities on the socket
1320  */
1321 void
1322 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1323                                   struct GNUNET_TIME_Relative timeout)
1324 {
1325   client->idle_timeout = timeout;
1326 }
1327
1328
1329 /**
1330  * Notify the server that the given client handle should
1331  * be kept (keeps the connection up if possible, increments
1332  * the internal reference counter).
1333  *
1334  * @param client the client to keep
1335  */
1336 void
1337 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1338 {
1339   client->reference_count++;
1340 }
1341
1342
1343 /**
1344  * Notify the server that the given client handle is no
1345  * longer required.  Decrements the reference counter.  If
1346  * that counter reaches zero an inactive connection maybe
1347  * closed.
1348  *
1349  * @param client the client to drop
1350  */
1351 void
1352 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1353 {
1354   GNUNET_assert (client->reference_count > 0);
1355   client->reference_count--;
1356   if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1357     GNUNET_SERVER_client_disconnect (client);
1358 }
1359
1360
1361 /**
1362  * Obtain the network address of the other party.
1363  *
1364  * @param client the client to get the address for
1365  * @param addr where to store the address
1366  * @param addrlen where to store the length of the @a addr
1367  * @return #GNUNET_OK on success
1368  */
1369 int
1370 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1371                                   void **addr, size_t * addrlen)
1372 {
1373   return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1374 }
1375
1376
1377 /**
1378  * Ask the server to notify us whenever a client disconnects.
1379  * This function is called whenever the actual network connection
1380  * is closed; the reference count may be zero or larger than zero
1381  * at this point.
1382  *
1383  * @param server the server manageing the clients
1384  * @param callback function to call on disconnect
1385  * @param callback_cls closure for @a callback
1386  */
1387 void
1388 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1389                                  GNUNET_SERVER_DisconnectCallback callback,
1390                                  void *callback_cls)
1391 {
1392   struct NotifyList *n;
1393
1394   n = GNUNET_new (struct NotifyList);
1395   n->callback = callback;
1396   n->callback_cls = callback_cls;
1397   GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1398                                server->disconnect_notify_list_tail,
1399                                n);
1400 }
1401
1402
1403 /**
1404  * Ask the server to notify us whenever a client connects.
1405  * This function is called whenever the actual network connection
1406  * is opened. If the server is destroyed before this
1407  * notification is explicitly cancelled, the 'callback' will
1408  * once be called with a 'client' argument of NULL to indicate
1409  * that the server itself is now gone (and that the callback
1410  * won't be called anymore and also can no longer be cancelled).
1411  *
1412  * @param server the server manageing the clients
1413  * @param callback function to call on sconnect
1414  * @param callback_cls closure for @a callback
1415  */
1416 void
1417 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1418                               GNUNET_SERVER_ConnectCallback callback,
1419                               void *callback_cls)
1420 {
1421   struct NotifyList *n;
1422   struct GNUNET_SERVER_Client *client;
1423
1424   n = GNUNET_new (struct NotifyList);
1425   n->callback = callback;
1426   n->callback_cls = callback_cls;
1427   GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1428                                server->connect_notify_list_tail,
1429                                n);
1430   for (client = server->clients_head; NULL != client; client = client->next)
1431     callback (callback_cls, client);
1432 }
1433
1434
1435 /**
1436  * Ask the server to stop notifying us whenever a client connects.
1437  *
1438  * @param server the server manageing the clients
1439  * @param callback function to call on connect
1440  * @param callback_cls closure for @a callback
1441  */
1442 void
1443 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1444                                         GNUNET_SERVER_DisconnectCallback callback,
1445                                         void *callback_cls)
1446 {
1447   struct NotifyList *pos;
1448
1449   for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1450     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1451       break;
1452   if (NULL == pos)
1453   {
1454     GNUNET_break (0);
1455     return;
1456   }
1457   GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1458                                server->disconnect_notify_list_tail,
1459                                pos);
1460   GNUNET_free (pos);
1461 }
1462
1463
1464 /**
1465  * Ask the server to stop notifying us whenever a client disconnects.
1466  *
1467  * @param server the server manageing the clients
1468  * @param callback function to call on disconnect
1469  * @param callback_cls closure for @a callback
1470  */
1471 void
1472 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1473                                      GNUNET_SERVER_ConnectCallback callback,
1474                                      void *callback_cls)
1475 {
1476   struct NotifyList *pos;
1477
1478   for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1479     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1480       break;
1481   if (NULL == pos)
1482   {
1483     GNUNET_break (0);
1484     return;
1485   }
1486   GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1487                                server->connect_notify_list_tail,
1488                                pos);
1489   GNUNET_free (pos);
1490 }
1491
1492
1493 /**
1494  * Destroy the connection that is passed in via @a cls.  Used
1495  * as calling #GNUNET_CONNECTION_destroy from within a function
1496  * that was itself called from within process_notify() of
1497  * 'connection.c' is not allowed (see #2329).
1498  *
1499  * @param cls connection to destroy
1500  * @param tc scheduler context (unused)
1501  */
1502 static void
1503 destroy_connection (void *cls,
1504                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1505 {
1506   struct GNUNET_CONNECTION_Handle *connection = cls;
1507
1508   GNUNET_CONNECTION_destroy (connection);
1509 }
1510
1511
1512 /**
1513  * Ask the server to disconnect from the given client.
1514  * This is the same as returning #GNUNET_SYSERR from a message
1515  * handler, except that it allows dropping of a client even
1516  * when not handling a message from that client.
1517  *
1518  * @param client the client to disconnect from
1519  */
1520 void
1521 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1522 {
1523   struct GNUNET_SERVER_Handle *server = client->server;
1524   struct NotifyList *n;
1525
1526   LOG (GNUNET_ERROR_TYPE_DEBUG,
1527        "Client is being disconnected from the server.\n");
1528   if (NULL != client->restart_task)
1529   {
1530     GNUNET_SCHEDULER_cancel (client->restart_task);
1531     client->restart_task = NULL;
1532   }
1533   if (NULL != client->warn_task)
1534   {
1535     GNUNET_SCHEDULER_cancel (client->warn_task);
1536     client->warn_task = NULL;
1537   }
1538   if (GNUNET_YES == client->receive_pending)
1539   {
1540     GNUNET_CONNECTION_receive_cancel (client->connection);
1541     client->receive_pending = GNUNET_NO;
1542   }
1543   client->shutdown_now = GNUNET_YES;
1544   client->reference_count++; /* make sure nobody else clean up client... */
1545   if ( (NULL != client->mst) &&
1546        (NULL != server) )
1547   {
1548     GNUNET_CONTAINER_DLL_remove (server->clients_head,
1549                                  server->clients_tail,
1550                                  client);
1551     if (NULL != server->mst_destroy)
1552       server->mst_destroy (server->mst_cls,
1553                            client->mst);
1554     else
1555       GNUNET_SERVER_mst_destroy (client->mst);
1556     client->mst = NULL;
1557     for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1558       n->callback (n->callback_cls,
1559                    client);
1560   }
1561   client->reference_count--;
1562   if (client->reference_count > 0)
1563   {
1564     LOG (GNUNET_ERROR_TYPE_DEBUG,
1565          "RC of %p still positive, not destroying everything.\n",
1566          client);
1567     client->server = NULL;
1568     return;
1569   }
1570   if (GNUNET_YES == client->in_process_client_buffer)
1571   {
1572     LOG (GNUNET_ERROR_TYPE_DEBUG,
1573          "Still processing inputs of %p, not destroying everything.\n",
1574          client);
1575     return;
1576   }
1577   LOG (GNUNET_ERROR_TYPE_DEBUG,
1578        "RC of %p now zero, destroying everything.\n",
1579        client);
1580   if (GNUNET_YES == client->persist)
1581     GNUNET_CONNECTION_persist_ (client->connection);
1582   if (NULL != client->th.cth)
1583     GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1584   (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1585                                    client->connection);
1586   /* need to cancel again, as it might have been re-added
1587      in the meantime (i.e. during callbacks) */
1588   if (NULL != client->warn_task)
1589   {
1590     GNUNET_SCHEDULER_cancel (client->warn_task);
1591     client->warn_task = NULL;
1592   }
1593   if (GNUNET_YES == client->receive_pending)
1594   {
1595     GNUNET_CONNECTION_receive_cancel (client->connection);
1596     client->receive_pending = GNUNET_NO;
1597   }
1598   GNUNET_free (client);
1599   /* we might be in soft-shutdown, test if we're done */
1600   if (NULL != server)
1601     test_monitor_clients (server);
1602 }
1603
1604
1605 /**
1606  * Disable the "CORK" feature for communication with the given client,
1607  * forcing the OS to immediately flush the buffer on transmission
1608  * instead of potentially buffering multiple messages.
1609  *
1610  * @param client handle to the client
1611  * @return #GNUNET_OK on success
1612  */
1613 int
1614 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1615 {
1616   return GNUNET_CONNECTION_disable_corking (client->connection);
1617 }
1618
1619
1620 /**
1621  * Wrapper for transmission notification that calls the original
1622  * callback and update the last activity time for our connection.
1623  *
1624  * @param cls the `struct GNUNET_SERVER_Client *`
1625  * @param size number of bytes we can transmit
1626  * @param buf where to copy the message
1627  * @return number of bytes actually transmitted
1628  */
1629 static size_t
1630 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1631 {
1632   struct GNUNET_SERVER_Client *client = cls;
1633   GNUNET_CONNECTION_TransmitReadyNotify callback;
1634
1635   client->th.cth = NULL;
1636   callback = client->th.callback;
1637   client->th.callback = NULL;
1638   client->last_activity = GNUNET_TIME_absolute_get ();
1639   return callback (client->th.callback_cls, size, buf);
1640 }
1641
1642
1643 /**
1644  * Notify us when the server has enough space to transmit
1645  * a message of the given size to the given client.
1646  *
1647  * @param client client to transmit message to
1648  * @param size requested amount of buffer space
1649  * @param timeout after how long should we give up (and call
1650  *        notify with buf NULL and size 0)?
1651  * @param callback function to call when space is available
1652  * @param callback_cls closure for @a callback
1653  * @return non-NULL if the notify callback was queued; can be used
1654  *         to cancel the request using
1655  *         #GNUNET_SERVER_notify_transmit_ready_cancel().
1656  *         NULL if we are already going to notify someone else (busy)
1657  */
1658 struct GNUNET_SERVER_TransmitHandle *
1659 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1660                                      size_t size,
1661                                      struct GNUNET_TIME_Relative timeout,
1662                                      GNUNET_CONNECTION_TransmitReadyNotify callback,
1663                                      void *callback_cls)
1664 {
1665   if (NULL != client->th.callback)
1666     return NULL;
1667   client->th.callback_cls = callback_cls;
1668   client->th.callback = callback;
1669   client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1670                                                             timeout,
1671                                                             &transmit_ready_callback_wrapper,
1672                                                             client);
1673   return &client->th;
1674 }
1675
1676
1677 /**
1678  * Abort transmission request.
1679  *
1680  * @param th request to abort
1681  */
1682 void
1683 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1684 {
1685   GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1686   th->cth = NULL;
1687   th->callback = NULL;
1688 }
1689
1690
1691 /**
1692  * Set the persistent flag on this client, used to setup client connection
1693  * to only be killed when the service it's connected to is actually dead.
1694  *
1695  * @param client the client to set the persistent flag on
1696  */
1697 void
1698 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1699 {
1700   client->persist = GNUNET_YES;
1701 }
1702
1703
1704 /**
1705  * Resume receiving from this client, we are done processing the
1706  * current request.  This function must be called from within each
1707  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1708  *
1709  * @param client client we were processing a message of
1710  * @param success #GNUNET_OK to keep the connection open and
1711  *                          continue to receive
1712  *                #GNUNET_NO to close the connection (normal behavior)
1713  *                #GNUNET_SYSERR to close the connection (signal
1714  *                          serious error)
1715  */
1716 void
1717 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1718                             int success)
1719 {
1720   if (NULL == client)
1721     return;
1722   GNUNET_assert (client->suspended > 0);
1723   client->suspended--;
1724   if (GNUNET_OK != success)
1725   {
1726     LOG (GNUNET_ERROR_TYPE_DEBUG,
1727          "GNUNET_SERVER_receive_done called with failure indication\n");
1728     if ( (client->reference_count > 0) || (client->suspended > 0) )
1729       client->shutdown_now = GNUNET_YES;
1730     else
1731       GNUNET_SERVER_client_disconnect (client);
1732     return;
1733   }
1734   if (client->suspended > 0)
1735   {
1736     LOG (GNUNET_ERROR_TYPE_DEBUG,
1737          "GNUNET_SERVER_receive_done called, but more clients pending\n");
1738     return;
1739   }
1740   if (NULL != client->warn_task)
1741   {
1742     GNUNET_SCHEDULER_cancel (client->warn_task);
1743     client->warn_task = NULL;
1744   }
1745   if (GNUNET_YES == client->in_process_client_buffer)
1746   {
1747     LOG (GNUNET_ERROR_TYPE_DEBUG,
1748          "GNUNET_SERVER_receive_done called while still in processing loop\n");
1749     return;
1750   }
1751   if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1752   {
1753     GNUNET_SERVER_client_disconnect (client);
1754     return;
1755   }
1756   LOG (GNUNET_ERROR_TYPE_DEBUG,
1757        "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1758   GNUNET_assert (NULL == client->restart_task);
1759   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing,
1760                                                    client);
1761 }
1762
1763
1764 /* end of server.c */