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