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