24740caabc1babe85ced703432683331d579aaf3
[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  * Struct to refer to a GNUnet TCP connection.
141  * This is more than just a socket because if the server
142  * drops the connection, the client automatically tries
143  * to reconnect (and for that needs connection information).
144  */
145 struct GNUNET_CLIENT_Connection
146 {
147
148   /**
149    * the socket handle, NULL if not live
150    */
151   struct GNUNET_CONNECTION_Handle *sock;
152
153   /**
154    * Our scheduler.
155    */
156   struct GNUNET_SCHEDULER_Handle *sched;
157
158   /**
159    * Our configuration.
160    * FIXME: why do we DUP the configuration? Avoid this!
161    */
162   struct GNUNET_CONFIGURATION_Handle *cfg;
163
164   /**
165    * Name of the service we interact with.
166    */
167   char *service_name;
168
169   /**
170    * Context of a transmit_and_get_response operation, NULL
171    * if no such operation is pending.
172    */
173   struct TransmitGetResponseContext *tag;
174
175   /**
176    * Handler for current receiver task.
177    */
178   GNUNET_CLIENT_MessageHandler receiver_handler;
179
180   /**
181    * Closure for receiver_handler.
182    */
183   void *receiver_handler_cls;
184
185   /**
186    * Handle for a pending transmission request, NULL if there is
187    * none pending.
188    */
189   struct GNUNET_CLIENT_TransmitHandle *th;
190
191   /**
192    * Handler for service test completion (NULL unless in service_test)
193    */
194   GNUNET_SCHEDULER_Task test_cb;
195
196   /**
197    * Deadline for calling 'test_cb'.
198    */
199   struct GNUNET_TIME_Absolute test_deadline;
200
201   /**
202    * If we are re-trying and are delaying to do so,
203    * handle to the scheduled task managing the delay.
204    */
205   GNUNET_SCHEDULER_TaskIdentifier receive_task;
206
207   /**
208    * Closure for test_cb (NULL unless in service_test)
209    */
210   void *test_cb_cls;
211
212   /**
213    * Buffer for received message.
214    */
215   char *received_buf;
216
217   /**
218    * Timeout for receiving a response (absolute time).
219    */
220   struct GNUNET_TIME_Absolute receive_timeout;
221
222   /**
223    * Current value for our incremental back-off (for
224    * connect re-tries).
225    */
226   struct GNUNET_TIME_Relative back_off;
227
228   /**
229    * Number of bytes in received_buf that are valid.
230    */
231   size_t received_pos;
232
233   /**
234    * Size of received_buf.
235    */
236   unsigned int received_size;
237
238   /**
239    * Do we have a complete response in received_buf?
240    */
241   int msg_complete;
242
243   /**
244    * Are we currently busy doing receive-processing?
245    * GNUNET_YES if so, GNUNET_NO if not.
246    */
247   int in_receive;
248
249   /**
250    * Are we ignoring shutdown signals?
251    */
252   int ignore_shutdown;
253
254 };
255
256
257 static struct GNUNET_CONNECTION_Handle *
258 do_connect (struct GNUNET_SCHEDULER_Handle *sched,
259             const char *service_name,
260             const struct GNUNET_CONFIGURATION_Handle *cfg)
261 {
262   struct GNUNET_CONNECTION_Handle *sock;
263   char *hostname;
264   unsigned long long port;
265
266   if ((GNUNET_OK !=
267        GNUNET_CONFIGURATION_get_value_number (cfg,
268                                               service_name,
269                                               "PORT",
270                                               &port)) ||
271       (port > 65535) ||
272       (GNUNET_OK !=
273        GNUNET_CONFIGURATION_get_value_string (cfg,
274                                               service_name,
275                                               "HOSTNAME", &hostname)))
276     {
277       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
278                   _
279                   ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
280                   service_name);
281       return NULL;
282     }
283   if (0 == strlen (hostname))
284     {
285       GNUNET_free (hostname);
286       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
287                   _("Need a non-empty hostname for service `%s'.\n"),
288                   service_name);
289       return NULL;
290     }
291   sock = GNUNET_CONNECTION_create_from_connect (sched,
292                                                 cfg,
293                                                 hostname,
294                                                 port,
295                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
296   GNUNET_free (hostname);
297   return sock;
298 }
299
300
301 /**
302  * Get a connection with a service.
303  *
304  * @param sched scheduler to use
305  * @param service_name name of the service
306  * @param cfg configuration to use
307  * @return NULL on error (service unknown to configuration)
308  */
309 struct GNUNET_CLIENT_Connection *
310 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
311                        const char *service_name,
312                        const struct GNUNET_CONFIGURATION_Handle *cfg)
313 {
314   struct GNUNET_CLIENT_Connection *ret;
315   struct GNUNET_CONNECTION_Handle *sock;
316
317   sock = do_connect (sched, service_name, cfg);
318   if (sock == NULL)
319     return NULL;
320   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
321   ret->sock = sock;
322   ret->sched = sched;
323   ret->service_name = GNUNET_strdup (service_name);
324   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
325   ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
326   return ret;
327 }
328
329
330 /**
331  * Configure this connection to ignore shutdown signals.
332  *
333  * @param h client handle
334  * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
335  */
336 void
337 GNUNET_CLIENT_ignore_shutdown (struct GNUNET_CLIENT_Connection *h,
338                                int do_ignore)
339 {
340   h->ignore_shutdown = do_ignore;
341   if (h->sock != NULL)
342     GNUNET_CONNECTION_ignore_shutdown (h->sock,
343                                        do_ignore);
344 }
345
346
347 /**
348  * Destroy connection with the service.  This will automatically
349  * cancel any pending "receive" request (however, the handler will
350  * *NOT* be called, not even with a NULL message).  Any pending
351  * transmission request will also be cancelled UNLESS the callback for
352  * the transmission request has already been called, in which case the
353  * transmission 'finish_pending_write' argument determines whether or
354  * not the write is guaranteed to complete before the socket is fully
355  * destroyed (unless, of course, there is an error with the server in
356  * which case the message may still be lost).
357  *
358  * @param finish_pending_write should a transmission already passed to the
359  *          handle be completed?
360  * @param sock handle to the service connection
361  */
362 void
363 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
364                           int finish_pending_write)
365 {
366   GNUNET_assert (sock->sock != NULL);
367   if (sock->in_receive == GNUNET_YES)
368     {
369       GNUNET_CONNECTION_receive_cancel (sock->sock);
370       sock->in_receive = GNUNET_NO;
371     }
372   GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
373   sock->sock = NULL;
374   if (sock->tag != NULL)
375     {
376       GNUNET_free (sock->tag);
377       sock->tag = NULL;
378     }
379   sock->receiver_handler = NULL;
380   if (sock->th != NULL)
381     GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
382   if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
383     {
384       GNUNET_SCHEDULER_cancel (sock->sched, sock->receive_task);
385       sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
386     }
387   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
388   GNUNET_free (sock->service_name);
389   GNUNET_CONFIGURATION_destroy (sock->cfg);
390   GNUNET_free (sock);
391 }
392
393
394 /**
395  * Check if message is complete
396  */
397 static void
398 check_complete (struct GNUNET_CLIENT_Connection *conn)
399 {
400   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
401       (conn->received_pos >=
402        ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
403               size)))
404     conn->msg_complete = GNUNET_YES;
405 }
406
407
408 /**
409  * Callback function for data received from the network.  Note that
410  * both "available" and "errCode" would be 0 if the read simply timed out.
411  *
412  * @param cls closure
413  * @param buf pointer to received data
414  * @param available number of bytes availabe in "buf",
415  *        possibly 0 (on errors)
416  * @param addr address of the sender
417  * @param addrlen size of addr
418  * @param errCode value of errno (on errors receiving)
419  */
420 static void
421 receive_helper (void *cls,
422                 const void *buf,
423                 size_t available,
424                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
425 {
426   struct GNUNET_CLIENT_Connection *conn = cls;
427   struct GNUNET_TIME_Relative remaining;
428   GNUNET_CLIENT_MessageHandler receive_handler;
429   void *receive_handler_cls;
430
431   GNUNET_assert (conn->msg_complete == GNUNET_NO);
432   conn->in_receive = GNUNET_NO;
433   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
434     {
435       /* signal timeout! */
436       if (NULL != (receive_handler = conn->receiver_handler))
437         {
438           receive_handler_cls = conn->receiver_handler_cls;
439           conn->receiver_handler = NULL;
440           receive_handler (receive_handler_cls, NULL);
441         }
442       return;
443     }
444
445   /* FIXME: optimize for common fast case where buf contains the
446      entire message and we need no copying... */
447
448
449   /* slow path: append to array */
450   if (conn->received_size < conn->received_pos + available)
451     GNUNET_array_grow (conn->received_buf,
452                        conn->received_size, conn->received_pos + available);
453   memcpy (&conn->received_buf[conn->received_pos], buf, available);
454   conn->received_pos += available;
455   check_complete (conn);
456   /* check for timeout */
457   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
458   if (remaining.value == 0)
459     {
460       /* signal timeout! */
461       conn->receiver_handler (conn->receiver_handler_cls, NULL);
462       return;
463     }
464   /* back to receive -- either for more data or to call callback! */
465   GNUNET_CLIENT_receive (conn,
466                          conn->receiver_handler,
467                          conn->receiver_handler_cls, remaining);
468 }
469
470
471 /**
472  * Continuation to call the receive callback.
473  *
474  * @param cls  our handle to the client connection
475  * @param tc scheduler context
476  */
477 static void
478 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
479 {
480   struct GNUNET_CLIENT_Connection *sock = cls;
481   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
482   const struct GNUNET_MessageHeader *cmsg =
483     (const struct GNUNET_MessageHeader *) sock->received_buf;
484   void *handler_cls = sock->receiver_handler_cls;
485   uint16_t msize = ntohs (cmsg->size);
486   char mbuf[msize];
487   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
488
489   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
490   GNUNET_assert (GNUNET_YES == sock->msg_complete);
491   GNUNET_assert (sock->received_pos >= msize);
492   memcpy (msg, cmsg, msize);
493   memmove (sock->received_buf,
494            &sock->received_buf[msize], sock->received_pos - msize);
495   sock->received_pos -= msize;
496   sock->msg_complete = GNUNET_NO;
497   sock->receiver_handler = NULL;
498   check_complete (sock);
499   if (handler != NULL)
500     handler (handler_cls, msg);
501 }
502
503
504 /**
505  * Read from the service.
506  *
507  * @param sock the service
508  * @param handler function to call with the message
509  * @param handler_cls closure for handler
510  * @param timeout how long to wait until timing out
511  */
512 void
513 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
514                        GNUNET_CLIENT_MessageHandler handler,
515                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
516 {
517   if (sock->sock == NULL)
518     {
519       /* already disconnected, fail instantly! */
520       GNUNET_break (0);         /* this should not happen in well-written code! */
521       handler (handler_cls, NULL);
522       return;
523     }
524   sock->receiver_handler = handler;
525   sock->receiver_handler_cls = handler_cls;
526   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
527   if (GNUNET_YES == sock->msg_complete)
528     {
529       sock->receive_task = GNUNET_SCHEDULER_add_after (sock->sched,
530                                                        GNUNET_SCHEDULER_NO_TASK,
531                                                        &receive_task, sock);
532     }
533   else
534     {
535       GNUNET_assert (sock->in_receive == GNUNET_NO);
536       sock->in_receive = GNUNET_YES;
537       GNUNET_CONNECTION_receive (sock->sock,
538                                  GNUNET_SERVER_MAX_MESSAGE_SIZE,
539                                  timeout, &receive_helper, sock);
540     }
541 }
542
543
544 /**
545  * Report service unavailable.
546  */
547 static void
548 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
549                     GNUNET_SCHEDULER_Task task, void *task_cls)
550 {
551   GNUNET_SCHEDULER_add_continuation (s,
552                                      task,
553                                      task_cls,
554                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
555 }
556
557
558 /**
559  * Receive confirmation from test, service is up.
560  *
561  * @param cls closure
562  * @param msg message received, NULL on timeout or fatal error
563  */
564 static void
565 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
566 {
567   struct GNUNET_CLIENT_Connection *conn = cls;
568   /* We may want to consider looking at the reply in more
569      detail in the future, for example, is this the
570      correct service? FIXME! */
571   if (msg != NULL)
572     {
573 #if DEBUG_CLIENT
574       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
575                   "Received confirmation that service is running.\n");
576 #endif
577       GNUNET_SCHEDULER_add_continuation (conn->sched,
578                                          conn->test_cb,
579                                          conn->test_cb_cls,
580                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
581     }
582   else
583     {
584       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
585     }
586   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
587 }
588
589
590 static size_t
591 write_test (void *cls, size_t size, void *buf)
592 {
593   struct GNUNET_CLIENT_Connection *conn = cls;
594   struct GNUNET_MessageHeader *msg;
595
596   if (size < sizeof (struct GNUNET_MessageHeader))
597     {
598 #if DEBUG_CLIENT
599       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
600                   _("Failure to transmit TEST request.\n"));
601 #endif
602       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
603       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
604       return 0;                 /* client disconnected */
605     }
606 #if DEBUG_CLIENT
607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
608               "Transmitting `%s' request.\n", "TEST");
609 #endif
610   msg = (struct GNUNET_MessageHeader *) buf;
611   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
612   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
613   GNUNET_CLIENT_receive (conn, 
614                          &confirm_handler, 
615                          conn, 
616                          GNUNET_TIME_absolute_get_remaining (conn->test_deadline));
617   return sizeof (struct GNUNET_MessageHeader);
618 }
619
620
621 /**
622  * Wait until the service is running.
623  *
624  * @param sched scheduler to use
625  * @param service name of the service to wait for
626  * @param cfg configuration to use
627  * @param timeout how long to wait at most in ms
628  * @param task task to run if service is running
629  *        (reason will be "PREREQ_DONE" (service running)
630  *         or "TIMEOUT" (service not known to be running))
631  * @param task_cls closure for task
632  */
633 void
634 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
635                             const char *service,
636                             const struct GNUNET_CONFIGURATION_Handle *cfg,
637                             struct GNUNET_TIME_Relative timeout,
638                             GNUNET_SCHEDULER_Task task, void *task_cls)
639 {
640   struct GNUNET_CLIENT_Connection *conn;
641
642 #if DEBUG_CLIENT
643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644               "Testing if service `%s' is running.\n", service);
645 #endif
646   conn = GNUNET_CLIENT_connect (sched, service, cfg);
647   if (conn == NULL)
648     {
649       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
650                   _
651                   ("Could not connect to service `%s', must not be running.\n"),
652                   service);
653       service_test_error (sched, task, task_cls);
654       return;
655     }
656   conn->test_cb = task;
657   conn->test_cb_cls = task_cls;
658   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
659
660   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
661                                                    sizeof (struct GNUNET_MessageHeader),
662                                                    timeout,
663                                                    GNUNET_YES,
664                                                    &write_test, conn))  
665     {
666       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
667                   _("Failure to transmit request to service `%s'\n"),
668                   service);
669       service_test_error (sched, task, task_cls);
670       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
671       return;
672     }
673 }
674
675
676 /**
677  * Connection notifies us about failure or success of
678  * a transmission request.  Either pass it on to our
679  * user or, if possible, retry.
680  *
681  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
682  * @param size number of bytes available for transmission
683  * @param buf where to write them
684  * @return number of bytes written to buf
685  */
686 static size_t client_notify (void *cls, size_t size, void *buf);
687
688
689 /**
690  * This task is run if we should re-try connection to the
691  * service after a while.
692  *
693  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
694  * @param tc unused
695  */
696 static void
697 client_delayed_retry (void *cls,
698                       const struct GNUNET_SCHEDULER_TaskContext *tc)
699 {
700   struct GNUNET_CLIENT_TransmitHandle *th = cls;
701
702   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
703   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
704     {
705 #if DEBUG_CLIENT
706       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
707                   "Transmission failed due to shutdown.\n");
708 #endif
709       th->sock->th = NULL;
710       th->notify (th->notify_cls, 0, NULL);
711       GNUNET_free (th);
712       return;
713     }
714   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
715                                                     th->size,
716                                                     GNUNET_TIME_absolute_get_remaining
717                                                     (th->timeout),
718                                                     &client_notify, th);
719   if (th->th == NULL)
720     {
721       GNUNET_break (0);
722       th->notify (th->notify_cls, 0, NULL);
723       GNUNET_free (th);
724       return;
725     }
726 }
727
728
729 /**
730  * Connection notifies us about failure or success of a transmission
731  * request.  Either pass it on to our user or, if possible, retry.
732  *
733  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
734  * @param size number of bytes available for transmission
735  * @param buf where to write them
736  * @return number of bytes written to buf
737  */
738 static size_t
739 client_notify (void *cls, size_t size, void *buf)
740 {
741   struct GNUNET_CLIENT_TransmitHandle *th = cls;
742   size_t ret;
743   struct GNUNET_TIME_Relative delay;
744
745   th->th = NULL;
746   th->sock->th = NULL;
747   if (buf == NULL)
748     {
749       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
750       delay.value /= 2;
751       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason (th->sock->sched))) ||
752            (GNUNET_YES != th->auto_retry) ||
753            (0 == --th->attempts_left) || 
754            (delay.value < 1) )
755         {
756 #if DEBUG_CLIENT
757           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
758                       "Transmission failed %u times, giving up.\n",
759                       MAX_ATTEMPTS - th->attempts_left);
760 #endif
761           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
762           GNUNET_free (th);
763           return 0;
764         }
765       /* auto-retry */
766       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
767       th->sock->sock = do_connect (th->sock->sched,
768                                    th->sock->service_name, th->sock->cfg);
769       GNUNET_assert (NULL != th->sock->sock);
770       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
771                                          th->sock->ignore_shutdown);
772       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
773       th->sock->back_off 
774           = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
775                                     GNUNET_TIME_UNIT_SECONDS);
776 #if DEBUG_CLIENT
777       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778                   "Transmission failed %u times, trying again in %llums.\n",
779                   MAX_ATTEMPTS - th->attempts_left,
780                   (unsigned long long) delay.value);
781 #endif
782       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
783                                                          delay,
784                                                          &client_delayed_retry,
785                                                          th);
786       th->sock->th = th;
787       return 0;
788     }
789   GNUNET_assert (size >= th->size);
790   ret = th->notify (th->notify_cls, size, buf);
791   GNUNET_free (th);
792   return ret;
793 }
794
795
796 /**
797  * Ask the client to call us once the specified number of bytes
798  * are free in the transmission buffer.  May call the notify
799  * method immediately if enough space is available.
800  *
801  * @param sock connection to the service
802  * @param size number of bytes to send
803  * @param timeout after how long should we give up (and call
804  *        notify with buf NULL and size 0)?
805  * @param auto_retry if the connection to the service dies, should we
806  *        automatically re-connect and retry (within the timeout period)
807  *        or should we immediately fail in this case?  Pass GNUNET_YES
808  *        if the caller does not care about temporary connection errors,
809  *        for example because the protocol is stateless
810  * @param notify function to call
811  * @param notify_cls closure for notify
812  * @return NULL if our buffer will never hold size bytes,
813  *         a handle if the notify callback was queued (can be used to cancel)
814  */
815 struct GNUNET_CLIENT_TransmitHandle *
816 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
817                                      size_t size,
818                                      struct GNUNET_TIME_Relative timeout,
819                                      int auto_retry,
820                                      GNUNET_CONNECTION_TransmitReadyNotify
821                                      notify, void *notify_cls)
822 {
823   struct GNUNET_CLIENT_TransmitHandle *th;
824
825   if (NULL != sock->th)
826     return NULL;
827   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
828   th->sock = sock;
829   th->size = size;
830   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
831   th->auto_retry = auto_retry;
832   th->notify = notify;
833   th->notify_cls = notify_cls;
834   th->attempts_left = MAX_ATTEMPTS;
835   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
836                                                     size,
837                                                     timeout,
838                                                     &client_notify, th);
839   if (NULL == th->th)
840     {
841       GNUNET_break (0);
842       GNUNET_free (th);
843       return NULL;
844     }
845   sock->th = th;
846   return th;
847 }
848
849
850 /**
851  * Cancel a request for notification.
852  * 
853  * @param th handle from the original request.
854  */
855 void
856 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
857                                             GNUNET_CLIENT_TransmitHandle *th)
858 {
859   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
860     {
861       GNUNET_break (NULL == th->th);
862       GNUNET_SCHEDULER_cancel (th->sock->sched, th->reconnect_task);
863       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
864     }
865   else
866     {
867       GNUNET_break (NULL != th->th);
868       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
869     }
870   th->sock->th = NULL;
871   GNUNET_free (th);
872 }
873
874
875 /**
876  * Function called to notify a client about the socket
877  * begin ready to queue the message.  "buf" will be
878  * NULL and "size" zero if the socket was closed for
879  * writing in the meantime.
880  *
881  * @param cls closure of type "struct TransmitGetResponseContext*"
882  * @param size number of bytes available in buf
883  * @param buf where the callee should write the message
884  * @return number of bytes written to buf
885  */
886 static size_t
887 transmit_for_response (void *cls, size_t size, void *buf)
888 {
889   struct TransmitGetResponseContext *tc = cls;
890   uint16_t msize;
891
892   tc->sock->tag = NULL;
893   msize = ntohs (tc->hdr->size);
894   if (NULL == buf)
895     {
896 #if DEBUG_CLIENT
897       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
898                   _("Could not submit request, not expecting to receive a response.\n"));
899 #endif
900       tc->rn (tc->rn_cls, NULL);
901       GNUNET_free (tc);
902       return 0;
903     }
904   GNUNET_assert (size >= msize);
905   memcpy (buf, tc->hdr, msize);
906   GNUNET_CLIENT_receive (tc->sock,
907                          tc->rn,
908                          tc->rn_cls,
909                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
910   GNUNET_free (tc);
911   return msize;
912 }
913
914
915 /**
916  * Convenience API that combines sending a request
917  * to the service and waiting for a response.
918  * If either operation times out, the callback
919  * will be called with a "NULL" response (in which
920  * case the connection should probably be destroyed).
921  *
922  * @param sock connection to use
923  * @param hdr message to transmit
924  * @param timeout when to give up (for both transmission
925  *         and for waiting for a response)
926  * @param auto_retry if the connection to the service dies, should we
927  *        automatically re-connect and retry (within the timeout period)
928  *        or should we immediately fail in this case?  Pass GNUNET_YES
929  *        if the caller does not care about temporary connection errors,
930  *        for example because the protocol is stateless
931  * @param rn function to call with the response
932  * @param rn_cls closure for rn 
933  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
934  *         is already pending
935  */
936 int
937 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
938                                          *sock,
939                                          const struct GNUNET_MessageHeader
940                                          *hdr,
941                                          struct GNUNET_TIME_Relative timeout,
942                                          int auto_retry,
943                                          GNUNET_CLIENT_MessageHandler rn,
944                                          void *rn_cls)
945 {
946   struct TransmitGetResponseContext *tc;
947   uint16_t msize;
948
949   if (NULL != sock->th)
950     return GNUNET_SYSERR;
951   GNUNET_assert (sock->tag == NULL);
952   msize = ntohs (hdr->size);
953   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
954   tc->sock = sock;
955   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
956   memcpy (&tc[1], hdr, msize);
957   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
958   tc->rn = rn;
959   tc->rn_cls = rn_cls;
960   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
961                                                    msize,
962                                                    timeout,
963                                                    auto_retry,
964                                                    &transmit_for_response,
965                                                    tc))
966     {
967       GNUNET_break (0);
968       GNUNET_free (tc);
969       return GNUNET_SYSERR;
970     }
971   sock->tag = tc;
972   return GNUNET_OK;
973 }
974
975
976
977 /*  end of client.c */