f964b7322177ced5a5e531c7bbe2913f10f23e3a
[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 #if DEBUG_CLIENT
490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
491               "Received message of size %u\n",
492               msize);
493 #endif
494   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
495   GNUNET_assert (GNUNET_YES == sock->msg_complete);
496   GNUNET_assert (sock->received_pos >= msize);
497   memcpy (msg, cmsg, msize);
498   memmove (sock->received_buf,
499            &sock->received_buf[msize], sock->received_pos - msize);
500   sock->received_pos -= msize;
501   sock->msg_complete = GNUNET_NO;
502   sock->receiver_handler = NULL;
503   check_complete (sock);
504   if (handler != NULL)
505     handler (handler_cls, msg);
506 }
507
508
509 /**
510  * Read from the service.
511  *
512  * @param sock the service
513  * @param handler function to call with the message
514  * @param handler_cls closure for handler
515  * @param timeout how long to wait until timing out
516  */
517 void
518 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
519                        GNUNET_CLIENT_MessageHandler handler,
520                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
521 {
522   if (sock->sock == NULL)
523     {
524       /* already disconnected, fail instantly! */
525       GNUNET_break (0);         /* this should not happen in well-written code! */
526       handler (handler_cls, NULL);
527       return;
528     }
529   sock->receiver_handler = handler;
530   sock->receiver_handler_cls = handler_cls;
531   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
532   if (GNUNET_YES == sock->msg_complete)
533     {
534       sock->receive_task = GNUNET_SCHEDULER_add_after (sock->sched,
535                                                        GNUNET_SCHEDULER_NO_TASK,
536                                                        &receive_task, sock);
537     }
538   else
539     {
540       GNUNET_assert (sock->in_receive == GNUNET_NO);
541       sock->in_receive = GNUNET_YES;
542       GNUNET_CONNECTION_receive (sock->sock,
543                                  GNUNET_SERVER_MAX_MESSAGE_SIZE,
544                                  timeout, &receive_helper, sock);
545     }
546 }
547
548
549 /**
550  * Report service unavailable.
551  */
552 static void
553 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
554                     GNUNET_SCHEDULER_Task task, void *task_cls)
555 {
556   GNUNET_SCHEDULER_add_continuation (s,
557                                      task,
558                                      task_cls,
559                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
560 }
561
562
563 /**
564  * Receive confirmation from test, service is up.
565  *
566  * @param cls closure
567  * @param msg message received, NULL on timeout or fatal error
568  */
569 static void
570 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
571 {
572   struct GNUNET_CLIENT_Connection *conn = cls;
573   /* We may want to consider looking at the reply in more
574      detail in the future, for example, is this the
575      correct service? FIXME! */
576   if (msg != NULL)
577     {
578 #if DEBUG_CLIENT
579       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
580                   "Received confirmation that service is running.\n");
581 #endif
582       GNUNET_SCHEDULER_add_continuation (conn->sched,
583                                          conn->test_cb,
584                                          conn->test_cb_cls,
585                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
586     }
587   else
588     {
589       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
590     }
591   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
592 }
593
594
595 static size_t
596 write_test (void *cls, size_t size, void *buf)
597 {
598   struct GNUNET_CLIENT_Connection *conn = cls;
599   struct GNUNET_MessageHeader *msg;
600
601   if (size < sizeof (struct GNUNET_MessageHeader))
602     {
603 #if DEBUG_CLIENT
604       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
605                   _("Failure to transmit TEST request.\n"));
606 #endif
607       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
608       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
609       return 0;                 /* client disconnected */
610     }
611 #if DEBUG_CLIENT
612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
613               "Transmitting `%s' request.\n", "TEST");
614 #endif
615   msg = (struct GNUNET_MessageHeader *) buf;
616   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
617   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
618   GNUNET_CLIENT_receive (conn, 
619                          &confirm_handler, 
620                          conn, 
621                          GNUNET_TIME_absolute_get_remaining (conn->test_deadline));
622   return sizeof (struct GNUNET_MessageHeader);
623 }
624
625
626 /**
627  * Wait until the service is running.
628  *
629  * @param sched scheduler to use
630  * @param service name of the service to wait for
631  * @param cfg configuration to use
632  * @param timeout how long to wait at most in ms
633  * @param task task to run if service is running
634  *        (reason will be "PREREQ_DONE" (service running)
635  *         or "TIMEOUT" (service not known to be running))
636  * @param task_cls closure for task
637  */
638 void
639 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
640                             const char *service,
641                             const struct GNUNET_CONFIGURATION_Handle *cfg,
642                             struct GNUNET_TIME_Relative timeout,
643                             GNUNET_SCHEDULER_Task task, void *task_cls)
644 {
645   struct GNUNET_CLIENT_Connection *conn;
646
647 #if DEBUG_CLIENT
648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649               "Testing if service `%s' is running.\n", service);
650 #endif
651   conn = GNUNET_CLIENT_connect (sched, service, cfg);
652   if (conn == NULL)
653     {
654       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
655                   _
656                   ("Could not connect to service `%s', must not be running.\n"),
657                   service);
658       service_test_error (sched, task, task_cls);
659       return;
660     }
661   conn->test_cb = task;
662   conn->test_cb_cls = task_cls;
663   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
664
665   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
666                                                    sizeof (struct GNUNET_MessageHeader),
667                                                    timeout,
668                                                    GNUNET_YES,
669                                                    &write_test, conn))  
670     {
671       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
672                   _("Failure to transmit request to service `%s'\n"),
673                   service);
674       service_test_error (sched, task, task_cls);
675       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
676       return;
677     }
678 }
679
680
681 /**
682  * Connection notifies us about failure or success of
683  * a transmission request.  Either pass it on to our
684  * user or, if possible, retry.
685  *
686  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
687  * @param size number of bytes available for transmission
688  * @param buf where to write them
689  * @return number of bytes written to buf
690  */
691 static size_t client_notify (void *cls, size_t size, void *buf);
692
693
694 /**
695  * This task is run if we should re-try connection to the
696  * service after a while.
697  *
698  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
699  * @param tc unused
700  */
701 static void
702 client_delayed_retry (void *cls,
703                       const struct GNUNET_SCHEDULER_TaskContext *tc)
704 {
705   struct GNUNET_CLIENT_TransmitHandle *th = cls;
706
707   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
708   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
709     {
710 #if DEBUG_CLIENT
711       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
712                   "Transmission failed due to shutdown.\n");
713 #endif
714       th->sock->th = NULL;
715       th->notify (th->notify_cls, 0, NULL);
716       GNUNET_free (th);
717       return;
718     }
719   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
720                                                     th->size,
721                                                     GNUNET_TIME_absolute_get_remaining
722                                                     (th->timeout),
723                                                     &client_notify, th);
724   if (th->th == NULL)
725     {
726       GNUNET_break (0);
727       th->notify (th->notify_cls, 0, NULL);
728       GNUNET_free (th);
729       return;
730     }
731 }
732
733
734 /**
735  * Connection notifies us about failure or success of a transmission
736  * request.  Either pass it on to our user or, if possible, retry.
737  *
738  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
739  * @param size number of bytes available for transmission
740  * @param buf where to write them
741  * @return number of bytes written to buf
742  */
743 static size_t
744 client_notify (void *cls, size_t size, void *buf)
745 {
746   struct GNUNET_CLIENT_TransmitHandle *th = cls;
747   size_t ret;
748   struct GNUNET_TIME_Relative delay;
749
750   th->th = NULL;
751   th->sock->th = NULL;
752   if (buf == NULL)
753     {
754       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
755       delay.value /= 2;
756       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason (th->sock->sched))) ||
757            (GNUNET_YES != th->auto_retry) ||
758            (0 == --th->attempts_left) || 
759            (delay.value < 1) )
760         {
761 #if DEBUG_CLIENT
762           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
763                       "Transmission failed %u times, giving up.\n",
764                       MAX_ATTEMPTS - th->attempts_left);
765 #endif
766           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
767           GNUNET_free (th);
768           return 0;
769         }
770       /* auto-retry */
771       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
772       th->sock->sock = do_connect (th->sock->sched,
773                                    th->sock->service_name, th->sock->cfg);
774       GNUNET_assert (NULL != th->sock->sock);
775       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
776                                          th->sock->ignore_shutdown);
777       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
778       th->sock->back_off 
779           = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
780                                     GNUNET_TIME_UNIT_SECONDS);
781 #if DEBUG_CLIENT
782       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
783                   "Transmission failed %u times, trying again in %llums.\n",
784                   MAX_ATTEMPTS - th->attempts_left,
785                   (unsigned long long) delay.value);
786 #endif
787       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
788                                                          delay,
789                                                          &client_delayed_retry,
790                                                          th);
791       th->sock->th = th;
792       return 0;
793     }
794   GNUNET_assert (size >= th->size);
795   ret = th->notify (th->notify_cls, size, buf);
796   GNUNET_free (th);
797   return ret;
798 }
799
800
801 /**
802  * Ask the client to call us once the specified number of bytes
803  * are free in the transmission buffer.  May call the notify
804  * method immediately if enough space is available.
805  *
806  * @param sock connection to the service
807  * @param size number of bytes to send
808  * @param timeout after how long should we give up (and call
809  *        notify with buf NULL and size 0)?
810  * @param auto_retry if the connection to the service dies, should we
811  *        automatically re-connect and retry (within the timeout period)
812  *        or should we immediately fail in this case?  Pass GNUNET_YES
813  *        if the caller does not care about temporary connection errors,
814  *        for example because the protocol is stateless
815  * @param notify function to call
816  * @param notify_cls closure for notify
817  * @return NULL if our buffer will never hold size bytes,
818  *         a handle if the notify callback was queued (can be used to cancel)
819  */
820 struct GNUNET_CLIENT_TransmitHandle *
821 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
822                                      size_t size,
823                                      struct GNUNET_TIME_Relative timeout,
824                                      int auto_retry,
825                                      GNUNET_CONNECTION_TransmitReadyNotify
826                                      notify, void *notify_cls)
827 {
828   struct GNUNET_CLIENT_TransmitHandle *th;
829
830   if (NULL != sock->th)
831     return NULL;
832   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
833   th->sock = sock;
834   th->size = size;
835   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
836   th->auto_retry = auto_retry;
837   th->notify = notify;
838   th->notify_cls = notify_cls;
839   th->attempts_left = MAX_ATTEMPTS;
840   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
841                                                     size,
842                                                     timeout,
843                                                     &client_notify, th);
844   if (NULL == th->th)
845     {
846       GNUNET_break (0);
847       GNUNET_free (th);
848       return NULL;
849     }
850   sock->th = th;
851   return th;
852 }
853
854
855 /**
856  * Cancel a request for notification.
857  * 
858  * @param th handle from the original request.
859  */
860 void
861 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
862                                             GNUNET_CLIENT_TransmitHandle *th)
863 {
864   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
865     {
866       GNUNET_break (NULL == th->th);
867       GNUNET_SCHEDULER_cancel (th->sock->sched, th->reconnect_task);
868       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
869     }
870   else
871     {
872       GNUNET_break (NULL != th->th);
873       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
874     }
875   th->sock->th = NULL;
876   GNUNET_free (th);
877 }
878
879
880 /**
881  * Function called to notify a client about the socket
882  * begin ready to queue the message.  "buf" will be
883  * NULL and "size" zero if the socket was closed for
884  * writing in the meantime.
885  *
886  * @param cls closure of type "struct TransmitGetResponseContext*"
887  * @param size number of bytes available in buf
888  * @param buf where the callee should write the message
889  * @return number of bytes written to buf
890  */
891 static size_t
892 transmit_for_response (void *cls, size_t size, void *buf)
893 {
894   struct TransmitGetResponseContext *tc = cls;
895   uint16_t msize;
896
897   tc->sock->tag = NULL;
898   msize = ntohs (tc->hdr->size);
899   if (NULL == buf)
900     {
901 #if DEBUG_CLIENT
902       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
903                   _("Could not submit request, not expecting to receive a response.\n"));
904 #endif
905       tc->rn (tc->rn_cls, NULL);
906       GNUNET_free (tc);
907       return 0;
908     }
909   GNUNET_assert (size >= msize);
910   memcpy (buf, tc->hdr, msize);
911   GNUNET_CLIENT_receive (tc->sock,
912                          tc->rn,
913                          tc->rn_cls,
914                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
915   GNUNET_free (tc);
916   return msize;
917 }
918
919
920 /**
921  * Convenience API that combines sending a request
922  * to the service and waiting for a response.
923  * If either operation times out, the callback
924  * will be called with a "NULL" response (in which
925  * case the connection should probably be destroyed).
926  *
927  * @param sock connection to use
928  * @param hdr message to transmit
929  * @param timeout when to give up (for both transmission
930  *         and for waiting for a response)
931  * @param auto_retry if the connection to the service dies, should we
932  *        automatically re-connect and retry (within the timeout period)
933  *        or should we immediately fail in this case?  Pass GNUNET_YES
934  *        if the caller does not care about temporary connection errors,
935  *        for example because the protocol is stateless
936  * @param rn function to call with the response
937  * @param rn_cls closure for rn 
938  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
939  *         is already pending
940  */
941 int
942 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
943                                          *sock,
944                                          const struct GNUNET_MessageHeader
945                                          *hdr,
946                                          struct GNUNET_TIME_Relative timeout,
947                                          int auto_retry,
948                                          GNUNET_CLIENT_MessageHandler rn,
949                                          void *rn_cls)
950 {
951   struct TransmitGetResponseContext *tc;
952   uint16_t msize;
953
954   if (NULL != sock->th)
955     return GNUNET_SYSERR;
956   GNUNET_assert (sock->tag == NULL);
957   msize = ntohs (hdr->size);
958   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
959   tc->sock = sock;
960   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
961   memcpy (&tc[1], hdr, msize);
962   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
963   tc->rn = rn;
964   tc->rn_cls = rn_cls;
965   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
966                                                    msize,
967                                                    timeout,
968                                                    auto_retry,
969                                                    &transmit_for_response,
970                                                    tc))
971     {
972       GNUNET_break (0);
973       GNUNET_free (tc);
974       return GNUNET_SYSERR;
975     }
976   sock->tag = tc;
977   return GNUNET_OK;
978 }
979
980
981
982 /*  end of client.c */