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