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