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