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