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