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