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