API change for Safey/ARM
[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 will automatically be
566  * disconnected.  Hence the "sock" shoud not
567  * be used by the caller after this call
568  * (calling this function frees "sock" after a while).
569  *
570  * @param sock the socket connected to the service
571  */
572 void
573 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
574 {
575   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
576                                            sizeof (struct
577                                                    GNUNET_MessageHeader),
578                                            GNUNET_TIME_UNIT_FOREVER_REL,
579                                            &write_shutdown, sock);
580 }
581
582
583 /**
584  * Report service unavailable.
585  */
586 static void
587 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
588                     GNUNET_SCHEDULER_Task task, void *task_cls)
589 {
590   GNUNET_SCHEDULER_add_continuation (s,
591                                      task,
592                                      task_cls,
593                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
594 }
595
596
597 /**
598  * Receive confirmation from test, service is up.
599  *
600  * @param cls closure
601  * @param msg message received, NULL on timeout or fatal error
602  */
603 static void
604 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
605 {
606   struct GNUNET_CLIENT_Connection *conn = cls;
607   /* We may want to consider looking at the reply in more
608      detail in the future, for example, is this the
609      correct service? FIXME! */
610   if (msg != NULL)
611     {
612 #if DEBUG_CLIENT
613       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
614                   "Received confirmation that service is running.\n");
615 #endif
616       GNUNET_SCHEDULER_add_continuation (conn->sched,
617                                          conn->test_cb,
618                                          conn->test_cb_cls,
619                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
620     }
621   else
622     {
623       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
624     }
625   GNUNET_CLIENT_disconnect (conn);
626 }
627
628
629 static size_t
630 write_test (void *cls, size_t size, void *buf)
631 {
632   struct GNUNET_MessageHeader *msg;
633
634   if (size < sizeof (struct GNUNET_MessageHeader))
635     {
636 #if DEBUG_CLIENT
637       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638                   _("Failure to transmit TEST request.\n"));
639 #endif
640       return 0;                 /* client disconnected */
641     }
642 #if DEBUG_CLIENT
643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644               "Transmitting `%s' request.\n", "TEST");
645 #endif
646   msg = (struct GNUNET_MessageHeader *) buf;
647   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
648   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
649   return sizeof (struct GNUNET_MessageHeader);
650 }
651
652
653 /**
654  * Wait until the service is running.
655  *
656  * @param sched scheduler to use
657  * @param service name of the service to wait for
658  * @param cfg configuration to use
659  * @param timeout how long to wait at most in ms
660  * @param task task to run if service is running
661  *        (reason will be "PREREQ_DONE" (service running)
662  *         or "TIMEOUT" (service not known to be running))
663  * @param task_cls closure for task
664  */
665 void
666 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
667                             const char *service,
668                             const struct GNUNET_CONFIGURATION_Handle *cfg,
669                             struct GNUNET_TIME_Relative timeout,
670                             GNUNET_SCHEDULER_Task task, void *task_cls)
671 {
672   struct GNUNET_CLIENT_Connection *conn;
673
674 #if DEBUG_CLIENT
675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
676               "Testing if service `%s' is running.\n", service);
677 #endif
678   conn = GNUNET_CLIENT_connect (sched, service, cfg);
679   if (conn == NULL)
680     {
681       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
682                   _
683                   ("Could not connect to service `%s', must not be running.\n"),
684                   service);
685       service_test_error (sched, task, task_cls);
686       return;
687     }
688   conn->test_cb = task;
689   conn->test_cb_cls = task_cls;
690   if (NULL ==
691       GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
692                                                sizeof (struct
693                                                        GNUNET_MessageHeader),
694                                                timeout, &write_test, NULL))
695     {
696       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
697                   _("Failure to transmit request to service `%s'\n"),
698                   service);
699       service_test_error (sched, task, task_cls);
700       GNUNET_CLIENT_disconnect (conn);
701       return;
702     }
703   GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
704 }
705
706
707 /**
708  * Connection notifies us about failure or success of
709  * a transmission request.  Either pass it on to our
710  * user or, if possible, retry.
711  *
712  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
713  * @param size number of bytes available for transmission
714  * @param buf where to write them
715  * @return number of bytes written to buf
716  */
717 static size_t client_notify (void *cls, size_t size, void *buf);
718
719
720 /**
721  * This task is run if we should re-try connection to the
722  * service after a while.
723  *
724  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
725  * @param tc unused
726  */
727 static void
728 client_delayed_retry (void *cls,
729                       const struct GNUNET_SCHEDULER_TaskContext *tc)
730 {
731   struct GNUNET_CLIENT_TransmitHandle *th = cls;
732
733   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
734   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
735     {
736 #if DEBUG_CLIENT
737       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
738                   "Transmission failed due to shutdown.\n");
739 #endif
740       th->sock->th = NULL;
741       th->notify (th->notify_cls, 0, NULL);
742       GNUNET_free (th);
743       return;
744     }
745   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
746                                                     th->size,
747                                                     GNUNET_TIME_absolute_get_remaining
748                                                     (th->timeout),
749                                                     &client_notify, th);
750   if (th->th == NULL)
751     {
752       GNUNET_break (0);
753       th->notify (th->notify_cls, 0, NULL);
754       GNUNET_free (th);
755       return;
756     }
757 }
758
759
760 /**
761  * Connection notifies us about failure or success of
762  * a transmission request.  Either pass it on to our
763  * user or, if possible, retry.
764  *
765  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
766  * @param size number of bytes available for transmission
767  * @param buf where to write them
768  * @return number of bytes written to buf
769  */
770 static size_t
771 client_notify (void *cls, size_t size, void *buf)
772 {
773   struct GNUNET_CLIENT_TransmitHandle *th = cls;
774   size_t ret;
775   struct GNUNET_TIME_Relative delay;
776
777   th->th = NULL;
778   th->sock->th = NULL;
779   if (buf == NULL)
780     {
781       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
782       delay.value /= 2;
783       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason (th->sock->sched))) ||
784            (GNUNET_YES != th->auto_retry) ||
785            (0 == --th->attempts_left) || 
786            (delay.value < 1) )
787         {
788 #if DEBUG_CLIENT
789           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790                       "Transmission failed %u times, giving up.\n",
791                       MAX_ATTEMPTS - th->attempts_left);
792 #endif
793           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
794           GNUNET_free (th);
795           return 0;
796         }
797       /* auto-retry */
798       GNUNET_CONNECTION_destroy (th->sock->sock);
799       th->sock->sock = do_connect (th->sock->sched,
800                                    th->sock->service_name, th->sock->cfg);
801       GNUNET_assert (NULL != th->sock->sock);
802       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
803                                          th->sock->ignore_shutdown);
804       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
805       th->sock->back_off 
806         = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
807                                     GNUNET_TIME_UNIT_SECONDS);
808 #if DEBUG_CLIENT
809       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810                   "Transmission failed %u times, trying again in %llums.\n",
811                   MAX_ATTEMPTS - th->attempts_left,
812                   (unsigned long long) delay.value);
813 #endif
814       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
815                                                          delay,
816                                                          &client_delayed_retry,
817                                                          th);
818       th->sock->th = th;
819       return 0;
820     }
821   GNUNET_assert (size >= th->size);
822   ret = th->notify (th->notify_cls, size, buf);
823   GNUNET_free (th);
824   return ret;
825 }
826
827
828 /**
829  * Ask the client to call us once the specified number of bytes
830  * are free in the transmission buffer.  May call the notify
831  * method immediately if enough space is available.
832  *
833  * @param sock connection to the service
834  * @param size number of bytes to send
835  * @param timeout after how long should we give up (and call
836  *        notify with buf NULL and size 0)?
837  * @param auto_retry if the connection to the service dies, should we
838  *        automatically re-connect and retry (within the timeout period)
839  *        or should we immediately fail in this case?  Pass GNUNET_YES
840  *        if the caller does not care about temporary connection errors,
841  *        for example because the protocol is stateless
842  * @param notify function to call
843  * @param notify_cls closure for notify
844  * @return NULL if our buffer will never hold size bytes,
845  *         a handle if the notify callback was queued (can be used to cancel)
846  */
847 struct GNUNET_CLIENT_TransmitHandle *
848 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
849                                      size_t size,
850                                      struct GNUNET_TIME_Relative timeout,
851                                      int auto_retry,
852                                      GNUNET_CONNECTION_TransmitReadyNotify
853                                      notify, void *notify_cls)
854 {
855   struct GNUNET_CLIENT_TransmitHandle *th;
856
857   if (NULL != sock->th)
858     return NULL;
859   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
860   th->sock = sock;
861   th->size = size;
862   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
863   th->auto_retry = auto_retry;
864   th->notify = notify;
865   th->notify_cls = notify_cls;
866   th->attempts_left = MAX_ATTEMPTS;
867   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
868                                                     size,
869                                                     timeout,
870                                                     &client_notify, th);
871   if (NULL == th->th)
872     {
873       GNUNET_break (0);
874       GNUNET_free (th);
875       return NULL;
876     }
877   sock->th = th;
878   return th;
879 }
880
881
882 /**
883  * Cancel a request for notification.
884  * 
885  * @param th handle from the original request.
886  */
887 void
888 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
889                                             GNUNET_CLIENT_TransmitHandle *th)
890 {
891   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
892     {
893       GNUNET_break (NULL == th->th);
894       GNUNET_SCHEDULER_cancel (th->sock->sched, th->reconnect_task);
895       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
896     }
897   else
898     {
899       GNUNET_break (NULL != th->th);
900       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
901     }
902   th->sock->th = NULL;
903   GNUNET_free (th);
904 }
905
906
907 /**
908  * Function called to notify a client about the socket
909  * begin ready to queue the message.  "buf" will be
910  * NULL and "size" zero if the socket was closed for
911  * writing in the meantime.
912  *
913  * @param cls closure of type "struct TransmitGetResponseContext*"
914  * @param size number of bytes available in buf
915  * @param buf where the callee should write the message
916  * @return number of bytes written to buf
917  */
918 static size_t
919 transmit_for_response (void *cls, size_t size, void *buf)
920 {
921   struct TransmitGetResponseContext *tc = cls;
922   uint16_t msize;
923
924   tc->sock->tag = NULL;
925   msize = ntohs (tc->hdr->size);
926   if (NULL == buf)
927     {
928 #if DEBUG_CLIENT
929       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930                   _("Could not submit request, not expecting to receive a response.\n"));
931 #endif
932       tc->rn (tc->rn_cls, NULL);
933       GNUNET_free (tc);
934       return 0;
935     }
936   GNUNET_assert (size >= msize);
937   memcpy (buf, tc->hdr, msize);
938   GNUNET_CLIENT_receive (tc->sock,
939                          tc->rn,
940                          tc->rn_cls,
941                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
942   GNUNET_free (tc);
943   return msize;
944 }
945
946
947 /**
948  * Convenience API that combines sending a request
949  * to the service and waiting for a response.
950  * If either operation times out, the callback
951  * will be called with a "NULL" response (in which
952  * case the connection should probably be destroyed).
953  *
954  * @param sock connection to use
955  * @param hdr message to transmit
956  * @param timeout when to give up (for both transmission
957  *         and for waiting for a response)
958  * @param auto_retry if the connection to the service dies, should we
959  *        automatically re-connect and retry (within the timeout period)
960  *        or should we immediately fail in this case?  Pass GNUNET_YES
961  *        if the caller does not care about temporary connection errors,
962  *        for example because the protocol is stateless
963  * @param rn function to call with the response
964  * @param rn_cls closure for rn 
965  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
966  *         is already pending
967  */
968 int
969 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
970                                          *sock,
971                                          const struct GNUNET_MessageHeader
972                                          *hdr,
973                                          struct GNUNET_TIME_Relative timeout,
974                                          int auto_retry,
975                                          GNUNET_CLIENT_MessageHandler rn,
976                                          void *rn_cls)
977 {
978   struct TransmitGetResponseContext *tc;
979   uint16_t msize;
980
981   if (NULL != sock->th)
982     return GNUNET_SYSERR;
983   GNUNET_assert (sock->tag == NULL);
984   msize = ntohs (hdr->size);
985   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
986   tc->sock = sock;
987   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
988   memcpy (&tc[1], hdr, msize);
989   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
990   tc->rn = rn;
991   tc->rn_cls = rn_cls;
992   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
993                                                    msize,
994                                                    timeout,
995                                                    auto_retry,
996                                                    &transmit_for_response,
997                                                    tc))
998     {
999       GNUNET_break (0);
1000       GNUNET_free (tc);
1001       return GNUNET_SYSERR;
1002     }
1003   sock->tag = tc;
1004   return GNUNET_OK;
1005 }
1006
1007
1008
1009 /*  end of client.c */