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