55eb68d13ca2f58cdc2a584c1b7a810f56517b85
[oweals/gnunet.git] / src / util / client.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2006, 2008, 2009 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/client.c
23  * @brief code for access to services
24  * @author Christian Grothoff
25  *
26  * Generic TCP code for reliable, record-oriented TCP
27  * connections between clients and service providers.
28  */
29
30 #include "platform.h"
31 #include "gnunet_common.h"
32 #include "gnunet_client_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_scheduler_lib.h"
36
37 #define DEBUG_CLIENT GNUNET_NO
38
39 /**
40  * How often do we re-try tranmsitting requests before giving up?
41  * Note that if we succeeded transmitting a request but failed to read
42  * a response, we do NOT re-try.
43  */
44 #define MAX_ATTEMPTS 50
45
46
47 /**
48  * Handle for a transmission request.
49  */
50 struct GNUNET_CLIENT_TransmitHandle
51 {
52   /**
53    * Connection state.
54    */
55   struct GNUNET_CLIENT_Connection *sock;
56
57   /**
58    * Function to call to get the data for transmission.
59    */
60   GNUNET_CONNECTION_TransmitReadyNotify notify;
61
62   /**
63    * Closure for notify.
64    */
65   void *notify_cls;
66
67   /**
68    * Handle to the transmission with the underlying
69    * connection.
70    */
71   struct GNUNET_CONNECTION_TransmitHandle *th;
72
73   /**
74    * If we are re-trying and are delaying to do so,
75    * handle to the scheduled task managing the delay.
76    */
77   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
78
79   /**
80    * Timeout for the operation overall.
81    */
82   struct GNUNET_TIME_Absolute timeout;
83
84   /**
85    * Number of bytes requested.
86    */
87   size_t size;
88
89   /**
90    * Are we allowed to re-try to connect without telling
91    * the user (of this API) about the connection troubles?
92    */
93   int auto_retry;
94
95   /**
96    * Number of attempts left for transmitting the request.  We may
97    * fail the first time (say because the service is not yet up), in
98    * which case (if auto_retry is set) we wait a bit and re-try
99    * (timeout permitting).
100    */
101   unsigned int attempts_left;
102
103 };
104
105
106 /**
107  * Context for processing 
108  * "GNUNET_CLIENT_transmit_and_get_response" requests.
109  */
110 struct TransmitGetResponseContext
111 {
112   /**
113    * Client handle.
114    */
115   struct GNUNET_CLIENT_Connection *sock;
116
117   /**
118    * Message to transmit; do not free, allocated
119    * right after this struct.
120    */
121   const struct GNUNET_MessageHeader *hdr;
122
123   /**
124    * Timeout to use.
125    */
126   struct GNUNET_TIME_Absolute timeout;
127
128   /**
129    * Function to call when done.
130    */
131   GNUNET_CLIENT_MessageHandler rn;
132
133   /**
134    * Closure for "rn".
135    */
136   void *rn_cls;
137 };
138
139 /**
140  * Context for handling the shutdown of a service.
141  */
142 struct ShutdownContext
143 {
144   /**
145    * Scheduler to be used to call continuation
146    */
147   struct GNUNET_SCHEDULER_Handle *sched;
148   /**
149    * Connection to the service that is being shutdown.
150    */
151   struct GNUNET_CLIENT_Connection *sock;
152
153   /**
154    * Time allowed for shutdown to happen.
155    */
156   struct GNUNET_TIME_Absolute timeout;
157
158   /**
159    * Task set up to cancel the shutdown request on timeout.
160    */
161   GNUNET_SCHEDULER_TaskIdentifier cancel_task;
162
163   /**
164    * Task to call once shutdown complete
165    */
166   GNUNET_CLIENT_ShutdownTask cont;
167
168   /**
169    * Closure for shutdown continuation
170    */
171   void *cont_cls;
172
173   /**
174    * We received a confirmation that the service will shut down.
175    */
176   int confirmed;
177
178 };
179
180 /**
181  * Struct to refer to a GNUnet TCP connection.
182  * This is more than just a socket because if the server
183  * drops the connection, the client automatically tries
184  * to reconnect (and for that needs connection information).
185  */
186 struct GNUNET_CLIENT_Connection
187 {
188
189   /**
190    * the socket handle, NULL if not live
191    */
192   struct GNUNET_CONNECTION_Handle *sock;
193
194   /**
195    * Our scheduler.
196    */
197   struct GNUNET_SCHEDULER_Handle *sched;
198
199   /**
200    * Our configuration.
201    */
202   struct GNUNET_CONFIGURATION_Handle *cfg;
203
204   /**
205    * Name of the service we interact with.
206    */
207   char *service_name;
208
209   /**
210    * Context of a transmit_and_get_response operation, NULL
211    * if no such operation is pending.
212    */
213   struct TransmitGetResponseContext *tag;
214
215   /**
216    * Handler for current receiver task.
217    */
218   GNUNET_CLIENT_MessageHandler receiver_handler;
219
220   /**
221    * Closure for receiver_handler.
222    */
223   void *receiver_handler_cls;
224
225   /**
226    * Handle for a pending transmission request, NULL if there is
227    * none pending.
228    */
229   struct GNUNET_CLIENT_TransmitHandle *th;
230
231   /**
232    * Handler for service test completion (NULL unless in service_test)
233    */
234   GNUNET_SCHEDULER_Task test_cb;
235
236   /**
237    * Deadline for calling 'test_cb'.
238    */
239   struct GNUNET_TIME_Absolute test_deadline;
240
241   /**
242    * If we are re-trying and are delaying to do so,
243    * handle to the scheduled task managing the delay.
244    */
245   GNUNET_SCHEDULER_TaskIdentifier receive_task;
246
247   /**
248    * Closure for test_cb (NULL unless in service_test)
249    */
250   void *test_cb_cls;
251
252   /**
253    * Buffer for received message.
254    */
255   char *received_buf;
256
257   /**
258    * Timeout for receiving a response (absolute time).
259    */
260   struct GNUNET_TIME_Absolute receive_timeout;
261
262   /**
263    * Current value for our incremental back-off (for
264    * connect re-tries).
265    */
266   struct GNUNET_TIME_Relative back_off;
267
268   /**
269    * Number of bytes in received_buf that are valid.
270    */
271   size_t received_pos;
272
273   /**
274    * Size of received_buf.
275    */
276   unsigned int received_size;
277
278   /**
279    * Do we have a complete response in received_buf?
280    */
281   int msg_complete;
282
283   /**
284    * Are we currently busy doing receive-processing?
285    * GNUNET_YES if so, GNUNET_NO if not.
286    */
287   int in_receive;
288
289   /**
290    * Are we ignoring shutdown signals?
291    */
292   int ignore_shutdown;
293
294 };
295
296
297 static struct GNUNET_CONNECTION_Handle *
298 do_connect (struct GNUNET_SCHEDULER_Handle *sched,
299             const char *service_name,
300             const struct GNUNET_CONFIGURATION_Handle *cfg)
301 {
302   struct GNUNET_CONNECTION_Handle *sock;
303   char *hostname;
304   unsigned long long port;
305
306   if ((GNUNET_OK !=
307        GNUNET_CONFIGURATION_get_value_number (cfg,
308                                               service_name,
309                                               "PORT",
310                                               &port)) ||
311       (port > 65535) ||
312       (GNUNET_OK !=
313        GNUNET_CONFIGURATION_get_value_string (cfg,
314                                               service_name,
315                                               "HOSTNAME", &hostname)))
316     {
317       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
318                   _
319                   ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
320                   service_name);
321       return NULL;
322     }
323   if (0 == strlen (hostname))
324     {
325       GNUNET_free (hostname);
326       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
327                   _("Need a non-empty hostname for service `%s'.\n"),
328                   service_name);
329       return NULL;
330     }
331   sock = GNUNET_CONNECTION_create_from_connect (sched,
332                                                 cfg,
333                                                 hostname,
334                                                 port,
335                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
336   GNUNET_free (hostname);
337   return sock;
338 }
339
340
341 /**
342  * Get a connection with a service.
343  *
344  * @param sched scheduler to use
345  * @param service_name name of the service
346  * @param cfg configuration to use
347  * @return NULL on error (service unknown to configuration)
348  */
349 struct GNUNET_CLIENT_Connection *
350 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
351                        const char *service_name,
352                        const struct GNUNET_CONFIGURATION_Handle *cfg)
353 {
354   struct GNUNET_CLIENT_Connection *ret;
355   struct GNUNET_CONNECTION_Handle *sock;
356
357   sock = do_connect (sched, service_name, cfg);
358   if (sock == NULL)
359     return NULL;
360   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
361   ret->sock = sock;
362   ret->sched = sched;
363   ret->service_name = GNUNET_strdup (service_name);
364   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
365   ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
366   return ret;
367 }
368
369
370 /**
371  * Configure this connection to ignore shutdown signals.
372  *
373  * @param h client handle
374  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
375  */
376 void
377 GNUNET_CLIENT_ignore_shutdown (struct GNUNET_CLIENT_Connection *h,
378                                int do_ignore)
379 {
380   h->ignore_shutdown = do_ignore;
381   if (h->sock != NULL)
382     GNUNET_CONNECTION_ignore_shutdown (h->sock,
383                                        do_ignore);
384 }
385
386
387 /**
388  * Destroy connection with the service.  This will automatically
389  * cancel any pending "receive" request (however, the handler will
390  * *NOT* be called, not even with a NULL message).  Any pending
391  * transmission request will also be cancelled UNLESS the callback for
392  * the transmission request has already been called, in which case the
393  * transmission 'finish_pending_write' argument determines whether or
394  * not the write is guaranteed to complete before the socket is fully
395  * destroyed (unless, of course, there is an error with the server in
396  * which case the message may still be lost).
397  *
398  * @param finish_pending_write should a transmission already passed to the
399  *          handle be completed?
400  * @param sock handle to the service connection
401  */
402 void
403 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
404                           int finish_pending_write)
405 {
406   GNUNET_assert (sock->sock != NULL);
407   if (sock->in_receive == GNUNET_YES)
408     {
409       GNUNET_CONNECTION_receive_cancel (sock->sock);
410       sock->in_receive = GNUNET_NO;
411     }
412   GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
413   sock->sock = NULL;
414   if (sock->tag != NULL)
415     {
416       GNUNET_free (sock->tag);
417       sock->tag = NULL;
418     }
419   sock->receiver_handler = NULL;
420   if (sock->th != NULL)
421     GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
422   if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
423     {
424       GNUNET_SCHEDULER_cancel (sock->sched, sock->receive_task);
425       sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
426     }
427   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
428   GNUNET_free (sock->service_name);
429   GNUNET_CONFIGURATION_destroy (sock->cfg);
430   GNUNET_free (sock);
431 }
432
433
434 /**
435  * Check if message is complete
436  */
437 static void
438 check_complete (struct GNUNET_CLIENT_Connection *conn)
439 {
440   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
441       (conn->received_pos >=
442        ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
443               size)))
444     conn->msg_complete = GNUNET_YES;
445 }
446
447
448 /**
449  * Callback function for data received from the network.  Note that
450  * both "available" and "errCode" would be 0 if the read simply timed out.
451  *
452  * @param cls closure
453  * @param buf pointer to received data
454  * @param available number of bytes availabe in "buf",
455  *        possibly 0 (on errors)
456  * @param addr address of the sender
457  * @param addrlen size of addr
458  * @param errCode value of errno (on errors receiving)
459  */
460 static void
461 receive_helper (void *cls,
462                 const void *buf,
463                 size_t available,
464                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
465 {
466   struct GNUNET_CLIENT_Connection *conn = cls;
467   struct GNUNET_TIME_Relative remaining;
468   GNUNET_CLIENT_MessageHandler receive_handler;
469   void *receive_handler_cls;
470
471   GNUNET_assert (conn->msg_complete == GNUNET_NO);
472   conn->in_receive = GNUNET_NO;
473   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
474     {
475       /* signal timeout! */
476       if (NULL != (receive_handler = conn->receiver_handler))
477         {
478           receive_handler_cls = conn->receiver_handler_cls;
479           conn->receiver_handler = NULL;
480           receive_handler (receive_handler_cls, NULL);
481         }
482       return;
483     }
484
485   /* FIXME: optimize for common fast case where buf contains the
486      entire message and we need no copying... */
487
488
489   /* slow path: append to array */
490   if (conn->received_size < conn->received_pos + available)
491     GNUNET_array_grow (conn->received_buf,
492                        conn->received_size, conn->received_pos + available);
493   memcpy (&conn->received_buf[conn->received_pos], buf, available);
494   conn->received_pos += available;
495   check_complete (conn);
496   /* check for timeout */
497   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
498   if (remaining.value == 0)
499     {
500       /* signal timeout! */
501       conn->receiver_handler (conn->receiver_handler_cls, NULL);
502       return;
503     }
504   /* back to receive -- either for more data or to call callback! */
505   GNUNET_CLIENT_receive (conn,
506                          conn->receiver_handler,
507                          conn->receiver_handler_cls, remaining);
508 }
509
510
511 /**
512  * Continuation to call the receive callback.
513  *
514  * @param cls  our handle to the client connection
515  * @param tc scheduler context
516  */
517 static void
518 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
519 {
520   struct GNUNET_CLIENT_Connection *sock = cls;
521   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
522   const struct GNUNET_MessageHeader *cmsg =
523     (const struct GNUNET_MessageHeader *) sock->received_buf;
524   void *handler_cls = sock->receiver_handler_cls;
525   uint16_t msize = ntohs (cmsg->size);
526   char mbuf[msize];
527   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
528
529   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
530   GNUNET_assert (GNUNET_YES == sock->msg_complete);
531   GNUNET_assert (sock->received_pos >= msize);
532   memcpy (msg, cmsg, msize);
533   memmove (sock->received_buf,
534            &sock->received_buf[msize], sock->received_pos - msize);
535   sock->received_pos -= msize;
536   sock->msg_complete = GNUNET_NO;
537   sock->receiver_handler = NULL;
538   check_complete (sock);
539   if (handler != NULL)
540     handler (handler_cls, msg);
541 }
542
543
544 /**
545  * Read from the service.
546  *
547  * @param sock the service
548  * @param handler function to call with the message
549  * @param handler_cls closure for handler
550  * @param timeout how long to wait until timing out
551  */
552 void
553 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
554                        GNUNET_CLIENT_MessageHandler handler,
555                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
556 {
557   if (sock->sock == NULL)
558     {
559       /* already disconnected, fail instantly! */
560       GNUNET_break (0);         /* this should not happen in well-written code! */
561       handler (handler_cls, NULL);
562       return;
563     }
564   sock->receiver_handler = handler;
565   sock->receiver_handler_cls = handler_cls;
566   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
567   if (GNUNET_YES == sock->msg_complete)
568     {
569       sock->receive_task = GNUNET_SCHEDULER_add_after (sock->sched,
570                                                        GNUNET_SCHEDULER_NO_TASK,
571                                                        &receive_task, sock);
572     }
573   else
574     {
575       sock->in_receive = GNUNET_YES;
576       GNUNET_CONNECTION_receive (sock->sock,
577                                  GNUNET_SERVER_MAX_MESSAGE_SIZE,
578                                  timeout, &receive_helper, sock);
579     }
580 }
581
582
583 /**
584  * Handler receiving response to service shutdown requests.
585  * First call with NULL: service misbehaving, or something.
586  * First call with GNUNET_MESSAGE_TYPE_SHUTDOWN_ACK:
587  *   - service will shutdown
588  * First call with GNUNET_MESSAGE_TYPE_SHUTDOWN_REFUSE:
589  *   - service will not be stopped!
590  *
591  * Second call with NULL:
592  *   - service has now really shut down.
593  *
594  * @param cls closure
595  * @param msg NULL, indicating socket closure.
596  */
597 static void
598 service_shutdown_handler (void *cls, const struct GNUNET_MessageHeader *msg)
599 {
600   struct ShutdownContext *shutdown_ctx = cls;
601
602   if ((msg == NULL) && (shutdown_ctx->confirmed != GNUNET_YES))   
603     {
604       /* Means the other side closed the connection and never confirmed a shutdown */
605       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
606                   "Service handle shutdown before ACK!\n");
607       if (shutdown_ctx->cont != NULL)
608         shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_SYSERR);      
609       GNUNET_SCHEDULER_cancel(shutdown_ctx->sched, shutdown_ctx->cancel_task);
610       GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
611       GNUNET_free(shutdown_ctx);
612     }
613   else if ((msg == NULL) && (shutdown_ctx->confirmed == GNUNET_YES))
614     {
615       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
616                  "Service shutdown complete.\n");
617       if (shutdown_ctx->cont != NULL)
618         shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_NO);
619
620       GNUNET_SCHEDULER_cancel(shutdown_ctx->sched, shutdown_ctx->cancel_task);
621       GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
622       GNUNET_free(shutdown_ctx);
623     }
624   else
625     {
626       GNUNET_assert(ntohs(msg->size) == sizeof(struct GNUNET_MessageHeader));
627
628       switch (ntohs(msg->type))
629       {
630       case GNUNET_MESSAGE_TYPE_SHUTDOWN_ACK:
631         GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
632                    "Received confirmation for service shutdown.\n");
633         shutdown_ctx->confirmed = GNUNET_YES;
634         GNUNET_CLIENT_receive (shutdown_ctx->sock, 
635                                &service_shutdown_handler, 
636                                shutdown_ctx, 
637                                GNUNET_TIME_UNIT_FOREVER_REL);
638         break;
639       case GNUNET_MESSAGE_TYPE_SHUTDOWN_REFUSE:
640       default: /* Fall through */
641         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
642                    "Service shutdown refused!\n");
643         if (shutdown_ctx->cont != NULL)
644           shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_YES);
645
646         GNUNET_SCHEDULER_cancel(shutdown_ctx->sched, shutdown_ctx->cancel_task);
647         GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
648         GNUNET_free(shutdown_ctx);
649         break;
650       }
651     }
652 }
653
654 /**
655  * Shutting down took too long, cancel receive and return error.
656  *
657  * @param cls closure
658  * @param tc context information (why was this task triggered now)
659  */
660 void service_shutdown_cancel (void *cls,
661                               const struct GNUNET_SCHEDULER_TaskContext * tc)
662 {
663   struct ShutdownContext *shutdown_ctx = cls;
664   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
665   shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_SYSERR);
666   GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
667   GNUNET_free(shutdown_ctx);
668 }
669
670
671 /**
672  * If possible, write a shutdown message to the target
673  * buffer and destroy the client connection.
674  *
675  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
676  * @param size number of bytes available in buf
677  * @param buf NULL on error, otherwise target buffer
678  * @return number of bytes written to buf
679  */
680 static size_t
681 write_shutdown (void *cls, size_t size, void *buf)
682 {
683   struct GNUNET_MessageHeader *msg;
684   struct ShutdownContext *shutdown_ctx = cls;
685
686   if (size < sizeof (struct GNUNET_MessageHeader))
687     {
688       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
689                   _("Failed to transmit shutdown request to client.\n"));
690       shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_SYSERR);
691       GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
692       GNUNET_free(shutdown_ctx);
693       return 0;                 /* client disconnected */
694     }
695
696   GNUNET_CLIENT_receive (shutdown_ctx->sock,
697                          &service_shutdown_handler, shutdown_ctx, 
698                          GNUNET_TIME_UNIT_FOREVER_REL);
699   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (shutdown_ctx->sched, 
700                                                             GNUNET_TIME_absolute_get_remaining(shutdown_ctx->timeout), 
701                                                             &service_shutdown_cancel, 
702                                                             shutdown_ctx);
703   msg = (struct GNUNET_MessageHeader *) buf;
704   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
705   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
706   return sizeof (struct GNUNET_MessageHeader);
707 }
708
709
710 /**
711  * Request that the service should shutdown.
712  * Afterwards, the connection will automatically be
713  * disconnected.  Hence the "sock" should not
714  * be used by the caller after this call
715  * (calling this function frees "sock" after a while).
716  *
717  * @param sched the scheduler to use for calling shutdown continuation
718  * @param sock the socket connected to the service
719  * @param timeout how long to wait before giving up on transmission
720  * @param cont continuation to call once the service is really down
721  * @param cont_cls closure for continuation
722  *
723  */
724 void
725 GNUNET_CLIENT_service_shutdown (struct GNUNET_SCHEDULER_Handle *sched,
726                                 struct GNUNET_CLIENT_Connection *sock,
727                                 struct GNUNET_TIME_Relative timeout,
728                                 GNUNET_CLIENT_ShutdownTask cont,
729                                 void *cont_cls)
730 {
731   struct ShutdownContext *shutdown_ctx;
732   shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
733   shutdown_ctx->sched = sched;
734   shutdown_ctx->cont = cont;
735   shutdown_ctx->cont_cls = cont_cls;
736   shutdown_ctx->sock = sock;
737   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute(timeout);
738   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
739                                            sizeof (struct
740                                                    GNUNET_MessageHeader),
741                                            timeout,
742                                            &write_shutdown, shutdown_ctx);
743 }
744
745
746 /**
747  * Report service unavailable.
748  */
749 static void
750 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
751                     GNUNET_SCHEDULER_Task task, void *task_cls)
752 {
753   GNUNET_SCHEDULER_add_continuation (s,
754                                      task,
755                                      task_cls,
756                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
757 }
758
759
760 /**
761  * Receive confirmation from test, service is up.
762  *
763  * @param cls closure
764  * @param msg message received, NULL on timeout or fatal error
765  */
766 static void
767 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
768 {
769   struct GNUNET_CLIENT_Connection *conn = cls;
770   /* We may want to consider looking at the reply in more
771      detail in the future, for example, is this the
772      correct service? FIXME! */
773   if (msg != NULL)
774     {
775 #if DEBUG_CLIENT
776       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
777                   "Received confirmation that service is running.\n");
778 #endif
779       GNUNET_SCHEDULER_add_continuation (conn->sched,
780                                          conn->test_cb,
781                                          conn->test_cb_cls,
782                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
783     }
784   else
785     {
786       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
787     }
788   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
789 }
790
791
792 static size_t
793 write_test (void *cls, size_t size, void *buf)
794 {
795   struct GNUNET_CLIENT_Connection *conn = cls;
796   struct GNUNET_MessageHeader *msg;
797
798   if (size < sizeof (struct GNUNET_MessageHeader))
799     {
800 #if DEBUG_CLIENT
801       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
802                   _("Failure to transmit TEST request.\n"));
803 #endif
804       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
805       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
806       return 0;                 /* client disconnected */
807     }
808 #if DEBUG_CLIENT
809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810               "Transmitting `%s' request.\n", "TEST");
811 #endif
812   msg = (struct GNUNET_MessageHeader *) buf;
813   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
814   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
815   GNUNET_CLIENT_receive (conn, 
816                          &confirm_handler, 
817                          conn, 
818                          GNUNET_TIME_absolute_get_remaining (conn->test_deadline));
819   return sizeof (struct GNUNET_MessageHeader);
820 }
821
822
823 /**
824  * Wait until the service is running.
825  *
826  * @param sched scheduler to use
827  * @param service name of the service to wait for
828  * @param cfg configuration to use
829  * @param timeout how long to wait at most in ms
830  * @param task task to run if service is running
831  *        (reason will be "PREREQ_DONE" (service running)
832  *         or "TIMEOUT" (service not known to be running))
833  * @param task_cls closure for task
834  */
835 void
836 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
837                             const char *service,
838                             const struct GNUNET_CONFIGURATION_Handle *cfg,
839                             struct GNUNET_TIME_Relative timeout,
840                             GNUNET_SCHEDULER_Task task, void *task_cls)
841 {
842   struct GNUNET_CLIENT_Connection *conn;
843
844 #if DEBUG_CLIENT
845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846               "Testing if service `%s' is running.\n", service);
847 #endif
848   conn = GNUNET_CLIENT_connect (sched, service, cfg);
849   if (conn == NULL)
850     {
851       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
852                   _
853                   ("Could not connect to service `%s', must not be running.\n"),
854                   service);
855       service_test_error (sched, task, task_cls);
856       return;
857     }
858   conn->test_cb = task;
859   conn->test_cb_cls = task_cls;
860   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
861
862   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
863                                                    sizeof (struct GNUNET_MessageHeader),
864                                                    timeout,
865                                                    GNUNET_YES,
866                                                    &write_test, conn))  
867     {
868       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
869                   _("Failure to transmit request to service `%s'\n"),
870                   service);
871       service_test_error (sched, task, task_cls);
872       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
873       return;
874     }
875 }
876
877
878 /**
879  * Connection notifies us about failure or success of
880  * a transmission request.  Either pass it on to our
881  * user or, if possible, retry.
882  *
883  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
884  * @param size number of bytes available for transmission
885  * @param buf where to write them
886  * @return number of bytes written to buf
887  */
888 static size_t client_notify (void *cls, size_t size, void *buf);
889
890
891 /**
892  * This task is run if we should re-try connection to the
893  * service after a while.
894  *
895  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
896  * @param tc unused
897  */
898 static void
899 client_delayed_retry (void *cls,
900                       const struct GNUNET_SCHEDULER_TaskContext *tc)
901 {
902   struct GNUNET_CLIENT_TransmitHandle *th = cls;
903
904   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
905   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
906     {
907 #if DEBUG_CLIENT
908       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
909                   "Transmission failed due to shutdown.\n");
910 #endif
911       th->sock->th = NULL;
912       th->notify (th->notify_cls, 0, NULL);
913       GNUNET_free (th);
914       return;
915     }
916   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
917                                                     th->size,
918                                                     GNUNET_TIME_absolute_get_remaining
919                                                     (th->timeout),
920                                                     &client_notify, th);
921   if (th->th == NULL)
922     {
923       GNUNET_break (0);
924       th->notify (th->notify_cls, 0, NULL);
925       GNUNET_free (th);
926       return;
927     }
928 }
929
930
931 /**
932  * Connection notifies us about failure or success of a transmission
933  * request.  Either pass it on to our user or, if possible, retry.
934  *
935  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
936  * @param size number of bytes available for transmission
937  * @param buf where to write them
938  * @return number of bytes written to buf
939  */
940 static size_t
941 client_notify (void *cls, size_t size, void *buf)
942 {
943   struct GNUNET_CLIENT_TransmitHandle *th = cls;
944   size_t ret;
945   struct GNUNET_TIME_Relative delay;
946
947   th->th = NULL;
948   th->sock->th = NULL;
949   if (buf == NULL)
950     {
951       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
952       delay.value /= 2;
953       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason (th->sock->sched))) ||
954            (GNUNET_YES != th->auto_retry) ||
955            (0 == --th->attempts_left) || 
956            (delay.value < 1) )
957         {
958 #if DEBUG_CLIENT
959           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960                       "Transmission failed %u times, giving up.\n",
961                       MAX_ATTEMPTS - th->attempts_left);
962 #endif
963           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
964           GNUNET_free (th);
965           return 0;
966         }
967       /* auto-retry */
968       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
969       th->sock->sock = do_connect (th->sock->sched,
970                                    th->sock->service_name, th->sock->cfg);
971       GNUNET_assert (NULL != th->sock->sock);
972       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
973                                          th->sock->ignore_shutdown);
974       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
975       th->sock->back_off 
976           = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
977                                     GNUNET_TIME_UNIT_SECONDS);
978 #if DEBUG_CLIENT
979       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980                   "Transmission failed %u times, trying again in %llums.\n",
981                   MAX_ATTEMPTS - th->attempts_left,
982                   (unsigned long long) delay.value);
983 #endif
984       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
985                                                          delay,
986                                                          &client_delayed_retry,
987                                                          th);
988       th->sock->th = th;
989       return 0;
990     }
991   GNUNET_assert (size >= th->size);
992   ret = th->notify (th->notify_cls, size, buf);
993   GNUNET_free (th);
994   return ret;
995 }
996
997
998 /**
999  * Ask the client to call us once the specified number of bytes
1000  * are free in the transmission buffer.  May call the notify
1001  * method immediately if enough space is available.
1002  *
1003  * @param sock connection to the service
1004  * @param size number of bytes to send
1005  * @param timeout after how long should we give up (and call
1006  *        notify with buf NULL and size 0)?
1007  * @param auto_retry if the connection to the service dies, should we
1008  *        automatically re-connect and retry (within the timeout period)
1009  *        or should we immediately fail in this case?  Pass GNUNET_YES
1010  *        if the caller does not care about temporary connection errors,
1011  *        for example because the protocol is stateless
1012  * @param notify function to call
1013  * @param notify_cls closure for notify
1014  * @return NULL if our buffer will never hold size bytes,
1015  *         a handle if the notify callback was queued (can be used to cancel)
1016  */
1017 struct GNUNET_CLIENT_TransmitHandle *
1018 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1019                                      size_t size,
1020                                      struct GNUNET_TIME_Relative timeout,
1021                                      int auto_retry,
1022                                      GNUNET_CONNECTION_TransmitReadyNotify
1023                                      notify, void *notify_cls)
1024 {
1025   struct GNUNET_CLIENT_TransmitHandle *th;
1026
1027   if (NULL != sock->th)
1028     return NULL;
1029   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1030   th->sock = sock;
1031   th->size = size;
1032   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1033   th->auto_retry = auto_retry;
1034   th->notify = notify;
1035   th->notify_cls = notify_cls;
1036   th->attempts_left = MAX_ATTEMPTS;
1037   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
1038                                                     size,
1039                                                     timeout,
1040                                                     &client_notify, th);
1041   if (NULL == th->th)
1042     {
1043       GNUNET_break (0);
1044       GNUNET_free (th);
1045       return NULL;
1046     }
1047   sock->th = th;
1048   return th;
1049 }
1050
1051
1052 /**
1053  * Cancel a request for notification.
1054  * 
1055  * @param th handle from the original request.
1056  */
1057 void
1058 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
1059                                             GNUNET_CLIENT_TransmitHandle *th)
1060 {
1061   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1062     {
1063       GNUNET_break (NULL == th->th);
1064       GNUNET_SCHEDULER_cancel (th->sock->sched, th->reconnect_task);
1065       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1066     }
1067   else
1068     {
1069       GNUNET_break (NULL != th->th);
1070       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1071     }
1072   th->sock->th = NULL;
1073   GNUNET_free (th);
1074 }
1075
1076
1077 /**
1078  * Function called to notify a client about the socket
1079  * begin ready to queue the message.  "buf" will be
1080  * NULL and "size" zero if the socket was closed for
1081  * writing in the meantime.
1082  *
1083  * @param cls closure of type "struct TransmitGetResponseContext*"
1084  * @param size number of bytes available in buf
1085  * @param buf where the callee should write the message
1086  * @return number of bytes written to buf
1087  */
1088 static size_t
1089 transmit_for_response (void *cls, size_t size, void *buf)
1090 {
1091   struct TransmitGetResponseContext *tc = cls;
1092   uint16_t msize;
1093
1094   tc->sock->tag = NULL;
1095   msize = ntohs (tc->hdr->size);
1096   if (NULL == buf)
1097     {
1098 #if DEBUG_CLIENT
1099       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100                   _("Could not submit request, not expecting to receive a response.\n"));
1101 #endif
1102       tc->rn (tc->rn_cls, NULL);
1103       GNUNET_free (tc);
1104       return 0;
1105     }
1106   GNUNET_assert (size >= msize);
1107   memcpy (buf, tc->hdr, msize);
1108   GNUNET_CLIENT_receive (tc->sock,
1109                          tc->rn,
1110                          tc->rn_cls,
1111                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1112   GNUNET_free (tc);
1113   return msize;
1114 }
1115
1116
1117 /**
1118  * Convenience API that combines sending a request
1119  * to the service and waiting for a response.
1120  * If either operation times out, the callback
1121  * will be called with a "NULL" response (in which
1122  * case the connection should probably be destroyed).
1123  *
1124  * @param sock connection to use
1125  * @param hdr message to transmit
1126  * @param timeout when to give up (for both transmission
1127  *         and for waiting for a response)
1128  * @param auto_retry if the connection to the service dies, should we
1129  *        automatically re-connect and retry (within the timeout period)
1130  *        or should we immediately fail in this case?  Pass GNUNET_YES
1131  *        if the caller does not care about temporary connection errors,
1132  *        for example because the protocol is stateless
1133  * @param rn function to call with the response
1134  * @param rn_cls closure for rn 
1135  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1136  *         is already pending
1137  */
1138 int
1139 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
1140                                          *sock,
1141                                          const struct GNUNET_MessageHeader
1142                                          *hdr,
1143                                          struct GNUNET_TIME_Relative timeout,
1144                                          int auto_retry,
1145                                          GNUNET_CLIENT_MessageHandler rn,
1146                                          void *rn_cls)
1147 {
1148   struct TransmitGetResponseContext *tc;
1149   uint16_t msize;
1150
1151   if (NULL != sock->th)
1152     return GNUNET_SYSERR;
1153   GNUNET_assert (sock->tag == NULL);
1154   msize = ntohs (hdr->size);
1155   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1156   tc->sock = sock;
1157   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1158   memcpy (&tc[1], hdr, msize);
1159   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1160   tc->rn = rn;
1161   tc->rn_cls = rn_cls;
1162   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
1163                                                    msize,
1164                                                    timeout,
1165                                                    auto_retry,
1166                                                    &transmit_for_response,
1167                                                    tc))
1168     {
1169       GNUNET_break (0);
1170       GNUNET_free (tc);
1171       return GNUNET_SYSERR;
1172     }
1173   sock->tag = tc;
1174   return GNUNET_OK;
1175 }
1176
1177
1178
1179 /*  end of client.c */