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