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