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