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