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