588957d85a9b230ea8d8c6def5c029d6efbc624f
[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, "Service shutdown complete.\n");
616       if (shutdown_ctx->cont != NULL)
617         shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_NO);
618
619       GNUNET_SCHEDULER_cancel(shutdown_ctx->sched, shutdown_ctx->cancel_task);
620       GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
621       GNUNET_free(shutdown_ctx);
622     }
623   else
624     {
625       GNUNET_assert(ntohs(msg->size) == sizeof(struct GNUNET_MessageHeader));
626
627       switch (ntohs(msg->type))
628       {
629       case GNUNET_MESSAGE_TYPE_SHUTDOWN_ACK:
630         GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
631                    "Received confirmation for service shutdown.\n");
632         shutdown_ctx->confirmed = GNUNET_YES;
633         GNUNET_CLIENT_receive (shutdown_ctx->sock, 
634                                &service_shutdown_handler, 
635                                shutdown_ctx, 
636                                GNUNET_TIME_UNIT_FOREVER_REL);
637         break;
638       case GNUNET_MESSAGE_TYPE_SHUTDOWN_REFUSE:
639       default: /* Fall through */
640         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
641                    "Service shutdown refused!\n");
642         if (shutdown_ctx->cont != NULL)
643           shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_YES);
644
645         GNUNET_SCHEDULER_cancel(shutdown_ctx->sched, shutdown_ctx->cancel_task);
646         GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
647         GNUNET_free(shutdown_ctx);
648         break;
649       }
650     }
651 }
652
653 /**
654  * Shutting down took too long, cancel receive and return error.
655  *
656  * @param cls closure
657  * @param tc context information (why was this task triggered now)
658  */
659 void service_shutdown_cancel (void *cls,
660                               const struct GNUNET_SCHEDULER_TaskContext * tc)
661 {
662   struct ShutdownContext *shutdown_ctx = cls;
663   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "service_shutdown_cancel called!\n");
664   shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_SYSERR);
665   GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
666   GNUNET_free(shutdown_ctx);
667 }
668
669
670 /**
671  * If possible, write a shutdown message to the target
672  * buffer and destroy the client connection.
673  *
674  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
675  * @param size number of bytes available in buf
676  * @param buf NULL on error, otherwise target buffer
677  * @return number of bytes written to buf
678  */
679 static size_t
680 write_shutdown (void *cls, size_t size, void *buf)
681 {
682   struct GNUNET_MessageHeader *msg;
683   struct ShutdownContext *shutdown_ctx = cls;
684
685   if (size < sizeof (struct GNUNET_MessageHeader))
686     {
687       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
688                   _("Failed to transmit shutdown request to client.\n"));
689       shutdown_ctx->cont(shutdown_ctx->cont_cls, GNUNET_SYSERR);
690       GNUNET_CLIENT_disconnect (shutdown_ctx->sock, GNUNET_NO);
691       GNUNET_free(shutdown_ctx);
692       return 0;                 /* client disconnected */
693     }
694
695   GNUNET_CLIENT_receive (shutdown_ctx->sock,
696                          &service_shutdown_handler, shutdown_ctx, 
697                          GNUNET_TIME_UNIT_FOREVER_REL);
698   shutdown_ctx->cancel_task = GNUNET_SCHEDULER_add_delayed (shutdown_ctx->sched, 
699                                                             GNUNET_TIME_absolute_get_remaining(shutdown_ctx->timeout), 
700                                                             &service_shutdown_cancel, 
701                                                             shutdown_ctx);
702   msg = (struct GNUNET_MessageHeader *) buf;
703   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
704   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
705   return sizeof (struct GNUNET_MessageHeader);
706 }
707
708
709 /**
710  * Request that the service should shutdown.
711  * Afterwards, the connection will automatically be
712  * disconnected.  Hence the "sock" should not
713  * be used by the caller after this call
714  * (calling this function frees "sock" after a while).
715  *
716  * @param sched the scheduler to use for calling shutdown continuation
717  * @param sock the socket connected to the service
718  * @param timeout how long to wait before giving up on transmission
719  * @param cont continuation to call once the service is really down
720  * @param cont_cls closure for continuation
721  *
722  */
723 void
724 GNUNET_CLIENT_service_shutdown (struct GNUNET_SCHEDULER_Handle *sched,
725                                 struct GNUNET_CLIENT_Connection *sock,
726                                 struct GNUNET_TIME_Relative timeout,
727                                 GNUNET_CLIENT_ShutdownTask cont,
728                                 void *cont_cls)
729 {
730   struct ShutdownContext *shutdown_ctx;
731   shutdown_ctx = GNUNET_malloc(sizeof(struct ShutdownContext));
732   shutdown_ctx->sched = sched;
733   shutdown_ctx->cont = cont;
734   shutdown_ctx->cont_cls = cont_cls;
735   shutdown_ctx->sock = sock;
736   shutdown_ctx->timeout = GNUNET_TIME_relative_to_absolute(timeout);
737   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
738                                            sizeof (struct
739                                                    GNUNET_MessageHeader),
740                                            timeout,
741                                            &write_shutdown, shutdown_ctx);
742 }
743
744
745 /**
746  * Report service unavailable.
747  */
748 static void
749 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
750                     GNUNET_SCHEDULER_Task task, void *task_cls)
751 {
752   GNUNET_SCHEDULER_add_continuation (s,
753                                      task,
754                                      task_cls,
755                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
756 }
757
758
759 /**
760  * Receive confirmation from test, service is up.
761  *
762  * @param cls closure
763  * @param msg message received, NULL on timeout or fatal error
764  */
765 static void
766 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
767 {
768   struct GNUNET_CLIENT_Connection *conn = cls;
769   /* We may want to consider looking at the reply in more
770      detail in the future, for example, is this the
771      correct service? FIXME! */
772   if (msg != NULL)
773     {
774 #if DEBUG_CLIENT
775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
776                   "Received confirmation that service is running.\n");
777 #endif
778       GNUNET_SCHEDULER_add_continuation (conn->sched,
779                                          conn->test_cb,
780                                          conn->test_cb_cls,
781                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
782     }
783   else
784     {
785       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
786     }
787   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
788 }
789
790
791 static size_t
792 write_test (void *cls, size_t size, void *buf)
793 {
794   struct GNUNET_CLIENT_Connection *conn = cls;
795   struct GNUNET_MessageHeader *msg;
796
797   if (size < sizeof (struct GNUNET_MessageHeader))
798     {
799 #if DEBUG_CLIENT
800       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801                   _("Failure to transmit TEST request.\n"));
802 #endif
803       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
804       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
805       return 0;                 /* client disconnected */
806     }
807 #if DEBUG_CLIENT
808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
809               "Transmitting `%s' request.\n", "TEST");
810 #endif
811   msg = (struct GNUNET_MessageHeader *) buf;
812   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
813   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
814   GNUNET_CLIENT_receive (conn, 
815                          &confirm_handler, 
816                          conn, 
817                          GNUNET_TIME_absolute_get_remaining (conn->test_deadline));
818   return sizeof (struct GNUNET_MessageHeader);
819 }
820
821
822 /**
823  * Wait until the service is running.
824  *
825  * @param sched scheduler to use
826  * @param service name of the service to wait for
827  * @param cfg configuration to use
828  * @param timeout how long to wait at most in ms
829  * @param task task to run if service is running
830  *        (reason will be "PREREQ_DONE" (service running)
831  *         or "TIMEOUT" (service not known to be running))
832  * @param task_cls closure for task
833  */
834 void
835 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
836                             const char *service,
837                             const struct GNUNET_CONFIGURATION_Handle *cfg,
838                             struct GNUNET_TIME_Relative timeout,
839                             GNUNET_SCHEDULER_Task task, void *task_cls)
840 {
841   struct GNUNET_CLIENT_Connection *conn;
842
843 #if DEBUG_CLIENT
844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
845               "Testing if service `%s' is running.\n", service);
846 #endif
847   conn = GNUNET_CLIENT_connect (sched, service, cfg);
848   if (conn == NULL)
849     {
850       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
851                   _
852                   ("Could not connect to service `%s', must not be running.\n"),
853                   service);
854       service_test_error (sched, task, task_cls);
855       return;
856     }
857   conn->test_cb = task;
858   conn->test_cb_cls = task_cls;
859   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
860
861   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
862                                                    sizeof (struct GNUNET_MessageHeader),
863                                                    timeout,
864                                                    GNUNET_YES,
865                                                    &write_test, conn))  
866     {
867       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
868                   _("Failure to transmit request to service `%s'\n"),
869                   service);
870       service_test_error (sched, task, task_cls);
871       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
872       return;
873     }
874 }
875
876
877 /**
878  * Connection notifies us about failure or success of
879  * a transmission request.  Either pass it on to our
880  * user or, if possible, retry.
881  *
882  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
883  * @param size number of bytes available for transmission
884  * @param buf where to write them
885  * @return number of bytes written to buf
886  */
887 static size_t client_notify (void *cls, size_t size, void *buf);
888
889
890 /**
891  * This task is run if we should re-try connection to the
892  * service after a while.
893  *
894  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
895  * @param tc unused
896  */
897 static void
898 client_delayed_retry (void *cls,
899                       const struct GNUNET_SCHEDULER_TaskContext *tc)
900 {
901   struct GNUNET_CLIENT_TransmitHandle *th = cls;
902
903   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
904   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
905     {
906 #if DEBUG_CLIENT
907       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
908                   "Transmission failed due to shutdown.\n");
909 #endif
910       th->sock->th = NULL;
911       th->notify (th->notify_cls, 0, NULL);
912       GNUNET_free (th);
913       return;
914     }
915   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
916                                                     th->size,
917                                                     GNUNET_TIME_absolute_get_remaining
918                                                     (th->timeout),
919                                                     &client_notify, th);
920   if (th->th == NULL)
921     {
922       GNUNET_break (0);
923       th->notify (th->notify_cls, 0, NULL);
924       GNUNET_free (th);
925       return;
926     }
927 }
928
929
930 /**
931  * Connection notifies us about failure or success of a transmission
932  * request.  Either pass it on to our user or, if possible, retry.
933  *
934  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
935  * @param size number of bytes available for transmission
936  * @param buf where to write them
937  * @return number of bytes written to buf
938  */
939 static size_t
940 client_notify (void *cls, size_t size, void *buf)
941 {
942   struct GNUNET_CLIENT_TransmitHandle *th = cls;
943   size_t ret;
944   struct GNUNET_TIME_Relative delay;
945
946   th->th = NULL;
947   th->sock->th = NULL;
948   if (buf == NULL)
949     {
950       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
951       delay.value /= 2;
952       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason (th->sock->sched))) ||
953            (GNUNET_YES != th->auto_retry) ||
954            (0 == --th->attempts_left) || 
955            (delay.value < 1) )
956         {
957 #if DEBUG_CLIENT
958           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959                       "Transmission failed %u times, giving up.\n",
960                       MAX_ATTEMPTS - th->attempts_left);
961 #endif
962           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
963           GNUNET_free (th);
964           return 0;
965         }
966       /* auto-retry */
967       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
968       th->sock->sock = do_connect (th->sock->sched,
969                                    th->sock->service_name, th->sock->cfg);
970       GNUNET_assert (NULL != th->sock->sock);
971       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
972                                          th->sock->ignore_shutdown);
973       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
974       th->sock->back_off 
975           = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
976                                     GNUNET_TIME_UNIT_SECONDS);
977 #if DEBUG_CLIENT
978       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979                   "Transmission failed %u times, trying again in %llums.\n",
980                   MAX_ATTEMPTS - th->attempts_left,
981                   (unsigned long long) delay.value);
982 #endif
983       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
984                                                          delay,
985                                                          &client_delayed_retry,
986                                                          th);
987       th->sock->th = th;
988       return 0;
989     }
990   GNUNET_assert (size >= th->size);
991   ret = th->notify (th->notify_cls, size, buf);
992   GNUNET_free (th);
993   return ret;
994 }
995
996
997 /**
998  * Ask the client to call us once the specified number of bytes
999  * are free in the transmission buffer.  May call the notify
1000  * method immediately if enough space is available.
1001  *
1002  * @param sock connection to the service
1003  * @param size number of bytes to send
1004  * @param timeout after how long should we give up (and call
1005  *        notify with buf NULL and size 0)?
1006  * @param auto_retry if the connection to the service dies, should we
1007  *        automatically re-connect and retry (within the timeout period)
1008  *        or should we immediately fail in this case?  Pass GNUNET_YES
1009  *        if the caller does not care about temporary connection errors,
1010  *        for example because the protocol is stateless
1011  * @param notify function to call
1012  * @param notify_cls closure for notify
1013  * @return NULL if our buffer will never hold size bytes,
1014  *         a handle if the notify callback was queued (can be used to cancel)
1015  */
1016 struct GNUNET_CLIENT_TransmitHandle *
1017 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1018                                      size_t size,
1019                                      struct GNUNET_TIME_Relative timeout,
1020                                      int auto_retry,
1021                                      GNUNET_CONNECTION_TransmitReadyNotify
1022                                      notify, void *notify_cls)
1023 {
1024   struct GNUNET_CLIENT_TransmitHandle *th;
1025
1026   if (NULL != sock->th)
1027     return NULL;
1028   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1029   th->sock = sock;
1030   th->size = size;
1031   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1032   th->auto_retry = auto_retry;
1033   th->notify = notify;
1034   th->notify_cls = notify_cls;
1035   th->attempts_left = MAX_ATTEMPTS;
1036   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
1037                                                     size,
1038                                                     timeout,
1039                                                     &client_notify, th);
1040   if (NULL == th->th)
1041     {
1042       GNUNET_break (0);
1043       GNUNET_free (th);
1044       return NULL;
1045     }
1046   sock->th = th;
1047   return th;
1048 }
1049
1050
1051 /**
1052  * Cancel a request for notification.
1053  * 
1054  * @param th handle from the original request.
1055  */
1056 void
1057 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
1058                                             GNUNET_CLIENT_TransmitHandle *th)
1059 {
1060   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1061     {
1062       GNUNET_break (NULL == th->th);
1063       GNUNET_SCHEDULER_cancel (th->sock->sched, th->reconnect_task);
1064       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1065     }
1066   else
1067     {
1068       GNUNET_break (NULL != th->th);
1069       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1070     }
1071   th->sock->th = NULL;
1072   GNUNET_free (th);
1073 }
1074
1075
1076 /**
1077  * Function called to notify a client about the socket
1078  * begin ready to queue the message.  "buf" will be
1079  * NULL and "size" zero if the socket was closed for
1080  * writing in the meantime.
1081  *
1082  * @param cls closure of type "struct TransmitGetResponseContext*"
1083  * @param size number of bytes available in buf
1084  * @param buf where the callee should write the message
1085  * @return number of bytes written to buf
1086  */
1087 static size_t
1088 transmit_for_response (void *cls, size_t size, void *buf)
1089 {
1090   struct TransmitGetResponseContext *tc = cls;
1091   uint16_t msize;
1092
1093   tc->sock->tag = NULL;
1094   msize = ntohs (tc->hdr->size);
1095   if (NULL == buf)
1096     {
1097 #if DEBUG_CLIENT
1098       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099                   _("Could not submit request, not expecting to receive a response.\n"));
1100 #endif
1101       tc->rn (tc->rn_cls, NULL);
1102       GNUNET_free (tc);
1103       return 0;
1104     }
1105   GNUNET_assert (size >= msize);
1106   memcpy (buf, tc->hdr, msize);
1107   GNUNET_CLIENT_receive (tc->sock,
1108                          tc->rn,
1109                          tc->rn_cls,
1110                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1111   GNUNET_free (tc);
1112   return msize;
1113 }
1114
1115
1116 /**
1117  * Convenience API that combines sending a request
1118  * to the service and waiting for a response.
1119  * If either operation times out, the callback
1120  * will be called with a "NULL" response (in which
1121  * case the connection should probably be destroyed).
1122  *
1123  * @param sock connection to use
1124  * @param hdr message to transmit
1125  * @param timeout when to give up (for both transmission
1126  *         and for waiting for a response)
1127  * @param auto_retry if the connection to the service dies, should we
1128  *        automatically re-connect and retry (within the timeout period)
1129  *        or should we immediately fail in this case?  Pass GNUNET_YES
1130  *        if the caller does not care about temporary connection errors,
1131  *        for example because the protocol is stateless
1132  * @param rn function to call with the response
1133  * @param rn_cls closure for rn 
1134  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1135  *         is already pending
1136  */
1137 int
1138 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
1139                                          *sock,
1140                                          const struct GNUNET_MessageHeader
1141                                          *hdr,
1142                                          struct GNUNET_TIME_Relative timeout,
1143                                          int auto_retry,
1144                                          GNUNET_CLIENT_MessageHandler rn,
1145                                          void *rn_cls)
1146 {
1147   struct TransmitGetResponseContext *tc;
1148   uint16_t msize;
1149
1150   if (NULL != sock->th)
1151     return GNUNET_SYSERR;
1152   GNUNET_assert (sock->tag == NULL);
1153   msize = ntohs (hdr->size);
1154   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1155   tc->sock = sock;
1156   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1157   memcpy (&tc[1], hdr, msize);
1158   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1159   tc->rn = rn;
1160   tc->rn_cls = rn_cls;
1161   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
1162                                                    msize,
1163                                                    timeout,
1164                                                    auto_retry,
1165                                                    &transmit_for_response,
1166                                                    tc))
1167     {
1168       GNUNET_break (0);
1169       GNUNET_free (tc);
1170       return GNUNET_SYSERR;
1171     }
1172   sock->tag = tc;
1173   return GNUNET_OK;
1174 }
1175
1176
1177
1178 /*  end of client.c */