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