-disable NSE POW during cadet tests
[oweals/gnunet.git] / src / util / server.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 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 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., 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_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;
126
127   /**
128    * Closure for access.
129    */
130   void *access_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   GNUNET_SCHEDULER_TaskIdentifier 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   GNUNET_SCHEDULER_TaskIdentifier restart_task;
250
251   /**
252    * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
253    */
254   GNUNET_SCHEDULER_TaskIdentifier 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   struct GNUNET_SERVER_Client *client;
401   unsigned int i;
402
403   server->listen_task = GNUNET_SCHEDULER_NO_TASK;
404   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
405   {
406     /* ignore shutdown, someone else will take care of it! */
407     GNUNET_SERVER_resume (server);
408     return;
409   }
410   i = 0;
411   while (NULL != server->listen_sockets[i])
412   {
413     if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
414     {
415       sock =
416           GNUNET_CONNECTION_create_from_accept (server->access,
417                                                 server->access_cls,
418                                                 server->listen_sockets[i]);
419       if (NULL != sock)
420       {
421         LOG (GNUNET_ERROR_TYPE_DEBUG,
422              "Server accepted incoming connection.\n");
423         client = GNUNET_SERVER_connect_socket (server, sock);
424         /* decrement reference count, we don't keep "client" alive */
425         GNUNET_SERVER_client_drop (client);
426       }
427     }
428     i++;
429   }
430   /* listen for more! */
431   GNUNET_SERVER_resume (server);
432 }
433
434
435 /**
436  * Create and initialize a listen socket for the server.
437  *
438  * @param server_addr address to listen on
439  * @param socklen length of @a server_addr
440  * @return NULL on error, otherwise the listen socket
441  */
442 static struct GNUNET_NETWORK_Handle *
443 open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
444 {
445   struct GNUNET_NETWORK_Handle *sock;
446   uint16_t port;
447   int eno;
448
449   switch (server_addr->sa_family)
450   {
451   case AF_INET:
452     port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
453     break;
454   case AF_INET6:
455     port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
456     break;
457   case AF_UNIX:
458     port = 0;
459     break;
460   default:
461     GNUNET_break (0);
462     port = 0;
463     break;
464   }
465   sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
466   if (NULL == sock)
467   {
468     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
469     errno = 0;
470     return NULL;
471   }
472   /* bind the socket */
473   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
474   {
475     eno = errno;
476     if (EADDRINUSE != errno)
477     {
478       /* we don't log 'EADDRINUSE' here since an IPv4 bind may
479        * fail if we already took the port on IPv6; if both IPv4 and
480        * IPv6 binds fail, then our caller will log using the
481        * errno preserved in 'eno' */
482       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
483       if (0 != port)
484         LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
485              "bind", 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, "listen");
511     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
512     errno = 0;
513     return NULL;
514   }
515   if (0 != port)
516     LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
517          port);
518   return sock;
519 }
520
521
522 /**
523  * Create a new server.
524  *
525  * @param access function for access control
526  * @param access_cls closure for access
527  * @param lsocks NULL-terminated array of listen sockets
528  * @param idle_timeout after how long should we timeout idle connections?
529  * @param require_found if #GNUNET_YES, connections sending messages of unknown type
530  *        will be closed
531  * @return handle for the new server, NULL on error
532  *         (typically, "port" already in use)
533  */
534 struct GNUNET_SERVER_Handle *
535 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
536                                    void *access_cls,
537                                    struct GNUNET_NETWORK_Handle **lsocks,
538                                    struct GNUNET_TIME_Relative idle_timeout,
539                                    int require_found)
540 {
541   struct GNUNET_SERVER_Handle *server;
542
543   server = GNUNET_new (struct GNUNET_SERVER_Handle);
544   server->idle_timeout = idle_timeout;
545   server->listen_sockets = lsocks;
546   server->access = access;
547   server->access_cls = access_cls;
548   server->require_found = require_found;
549   if (NULL != lsocks)
550     GNUNET_SERVER_resume (server);
551   return server;
552 }
553
554
555 /**
556  * Create a new server.
557  *
558  * @param access function for access control
559  * @param access_cls closure for access
560  * @param server_addr address to listen on (including port), NULL terminated array
561  * @param socklen length of server_addr
562  * @param idle_timeout after how long should we timeout idle connections?
563  * @param require_found if YES, connections sending messages of unknown type
564  *        will be closed
565  * @return handle for the new server, NULL on error
566  *         (typically, "port" already in use)
567  */
568 struct GNUNET_SERVER_Handle *
569 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
570                       struct sockaddr *const *server_addr,
571                       const socklen_t * socklen,
572                       struct GNUNET_TIME_Relative idle_timeout,
573                       int require_found)
574 {
575   struct GNUNET_NETWORK_Handle **lsocks;
576   unsigned int i;
577   unsigned int j;
578   unsigned int k;
579   int seen;
580
581   i = 0;
582   while (NULL != server_addr[i])
583     i++;
584   if (i > 0)
585   {
586     lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
587     i = 0;
588     j = 0;
589     while (NULL != server_addr[i])
590     {
591       seen = 0;
592       for (k=0;k<i;k++)
593         if ( (socklen[k] == socklen[i]) &&
594              (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
595         {
596           seen = 1;
597           break;
598         }
599       if (0 != seen)
600       {
601         /* duplicate address, skip */
602         i++;
603         continue;
604       }
605       lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
606       if (NULL != lsocks[j])
607         j++;
608       i++;
609     }
610     if (0 == j)
611     {
612       if (0 != errno)
613         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
614       GNUNET_free (lsocks);
615       lsocks = NULL;
616     }
617   }
618   else
619   {
620     lsocks = NULL;
621   }
622   return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
623                                             idle_timeout, require_found);
624 }
625
626
627 /**
628  * Set the 'monitor' flag on this client.  Clients which have been
629  * marked as 'monitors' won't prevent the server from shutting down
630  * once '#GNUNET_SERVER_stop_listening()' has been invoked.  The idea is
631  * that for "normal" clients we likely want to allow them to process
632  * their requests; however, monitor-clients are likely to 'never'
633  * disconnect during shutdown and thus will not be considered when
634  * determining if the server should continue to exist after
635  * 'GNUNET_SERVER_destroy' has been called.
636  *
637  * @param client the client to set the 'monitor' flag on
638  */
639 void
640 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
641 {
642   client->is_monitor = GNUNET_YES;
643 }
644
645
646 /**
647  * Helper function for 'test_monitor_clients' to trigger
648  * 'GNUNET_SERVER_destroy' after the stack has unwound.
649  *
650  * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
651  * @param tc unused
652  */
653 static void
654 do_destroy (void *cls,
655             const struct GNUNET_SCHEDULER_TaskContext *tc)
656 {
657   struct GNUNET_SERVER_Handle *server = cls;
658   GNUNET_SERVER_destroy (server);
659 }
660
661
662 /**
663  * Check if only 'monitor' clients are left.  If so, destroy the
664  * server completely.
665  *
666  * @param server server to test for full shutdown
667  */
668 static void
669 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
670 {
671   struct GNUNET_SERVER_Client *client;
672
673   if (GNUNET_YES != server->in_soft_shutdown)
674     return;
675   for (client = server->clients_head; NULL != client; client = client->next)
676     if (GNUNET_NO == client->is_monitor)
677       return; /* not done yet */
678   server->in_soft_shutdown = GNUNET_SYSERR;
679   GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
680                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
681 }
682
683
684 /**
685  * Suspend accepting connections from the listen socket temporarily.
686  *
687  * @param server server to stop accepting connections.
688  */
689 void
690 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
691 {
692   if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
693   {
694     GNUNET_SCHEDULER_cancel (server->listen_task);
695     server->listen_task = GNUNET_SCHEDULER_NO_TASK;
696   }
697 }
698
699
700 /**
701  * Resume accepting connections from the listen socket.
702  *
703  * @param server server to stop accepting connections.
704  */
705 void
706 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
707 {
708   struct GNUNET_NETWORK_FDSet *r;
709   unsigned int i;
710
711   if (NULL == server->listen_sockets)
712     return;
713   if (NULL == server->listen_sockets[0])
714     return; /* nothing to do, no listen sockets! */
715   if (NULL == server->listen_sockets[1])
716   {
717     /* simplified method: no fd set needed; this is then much simpler and
718        much more efficient */
719     server->listen_task =
720       GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
721                                                    GNUNET_SCHEDULER_PRIORITY_HIGH,
722                                                    server->listen_sockets[0],
723                                                    &process_listen_socket, server);
724     return;
725   }
726   r = GNUNET_NETWORK_fdset_create ();
727   i = 0;
728   while (NULL != server->listen_sockets[i])
729     GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
730   server->listen_task =
731     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
732                                  GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
733                                  &process_listen_socket, server);
734   GNUNET_NETWORK_fdset_destroy (r);
735 }
736
737
738 /**
739  * Stop the listen socket and get ready to shutdown the server
740  * once only 'monitor' clients are left.
741  *
742  * @param server server to stop listening on
743  */
744 void
745 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
746 {
747   unsigned int i;
748
749   LOG (GNUNET_ERROR_TYPE_DEBUG,
750        "Server in soft shutdown\n");
751   if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
752   {
753     GNUNET_SCHEDULER_cancel (server->listen_task);
754     server->listen_task = GNUNET_SCHEDULER_NO_TASK;
755   }
756   if (NULL != server->listen_sockets)
757   {
758     i = 0;
759     while (NULL != server->listen_sockets[i])
760       GNUNET_break (GNUNET_OK ==
761                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
762     GNUNET_free (server->listen_sockets);
763     server->listen_sockets = NULL;
764   }
765   if (GNUNET_NO == server->in_soft_shutdown)
766     server->in_soft_shutdown = GNUNET_YES;
767   test_monitor_clients (server);
768 }
769
770
771 /**
772  * Free resources held by this server.
773  *
774  * @param server server to destroy
775  */
776 void
777 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
778 {
779   struct HandlerList *hpos;
780   struct NotifyList *npos;
781   unsigned int i;
782
783   LOG (GNUNET_ERROR_TYPE_DEBUG,
784        "Server shutting down.\n");
785   if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
786   {
787     GNUNET_SCHEDULER_cancel (server->listen_task);
788     server->listen_task = GNUNET_SCHEDULER_NO_TASK;
789   }
790   if (NULL != server->listen_sockets)
791   {
792     i = 0;
793     while (NULL != server->listen_sockets[i])
794       GNUNET_break (GNUNET_OK ==
795                     GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
796     GNUNET_free (server->listen_sockets);
797     server->listen_sockets = NULL;
798   }
799   while (NULL != server->clients_head)
800     GNUNET_SERVER_client_disconnect (server->clients_head);
801   while (NULL != (hpos = server->handlers))
802   {
803     server->handlers = hpos->next;
804     GNUNET_free (hpos);
805   }
806   while (NULL != (npos = server->disconnect_notify_list_head))
807   {
808     npos->callback (npos->callback_cls, NULL);
809     GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
810                                  server->disconnect_notify_list_tail,
811                                  npos);
812     GNUNET_free (npos);
813   }
814   while (NULL != (npos = server->connect_notify_list_head))
815   {
816     npos->callback (npos->callback_cls, NULL);
817     GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
818                                  server->connect_notify_list_tail,
819                                  npos);
820     GNUNET_free (npos);
821   }
822   GNUNET_free (server);
823 }
824
825
826 /**
827  * Add additional handlers to an existing server.
828  *
829  * @param server the server to add handlers to
830  * @param handlers array of message handlers for
831  *        incoming messages; the last entry must
832  *        have "NULL" for the "callback"; multiple
833  *        entries for the same type are allowed,
834  *        they will be called in order of occurence.
835  *        These handlers can be removed later;
836  *        the handlers array must exist until removed
837  *        (or server is destroyed).
838  */
839 void
840 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
841                             const struct GNUNET_SERVER_MessageHandler *handlers)
842 {
843   struct HandlerList *p;
844
845   p = GNUNET_new (struct HandlerList);
846   p->handlers = handlers;
847   p->next = server->handlers;
848   server->handlers = p;
849 }
850
851
852 /**
853  * Change functions used by the server to tokenize the message stream.
854  * (very rarely used).
855  *
856  * @param server server to modify
857  * @param create new tokenizer initialization function
858  * @param destroy new tokenizer destruction function
859  * @param receive new tokenizer receive function
860  * @param cls closure for @a create, @a receive, @a destroy
861  */
862 void
863 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
864                              GNUNET_SERVER_MstCreateCallback create,
865                              GNUNET_SERVER_MstDestroyCallback destroy,
866                              GNUNET_SERVER_MstReceiveCallback receive,
867                              void *cls)
868 {
869   server->mst_create = create;
870   server->mst_destroy = destroy;
871   server->mst_receive = receive;
872   server->mst_cls = cls;
873 }
874
875
876 /**
877  * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
878  *
879  * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
880  * @param tc scheduler context (unused)
881  */
882 static void
883 warn_no_receive_done (void *cls,
884                       const struct GNUNET_SCHEDULER_TaskContext *tc)
885 {
886   struct GNUNET_SERVER_Client *client = cls;
887
888   GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
889   client->warn_task =
890       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
891                                     &warn_no_receive_done, client);
892   if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
893     LOG (GNUNET_ERROR_TYPE_WARNING,
894          _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
895          (unsigned int) client->warn_type,
896          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
897 }
898
899
900 /**
901  * Disable the warning the server issues if a message is not acknowledged
902  * in a timely fashion.  Use this call if a client is intentionally delayed
903  * for a while.  Only applies to the current message.
904  *
905  * @param client client for which to disable the warning
906  */
907 void
908 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
909 {
910   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
911   {
912     GNUNET_SCHEDULER_cancel (client->warn_task);
913     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
914   }
915 }
916
917
918 /**
919  * Inject a message into the server, pretend it came
920  * from the specified client.  Delivery of the message
921  * will happen instantly (if a handler is installed;
922  * otherwise the call does nothing).
923  *
924  * @param server the server receiving the message
925  * @param sender the "pretended" sender of the message
926  *        can be NULL!
927  * @param message message to transmit
928  * @return GNUNET_OK if the message was OK and the
929  *                   connection can stay open
930  *         GNUNET_SYSERR if the connection to the
931  *         client should be shut down
932  */
933 int
934 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
935                       struct GNUNET_SERVER_Client *sender,
936                       const struct GNUNET_MessageHeader *message)
937 {
938   struct HandlerList *pos;
939   const struct GNUNET_SERVER_MessageHandler *mh;
940   unsigned int i;
941   uint16_t type;
942   uint16_t size;
943   int found;
944
945   type = ntohs (message->type);
946   size = ntohs (message->size);
947   LOG (GNUNET_ERROR_TYPE_DEBUG,
948        "Server schedules transmission of %u-byte message of type %u to client.\n",
949        size, type);
950   found = GNUNET_NO;
951   for (pos = server->handlers; NULL != pos; pos = pos->next)
952   {
953     i = 0;
954     while (pos->handlers[i].callback != NULL)
955     {
956       mh = &pos->handlers[i];
957       if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
958       {
959         if ((0 != mh->expected_size) && (mh->expected_size != size))
960         {
961 #if GNUNET8_NETWORK_IS_DEAD
962           LOG (GNUNET_ERROR_TYPE_WARNING,
963                "Expected %u bytes for message of type %u, got %u\n",
964                mh->expected_size, mh->type, size);
965           GNUNET_break_op (0);
966 #else
967           LOG (GNUNET_ERROR_TYPE_DEBUG,
968                "Expected %u bytes for message of type %u, got %u\n",
969                mh->expected_size, mh->type, size);
970 #endif
971           return GNUNET_SYSERR;
972         }
973         if (NULL != sender)
974         {
975           if ( (0 == sender->suspended) &&
976                (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
977           {
978             GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
979             sender->warn_start = GNUNET_TIME_absolute_get ();
980             sender->warn_task =
981                 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
982                                               &warn_no_receive_done, sender);
983             sender->warn_type = type;
984           }
985           sender->suspended++;
986         }
987         mh->callback (mh->callback_cls, sender, message);
988         found = GNUNET_YES;
989       }
990       i++;
991     }
992   }
993   if (GNUNET_NO == found)
994   {
995     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
996          "Received message of unknown type %d\n", type);
997     if (GNUNET_YES == server->require_found)
998       return GNUNET_SYSERR;
999   }
1000   return GNUNET_OK;
1001 }
1002
1003
1004 /**
1005  * We are receiving an incoming message.  Process it.
1006  *
1007  * @param cls our closure (handle for the client)
1008  * @param buf buffer with data received from network
1009  * @param available number of bytes available in buf
1010  * @param addr address of the sender
1011  * @param addrlen length of @a addr
1012  * @param errCode code indicating errors receiving, 0 for success
1013  */
1014 static void
1015 process_incoming (void *cls,
1016                   const void *buf,
1017                   size_t available,
1018                   const struct sockaddr *addr,
1019                   socklen_t addrlen,
1020                   int errCode);
1021
1022
1023 /**
1024  * Process messages from the client's message tokenizer until either
1025  * the tokenizer is empty (and then schedule receiving more), or
1026  * until some handler is not immediately done (then wait for restart_processing)
1027  * or shutdown.
1028  *
1029  * @param client the client to process, RC must have already been increased
1030  *        using #GNUNET_SERVER_client_keep and will be decreased by one in this
1031  *        function
1032  * @param ret #GNUNET_NO to start processing from the buffer,
1033  *            #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1034  *            #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1035  */
1036 static void
1037 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1038 {
1039   while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1040          (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1041   {
1042     if (GNUNET_OK == ret)
1043     {
1044       LOG (GNUNET_ERROR_TYPE_DEBUG,
1045            "Server re-enters receive loop, timeout: %s.\n",
1046            GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1047       client->receive_pending = GNUNET_YES;
1048       GNUNET_CONNECTION_receive (client->connection,
1049                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1050                                  client->idle_timeout, &process_incoming,
1051                                  client);
1052       break;
1053     }
1054     LOG (GNUNET_ERROR_TYPE_DEBUG,
1055          "Server processes additional messages instantly.\n");
1056     if (NULL != client->server->mst_receive)
1057       ret =
1058           client->server->mst_receive (client->server->mst_cls, client->mst,
1059                                        client, NULL, 0, GNUNET_NO, GNUNET_YES);
1060     else
1061       ret =
1062           GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1063                                      GNUNET_YES);
1064   }
1065   LOG (GNUNET_ERROR_TYPE_DEBUG,
1066        "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1067        ret, client->server,
1068        client->shutdown_now,
1069        client->suspended);
1070   if (GNUNET_NO == ret)
1071   {
1072     LOG (GNUNET_ERROR_TYPE_DEBUG,
1073          "Server has more data pending but is suspended.\n");
1074     client->receive_pending = GNUNET_SYSERR;    /* data pending */
1075   }
1076   if ( (GNUNET_SYSERR == ret) ||
1077        (GNUNET_YES == client->shutdown_now) )
1078     GNUNET_SERVER_client_disconnect (client);
1079 }
1080
1081
1082 /**
1083  * We are receiving an incoming message.  Process it.
1084  *
1085  * @param cls our closure (handle for the client)
1086  * @param buf buffer with data received from network
1087  * @param available number of bytes available in buf
1088  * @param addr address of the sender
1089  * @param addrlen length of addr
1090  * @param errCode code indicating errors receiving, 0 for success
1091  */
1092 static void
1093 process_incoming (void *cls, const void *buf, size_t available,
1094                   const struct sockaddr *addr, socklen_t addrlen, int errCode)
1095 {
1096   struct GNUNET_SERVER_Client *client = cls;
1097   struct GNUNET_SERVER_Handle *server = client->server;
1098   struct GNUNET_TIME_Absolute end;
1099   struct GNUNET_TIME_Absolute now;
1100   int ret;
1101
1102   GNUNET_assert (GNUNET_YES == client->receive_pending);
1103   client->receive_pending = GNUNET_NO;
1104   now = GNUNET_TIME_absolute_get ();
1105   end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1106
1107   if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1108       (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1109       (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1110       (end.abs_value_us > now.abs_value_us))
1111   {
1112     /* wait longer, timeout changed (i.e. due to us sending) */
1113     LOG (GNUNET_ERROR_TYPE_DEBUG,
1114          "Receive time out, but no disconnect due to sending (%p)\n",
1115          GNUNET_a2s (addr, addrlen));
1116     client->receive_pending = GNUNET_YES;
1117     GNUNET_CONNECTION_receive (client->connection,
1118                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1119                                GNUNET_TIME_absolute_get_remaining (end),
1120                                &process_incoming, client);
1121     return;
1122   }
1123   if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1124       (GNUNET_YES == client->shutdown_now) ||
1125       (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1126   {
1127     /* other side closed connection, error connecting, etc. */
1128     GNUNET_SERVER_client_disconnect (client);
1129     return;
1130   }
1131   LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1132        (unsigned int) available, GNUNET_a2s (addr, addrlen));
1133   GNUNET_SERVER_client_keep (client);
1134   client->last_activity = now;
1135
1136   if (NULL != server->mst_receive)
1137     ret =
1138         client->server->mst_receive (client->server->mst_cls, client->mst,
1139                                      client, buf, available, GNUNET_NO, GNUNET_YES);
1140   else if (NULL != client->mst)
1141   {
1142     ret =
1143         GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1144                                    GNUNET_YES);
1145   }
1146   else
1147   {
1148     GNUNET_break (0);
1149     return;
1150   }
1151
1152   process_mst (client, ret);
1153   GNUNET_SERVER_client_drop (client);
1154 }
1155
1156
1157 /**
1158  * Task run to start again receiving from the network
1159  * and process requests.
1160  *
1161  * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1162  * @param tc scheduler context (unused)
1163  */
1164 static void
1165 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1166 {
1167   struct GNUNET_SERVER_Client *client = cls;
1168
1169   GNUNET_assert (GNUNET_YES != client->shutdown_now);
1170   client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1171   if (GNUNET_NO == client->receive_pending)
1172   {
1173     LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1174     client->receive_pending = GNUNET_YES;
1175     GNUNET_CONNECTION_receive (client->connection,
1176                                GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1177                                client->idle_timeout, &process_incoming, client);
1178     return;
1179   }
1180   LOG (GNUNET_ERROR_TYPE_DEBUG,
1181        "Server continues processing messages still in the buffer.\n");
1182   GNUNET_SERVER_client_keep (client);
1183   client->receive_pending = GNUNET_NO;
1184   process_mst (client, GNUNET_NO);
1185   GNUNET_SERVER_client_drop (client);
1186 }
1187
1188
1189 /**
1190  * This function is called whenever our inbound message tokenizer has
1191  * received a complete message.
1192  *
1193  * @param cls closure (struct GNUNET_SERVER_Handle)
1194  * @param client identification of the client (struct GNUNET_SERVER_Client*)
1195  * @param message the actual message
1196  *
1197  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1198  */
1199 static int
1200 client_message_tokenizer_callback (void *cls, void *client,
1201                                    const struct GNUNET_MessageHeader *message)
1202 {
1203   struct GNUNET_SERVER_Handle *server = cls;
1204   struct GNUNET_SERVER_Client *sender = client;
1205   int ret;
1206
1207   LOG (GNUNET_ERROR_TYPE_DEBUG,
1208        "Tokenizer gives server message of type %u from client\n",
1209        ntohs (message->type));
1210   sender->in_process_client_buffer = GNUNET_YES;
1211   ret = GNUNET_SERVER_inject (server, sender, message);
1212   sender->in_process_client_buffer = GNUNET_NO;
1213   if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1214   {
1215     GNUNET_SERVER_client_disconnect (sender);
1216     return GNUNET_SYSERR;
1217   }
1218   return GNUNET_OK;
1219 }
1220
1221
1222 /**
1223  * Add a TCP socket-based connection to the set of handles managed by
1224  * this server.  Use this function for outgoing (P2P) connections that
1225  * we initiated (and where this server should process incoming
1226  * messages).
1227  *
1228  * @param server the server to use
1229  * @param connection the connection to manage (client must
1230  *        stop using this connection from now on)
1231  * @return the client handle (client should call
1232  *         "client_drop" on the return value eventually)
1233  */
1234 struct GNUNET_SERVER_Client *
1235 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1236                               struct GNUNET_CONNECTION_Handle *connection)
1237 {
1238   struct GNUNET_SERVER_Client *client;
1239   struct NotifyList *n;
1240
1241   client = GNUNET_new (struct GNUNET_SERVER_Client);
1242   client->connection = connection;
1243   client->reference_count = 1;
1244   client->server = server;
1245   client->last_activity = GNUNET_TIME_absolute_get ();
1246   client->idle_timeout = server->idle_timeout;
1247   GNUNET_CONTAINER_DLL_insert (server->clients_head,
1248                                server->clients_tail,
1249                                client);
1250   if (NULL != server->mst_create)
1251     client->mst =
1252         server->mst_create (server->mst_cls, client);
1253   else
1254     client->mst =
1255         GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1256   GNUNET_assert (NULL != client->mst);
1257   for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1258     n->callback (n->callback_cls, client);
1259
1260   client->receive_pending = GNUNET_YES;
1261   GNUNET_CONNECTION_receive (client->connection,
1262                              GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1263                              client->idle_timeout, &process_incoming, client);
1264   return client;
1265 }
1266
1267
1268 /**
1269  * Change the timeout for a particular client.  Decreasing the timeout
1270  * may not go into effect immediately (only after the previous timeout
1271  * times out or activity happens on the socket).
1272  *
1273  * @param client the client to update
1274  * @param timeout new timeout for activities on the socket
1275  */
1276 void
1277 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1278                                   struct GNUNET_TIME_Relative timeout)
1279 {
1280   client->idle_timeout = timeout;
1281 }
1282
1283
1284 /**
1285  * Notify the server that the given client handle should
1286  * be kept (keeps the connection up if possible, increments
1287  * the internal reference counter).
1288  *
1289  * @param client the client to keep
1290  */
1291 void
1292 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1293 {
1294   client->reference_count++;
1295 }
1296
1297
1298 /**
1299  * Notify the server that the given client handle is no
1300  * longer required.  Decrements the reference counter.  If
1301  * that counter reaches zero an inactive connection maybe
1302  * closed.
1303  *
1304  * @param client the client to drop
1305  */
1306 void
1307 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1308 {
1309   GNUNET_assert (client->reference_count > 0);
1310   client->reference_count--;
1311   if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1312     GNUNET_SERVER_client_disconnect (client);
1313 }
1314
1315
1316 /**
1317  * Obtain the network address of the other party.
1318  *
1319  * @param client the client to get the address for
1320  * @param addr where to store the address
1321  * @param addrlen where to store the length of the address
1322  * @return GNUNET_OK on success
1323  */
1324 int
1325 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1326                                   void **addr, size_t * addrlen)
1327 {
1328   return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1329 }
1330
1331
1332 /**
1333  * Ask the server to notify us whenever a client disconnects.
1334  * This function is called whenever the actual network connection
1335  * is closed; the reference count may be zero or larger than zero
1336  * at this point.
1337  *
1338  * @param server the server manageing the clients
1339  * @param callback function to call on disconnect
1340  * @param callback_cls closure for @a callback
1341  */
1342 void
1343 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1344                                  GNUNET_SERVER_DisconnectCallback callback,
1345                                  void *callback_cls)
1346 {
1347   struct NotifyList *n;
1348
1349   n = GNUNET_new (struct NotifyList);
1350   n->callback = callback;
1351   n->callback_cls = callback_cls;
1352   GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1353                                server->disconnect_notify_list_tail,
1354                                n);
1355 }
1356
1357
1358 /**
1359  * Ask the server to notify us whenever a client connects.
1360  * This function is called whenever the actual network connection
1361  * is opened. If the server is destroyed before this
1362  * notification is explicitly cancelled, the 'callback' will
1363  * once be called with a 'client' argument of NULL to indicate
1364  * that the server itself is now gone (and that the callback
1365  * won't be called anymore and also can no longer be cancelled).
1366  *
1367  * @param server the server manageing the clients
1368  * @param callback function to call on sconnect
1369  * @param callback_cls closure for @a callback
1370  */
1371 void
1372 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1373                               GNUNET_SERVER_ConnectCallback callback,
1374                               void *callback_cls)
1375 {
1376   struct NotifyList *n;
1377
1378   n = GNUNET_new (struct NotifyList);
1379   n->callback = callback;
1380   n->callback_cls = callback_cls;
1381   GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1382                                server->connect_notify_list_tail,
1383                                n);
1384 }
1385
1386
1387 /**
1388  * Ask the server to stop notifying us whenever a client connects.
1389  *
1390  * @param server the server manageing the clients
1391  * @param callback function to call on connect
1392  * @param callback_cls closure for @a callback
1393  */
1394 void
1395 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1396                                         GNUNET_SERVER_DisconnectCallback
1397                                         callback, void *callback_cls)
1398 {
1399   struct NotifyList *pos;
1400
1401   for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1402     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1403       break;
1404   if (NULL == pos)
1405   {
1406     GNUNET_break (0);
1407     return;
1408   }
1409   GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1410                                server->disconnect_notify_list_tail,
1411                                pos);
1412   GNUNET_free (pos);
1413 }
1414
1415
1416 /**
1417  * Ask the server to stop notifying us whenever a client disconnects.
1418  *
1419  * @param server the server manageing the clients
1420  * @param callback function to call on disconnect
1421  * @param callback_cls closure for @a callback
1422  */
1423 void
1424 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1425                                      GNUNET_SERVER_ConnectCallback callback,
1426                                      void *callback_cls)
1427 {
1428   struct NotifyList *pos;
1429
1430   for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1431     if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1432       break;
1433   if (NULL == pos)
1434   {
1435     GNUNET_break (0);
1436     return;
1437   }
1438   GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1439                                server->connect_notify_list_tail,
1440                                pos);
1441   GNUNET_free (pos);
1442 }
1443
1444
1445 /**
1446  * Destroy the connection that is passed in via @a cls.  Used
1447  * as calling #GNUNET_CONNECTION_destroy from within a function
1448  * that was itself called from within 'process_notify' of
1449  * 'connection.c' is not allowed (see #2329).
1450  *
1451  * @param cls connection to destroy
1452  * @param tc scheduler context (unused)
1453  */
1454 static void
1455 destroy_connection (void *cls,
1456                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1457 {
1458   struct GNUNET_CONNECTION_Handle *connection = cls;
1459
1460   GNUNET_CONNECTION_destroy (connection);
1461 }
1462
1463
1464 /**
1465  * Ask the server to disconnect from the given client.
1466  * This is the same as returning #GNUNET_SYSERR from a message
1467  * handler, except that it allows dropping of a client even
1468  * when not handling a message from that client.
1469  *
1470  * @param client the client to disconnect from
1471  */
1472 void
1473 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1474 {
1475   struct GNUNET_SERVER_Handle *server = client->server;
1476   struct NotifyList *n;
1477
1478   LOG (GNUNET_ERROR_TYPE_DEBUG,
1479        "Client is being disconnected from the server.\n");
1480   if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1481   {
1482     GNUNET_SCHEDULER_cancel (client->restart_task);
1483     client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1484   }
1485   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1486   {
1487     GNUNET_SCHEDULER_cancel (client->warn_task);
1488     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1489   }
1490   if (GNUNET_YES == client->receive_pending)
1491   {
1492     GNUNET_CONNECTION_receive_cancel (client->connection);
1493     client->receive_pending = GNUNET_NO;
1494   }
1495   client->shutdown_now = GNUNET_YES;
1496   client->reference_count++; /* make sure nobody else clean up client... */
1497   if ( (NULL != client->mst) &&
1498        (NULL != server) )
1499   {
1500     GNUNET_CONTAINER_DLL_remove (server->clients_head,
1501                                  server->clients_tail,
1502                                  client);
1503     if (NULL != server->mst_destroy)
1504       server->mst_destroy (server->mst_cls, client->mst);
1505     else
1506       GNUNET_SERVER_mst_destroy (client->mst);
1507     client->mst = NULL;
1508     for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1509       n->callback (n->callback_cls, client);
1510   }
1511   client->reference_count--;
1512   if (client->reference_count > 0)
1513   {
1514     LOG (GNUNET_ERROR_TYPE_DEBUG,
1515          "RC still positive, not destroying everything.\n");
1516     client->server = NULL;
1517     return;
1518   }
1519   if (GNUNET_YES == client->in_process_client_buffer)
1520   {
1521     LOG (GNUNET_ERROR_TYPE_DEBUG,
1522          "Still processing inputs, not destroying everything.\n");
1523     return;
1524   }
1525   if (GNUNET_YES == client->persist)
1526     GNUNET_CONNECTION_persist_ (client->connection);
1527   if (NULL != client->th.cth)
1528     GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1529   (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1530                                    client->connection);
1531   /* need to cancel again, as it might have been re-added
1532      in the meantime (i.e. during callbacks) */
1533   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1534   {
1535     GNUNET_SCHEDULER_cancel (client->warn_task);
1536     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1537   }
1538   if (GNUNET_YES == client->receive_pending)
1539   {
1540     GNUNET_CONNECTION_receive_cancel (client->connection);
1541     client->receive_pending = GNUNET_NO;
1542   }
1543   GNUNET_free (client);
1544   /* we might be in soft-shutdown, test if we're done */
1545   if (NULL != server)
1546     test_monitor_clients (server);
1547 }
1548
1549
1550 /**
1551  * Disable the "CORK" feature for communication with the given client,
1552  * forcing the OS to immediately flush the buffer on transmission
1553  * instead of potentially buffering multiple messages.
1554  *
1555  * @param client handle to the client
1556  * @return GNUNET_OK on success
1557  */
1558 int
1559 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1560 {
1561   return GNUNET_CONNECTION_disable_corking (client->connection);
1562 }
1563
1564
1565 /**
1566  * Wrapper for transmission notification that calls the original
1567  * callback and update the last activity time for our connection.
1568  *
1569  * @param cls the 'struct GNUNET_SERVER_Client'
1570  * @param size number of bytes we can transmit
1571  * @param buf where to copy the message
1572  * @return number of bytes actually transmitted
1573  */
1574 static size_t
1575 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1576 {
1577   struct GNUNET_SERVER_Client *client = cls;
1578   GNUNET_CONNECTION_TransmitReadyNotify callback;
1579
1580   client->th.cth = NULL;
1581   callback = client->th.callback;
1582   client->th.callback = NULL;
1583   client->last_activity = GNUNET_TIME_absolute_get ();
1584   return callback (client->th.callback_cls, size, buf);
1585 }
1586
1587
1588 /**
1589  * Notify us when the server has enough space to transmit
1590  * a message of the given size to the given client.
1591  *
1592  * @param client client to transmit message to
1593  * @param size requested amount of buffer space
1594  * @param timeout after how long should we give up (and call
1595  *        notify with buf NULL and size 0)?
1596  * @param callback function to call when space is available
1597  * @param callback_cls closure for @a callback
1598  * @return non-NULL if the notify callback was queued; can be used
1599  *         to cancel the request using
1600  *         #GNUNET_SERVER_notify_transmit_ready_cancel.
1601  *         NULL if we are already going to notify someone else (busy)
1602  */
1603 struct GNUNET_SERVER_TransmitHandle *
1604 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1605                                      size_t size,
1606                                      struct GNUNET_TIME_Relative timeout,
1607                                      GNUNET_CONNECTION_TransmitReadyNotify
1608                                      callback, void *callback_cls)
1609 {
1610   if (NULL != client->th.callback)
1611     return NULL;
1612   client->th.callback_cls = callback_cls;
1613   client->th.callback = callback;
1614   client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1615                                                             timeout,
1616                                                             &transmit_ready_callback_wrapper,
1617                                                             client);
1618   return &client->th;
1619 }
1620
1621
1622 /**
1623  * Abort transmission request.
1624  *
1625  * @param th request to abort
1626  */
1627 void
1628 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1629 {
1630   GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1631   th->cth = NULL;
1632   th->callback = NULL;
1633 }
1634
1635
1636 /**
1637  * Set the persistent flag on this client, used to setup client connection
1638  * to only be killed when the service it's connected to is actually dead.
1639  *
1640  * @param client the client to set the persistent flag on
1641  */
1642 void
1643 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1644 {
1645   client->persist = GNUNET_YES;
1646 }
1647
1648
1649 /**
1650  * Resume receiving from this client, we are done processing the
1651  * current request.  This function must be called from within each
1652  * GNUNET_SERVER_MessageCallback (or its respective continuations).
1653  *
1654  * @param client client we were processing a message of
1655  * @param success #GNUNET_OK to keep the connection open and
1656  *                          continue to receive
1657  *                #GNUNET_NO to close the connection (normal behavior)
1658  *                #GNUNET_SYSERR to close the connection (signal
1659  *                          serious error)
1660  */
1661 void
1662 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1663                             int success)
1664 {
1665   if (NULL == client)
1666     return;
1667   GNUNET_assert (client->suspended > 0);
1668   client->suspended--;
1669   if (GNUNET_OK != success)
1670   {
1671     LOG (GNUNET_ERROR_TYPE_DEBUG,
1672          "GNUNET_SERVER_receive_done called with failure indication\n");
1673     if ( (client->reference_count > 0) || (client->suspended > 0) )
1674       client->shutdown_now = GNUNET_YES;
1675     else
1676       GNUNET_SERVER_client_disconnect (client);
1677     return;
1678   }
1679   if (client->suspended > 0)
1680   {
1681     LOG (GNUNET_ERROR_TYPE_DEBUG,
1682          "GNUNET_SERVER_receive_done called, but more clients pending\n");
1683     return;
1684   }
1685   if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1686   {
1687     GNUNET_SCHEDULER_cancel (client->warn_task);
1688     client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1689   }
1690   if (GNUNET_YES == client->in_process_client_buffer)
1691   {
1692     LOG (GNUNET_ERROR_TYPE_DEBUG,
1693          "GNUNET_SERVER_receive_done called while still in processing loop\n");
1694     return;
1695   }
1696   if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1697   {
1698     GNUNET_SERVER_client_disconnect (client);
1699     return;
1700   }
1701   LOG (GNUNET_ERROR_TYPE_DEBUG,
1702        "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1703   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1704   client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1705 }
1706
1707
1708 /* end of server.c */