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