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