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