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