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