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