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