changed confs
[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, 
496                   "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n", 
497                   (unsigned int) available, 
498                   conn->sock == NULL ? "NULL" : "non-NULL", 
499                   STRERROR (errCode));
500 #endif
501       if (NULL != (receive_handler = conn->receiver_handler))
502         {
503           receive_handler_cls = conn->receiver_handler_cls;
504           conn->receiver_handler = NULL;
505           receive_handler (receive_handler_cls, NULL);
506         }
507       return;
508     }
509
510   /* FIXME: optimize for common fast case where buf contains the
511      entire message and we need no copying... */
512
513
514   /* slow path: append to array */
515   if (conn->received_size < conn->received_pos + available)
516     GNUNET_array_grow (conn->received_buf,
517                        conn->received_size, conn->received_pos + available);
518   memcpy (&conn->received_buf[conn->received_pos], buf, available);
519   conn->received_pos += available;
520   check_complete (conn);
521   /* check for timeout */
522   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
523   if (remaining.rel_value == 0)
524     {
525       /* signal timeout! */
526       conn->receiver_handler (conn->receiver_handler_cls, NULL);
527       return;
528     }
529   /* back to receive -- either for more data or to call callback! */
530   GNUNET_CLIENT_receive (conn,
531                          conn->receiver_handler,
532                          conn->receiver_handler_cls, remaining);
533 }
534
535
536 /**
537  * Continuation to call the receive callback.
538  *
539  * @param cls  our handle to the client connection
540  * @param tc scheduler context
541  */
542 static void
543 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
544 {
545   struct GNUNET_CLIENT_Connection *sock = cls;
546   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
547   const struct GNUNET_MessageHeader *cmsg =
548     (const struct GNUNET_MessageHeader *) sock->received_buf;
549   void *handler_cls = sock->receiver_handler_cls;
550   uint16_t msize = ntohs (cmsg->size);
551   char mbuf[msize];
552   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
553
554 #if DEBUG_CLIENT
555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
556               "Received message of type %u and size %u\n",
557               ntohs (cmsg->type),
558               msize);
559 #endif
560   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
561   GNUNET_assert (GNUNET_YES == sock->msg_complete);
562   GNUNET_assert (sock->received_pos >= msize);
563   memcpy (msg, cmsg, msize);
564   memmove (sock->received_buf,
565            &sock->received_buf[msize], sock->received_pos - msize);
566   sock->received_pos -= msize;
567   sock->msg_complete = GNUNET_NO;
568   sock->receiver_handler = NULL;
569   check_complete (sock);
570   if (handler != NULL)
571     handler (handler_cls, msg);
572 }
573
574
575 /**
576  * Read from the service.
577  *
578  * @param sock the service
579  * @param handler function to call with the message
580  * @param handler_cls closure for handler
581  * @param timeout how long to wait until timing out
582  */
583 void
584 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
585                        GNUNET_CLIENT_MessageHandler handler,
586                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
587 {
588   if (sock->sock == NULL)
589     {
590       /* already disconnected, fail instantly! */
591       GNUNET_break (0);         /* this should not happen in well-written code! */
592       handler (handler_cls, NULL);
593       return;
594     }
595   sock->receiver_handler = handler;
596   sock->receiver_handler_cls = handler_cls;
597   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
598   if (GNUNET_YES == sock->msg_complete)
599     {
600       sock->receive_task = GNUNET_SCHEDULER_add_after (GNUNET_SCHEDULER_NO_TASK,
601                                                        &receive_task, sock);
602     }
603   else
604     {
605       GNUNET_assert (sock->in_receive == GNUNET_NO);
606       sock->in_receive = GNUNET_YES;
607 #if DEBUG_CLIENT
608       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
609 #endif
610       GNUNET_CONNECTION_receive (sock->sock,
611                                  GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
612                                  timeout, &receive_helper, sock);
613     }
614 }
615
616
617 /**
618  * Report service unavailable.
619  */
620 static void
621 service_test_error (GNUNET_SCHEDULER_Task task, void *task_cls)
622 {
623   GNUNET_SCHEDULER_add_continuation (task,
624                                      task_cls,
625                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
626 }
627
628
629 /**
630  * Receive confirmation from test, service is up.
631  *
632  * @param cls closure
633  * @param msg message received, NULL on timeout or fatal error
634  */
635 static void
636 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
637 {
638   struct GNUNET_CLIENT_Connection *conn = cls;
639   /* We may want to consider looking at the reply in more
640      detail in the future, for example, is this the
641      correct service? FIXME! */
642   if (msg != NULL)
643     {
644 #if DEBUG_CLIENT
645       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
646                   "Received confirmation that service is running.\n");
647 #endif
648       GNUNET_SCHEDULER_add_continuation (conn->test_cb,
649                                          conn->test_cb_cls,
650                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
651     }
652   else
653     {
654       service_test_error (conn->test_cb, conn->test_cb_cls);
655     }
656   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
657 }
658
659
660 static size_t
661 write_test (void *cls, size_t size, void *buf)
662 {
663   struct GNUNET_CLIENT_Connection *conn = cls;
664   struct GNUNET_MessageHeader *msg;
665
666   if (size < sizeof (struct GNUNET_MessageHeader))
667     {
668 #if DEBUG_CLIENT
669       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
670                   _("Failure to transmit TEST request.\n"));
671 #endif
672       service_test_error (conn->test_cb, conn->test_cb_cls);
673       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
674       return 0;                 /* client disconnected */
675     }
676 #if DEBUG_CLIENT
677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
678               "Transmitting `%s' request.\n", "TEST");
679 #endif
680   msg = (struct GNUNET_MessageHeader *) buf;
681   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
682   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
683   GNUNET_CLIENT_receive (conn, 
684                          &confirm_handler, 
685                          conn, 
686                          GNUNET_TIME_absolute_get_remaining (conn->test_deadline));
687   return sizeof (struct GNUNET_MessageHeader);
688 }
689
690
691 /**
692  * Wait until the service is running.
693  *
694  * @param service name of the service to wait for
695  * @param cfg configuration to use
696  * @param timeout how long to wait at most in ms
697  * @param task task to run if service is running
698  *        (reason will be "PREREQ_DONE" (service running)
699  *         or "TIMEOUT" (service not known to be running))
700  * @param task_cls closure for task
701  */
702 void
703 GNUNET_CLIENT_service_test (const char *service,
704                             const struct GNUNET_CONFIGURATION_Handle *cfg,
705                             struct GNUNET_TIME_Relative timeout,
706                             GNUNET_SCHEDULER_Task task, void *task_cls)
707 {
708   struct GNUNET_CLIENT_Connection *conn;
709
710 #if DEBUG_CLIENT
711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
712               "Testing if service `%s' is running.\n", service);
713 #endif
714   conn = GNUNET_CLIENT_connect (service, cfg);
715   if (conn == NULL)
716     {
717       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
718                   _
719                   ("Could not connect to service `%s', must not be running.\n"),
720                   service);
721       service_test_error (task, task_cls);
722       return;
723     }
724   conn->test_cb = task;
725   conn->test_cb_cls = task_cls;
726   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
727
728   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
729                                                    sizeof (struct GNUNET_MessageHeader),
730                                                    timeout,
731                                                    GNUNET_YES,
732                                                    &write_test, conn))  
733     {
734       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
735                   _("Failure to transmit request to service `%s'\n"),
736                   service);
737       service_test_error (task, task_cls);
738       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
739       return;
740     }
741 }
742
743
744 /**
745  * Connection notifies us about failure or success of
746  * a transmission request.  Either pass it on to our
747  * user or, if possible, retry.
748  *
749  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
750  * @param size number of bytes available for transmission
751  * @param buf where to write them
752  * @return number of bytes written to buf
753  */
754 static size_t client_notify (void *cls, size_t size, void *buf);
755
756
757 /**
758  * This task is run if we should re-try connection to the
759  * service after a while.
760  *
761  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
762  * @param tc unused
763  */
764 static void
765 client_delayed_retry (void *cls,
766                       const struct GNUNET_SCHEDULER_TaskContext *tc)
767 {
768   struct GNUNET_CLIENT_TransmitHandle *th = cls;
769
770   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
771   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
772     {
773 #if DEBUG_CLIENT
774       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775                   "Transmission failed due to shutdown.\n");
776 #endif
777       th->sock->th = NULL;
778       th->notify (th->notify_cls, 0, NULL);
779       GNUNET_free (th);
780       return;
781     }
782   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
783                                                     th->size,
784                                                     GNUNET_TIME_absolute_get_remaining
785                                                     (th->timeout),
786                                                     &client_notify, th);
787   if (th->th == NULL)
788     {
789       GNUNET_break (0);
790       th->notify (th->notify_cls, 0, NULL);
791       GNUNET_free (th);
792       return;
793     }
794 }
795
796
797 /**
798  * Connection notifies us about failure or success of a transmission
799  * request.  Either pass it on to our user or, if possible, retry.
800  *
801  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
802  * @param size number of bytes available for transmission
803  * @param buf where to write them
804  * @return number of bytes written to buf
805  */
806 static size_t
807 client_notify (void *cls, size_t size, void *buf)
808 {
809   struct GNUNET_CLIENT_TransmitHandle *th = cls;
810   size_t ret;
811   struct GNUNET_TIME_Relative delay;
812
813   th->th = NULL;
814   th->sock->th = NULL;
815   if (buf == NULL)
816     {
817       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
818       delay.rel_value /= 2;
819       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
820            (GNUNET_YES != th->auto_retry) ||
821            (0 == --th->attempts_left) || 
822            (delay.rel_value < 1) )
823         {
824 #if DEBUG_CLIENT
825           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
826                       "Transmission failed %u times, giving up.\n",
827                       MAX_ATTEMPTS - th->attempts_left);
828 #endif
829           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
830           GNUNET_free (th);
831           return 0;
832         }
833       /* auto-retry */
834       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
835       th->sock->sock = do_connect (th->sock->service_name,
836                                    th->sock->cfg,
837                                    th->sock->attempts++);
838       GNUNET_assert (NULL != th->sock->sock);
839       GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
840                                          th->sock->ignore_shutdown);
841       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
842       th->sock->back_off 
843           = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
844                                     GNUNET_TIME_UNIT_SECONDS);
845 #if DEBUG_CLIENT
846       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                   "Transmission failed %u times, trying again in %llums.\n",
848                   MAX_ATTEMPTS - th->attempts_left,
849                   (unsigned long long) delay.rel_value);
850 #endif
851       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (delay,
852                                                          &client_delayed_retry,
853                                                          th);
854       th->sock->th = th;
855       return 0;
856     }
857   GNUNET_assert (size >= th->size);
858   ret = th->notify (th->notify_cls, size, buf);
859   GNUNET_free (th);
860   return ret;
861 }
862
863
864 /**
865  * Ask the client to call us once the specified number of bytes
866  * are free in the transmission buffer.  May call the notify
867  * method immediately if enough space is available.
868  *
869  * @param sock connection to the service
870  * @param size number of bytes to send
871  * @param timeout after how long should we give up (and call
872  *        notify with buf NULL and size 0)?
873  * @param auto_retry if the connection to the service dies, should we
874  *        automatically re-connect and retry (within the timeout period)
875  *        or should we immediately fail in this case?  Pass GNUNET_YES
876  *        if the caller does not care about temporary connection errors,
877  *        for example because the protocol is stateless
878  * @param notify function to call
879  * @param notify_cls closure for notify
880  * @return NULL if our buffer will never hold size bytes,
881  *         a handle if the notify callback was queued (can be used to cancel)
882  */
883 struct GNUNET_CLIENT_TransmitHandle *
884 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
885                                      size_t size,
886                                      struct GNUNET_TIME_Relative timeout,
887                                      int auto_retry,
888                                      GNUNET_CONNECTION_TransmitReadyNotify
889                                      notify, void *notify_cls)
890 {
891   struct GNUNET_CLIENT_TransmitHandle *th;
892
893   if (NULL != sock->th)
894     return NULL;
895   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
896   th->sock = sock;
897   th->size = size;
898   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
899   th->auto_retry = auto_retry;
900   th->notify = notify;
901   th->notify_cls = notify_cls;
902   th->attempts_left = MAX_ATTEMPTS;
903   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
904                                                     size,
905                                                     timeout,
906                                                     &client_notify, th);
907   if (NULL == th->th)
908     {
909       GNUNET_break (0);
910       GNUNET_free (th);
911       return NULL;
912     }
913   sock->th = th;
914   return th;
915 }
916
917
918 /**
919  * Cancel a request for notification.
920  * 
921  * @param th handle from the original request.
922  */
923 void
924 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
925                                             GNUNET_CLIENT_TransmitHandle *th)
926 {
927   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
928     {
929       GNUNET_break (NULL == th->th);
930       GNUNET_SCHEDULER_cancel (th->reconnect_task);
931       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
932     }
933   else
934     {
935       GNUNET_assert (NULL != th->th);
936       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
937     }
938   th->sock->th = NULL;
939   GNUNET_free (th);
940 }
941
942
943 /**
944  * Function called to notify a client about the socket
945  * begin ready to queue the message.  "buf" will be
946  * NULL and "size" zero if the socket was closed for
947  * writing in the meantime.
948  *
949  * @param cls closure of type "struct TransmitGetResponseContext*"
950  * @param size number of bytes available in buf
951  * @param buf where the callee should write the message
952  * @return number of bytes written to buf
953  */
954 static size_t
955 transmit_for_response (void *cls, size_t size, void *buf)
956 {
957   struct TransmitGetResponseContext *tc = cls;
958   uint16_t msize;
959
960   tc->sock->tag = NULL;
961   msize = ntohs (tc->hdr->size);
962   if (NULL == buf)
963     {
964 #if DEBUG_CLIENT
965       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966                   _("Could not submit request, not expecting to receive a response.\n"));
967 #endif
968       tc->rn (tc->rn_cls, NULL);
969       GNUNET_free (tc);
970       return 0;
971     }
972   GNUNET_assert (size >= msize);
973   memcpy (buf, tc->hdr, msize);
974   GNUNET_CLIENT_receive (tc->sock,
975                          tc->rn,
976                          tc->rn_cls,
977                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
978   GNUNET_free (tc);
979   return msize;
980 }
981
982
983 /**
984  * Convenience API that combines sending a request
985  * to the service and waiting for a response.
986  * If either operation times out, the callback
987  * will be called with a "NULL" response (in which
988  * case the connection should probably be destroyed).
989  *
990  * @param sock connection to use
991  * @param hdr message to transmit
992  * @param timeout when to give up (for both transmission
993  *         and for waiting for a response)
994  * @param auto_retry if the connection to the service dies, should we
995  *        automatically re-connect and retry (within the timeout period)
996  *        or should we immediately fail in this case?  Pass GNUNET_YES
997  *        if the caller does not care about temporary connection errors,
998  *        for example because the protocol is stateless
999  * @param rn function to call with the response
1000  * @param rn_cls closure for rn 
1001  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1002  *         is already pending
1003  */
1004 int
1005 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
1006                                          *sock,
1007                                          const struct GNUNET_MessageHeader
1008                                          *hdr,
1009                                          struct GNUNET_TIME_Relative timeout,
1010                                          int auto_retry,
1011                                          GNUNET_CLIENT_MessageHandler rn,
1012                                          void *rn_cls)
1013 {
1014   struct TransmitGetResponseContext *tc;
1015   uint16_t msize;
1016
1017   if (NULL != sock->th)
1018     return GNUNET_SYSERR;
1019   GNUNET_assert (sock->tag == NULL);
1020   msize = ntohs (hdr->size);
1021   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1022   tc->sock = sock;
1023   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1024   memcpy (&tc[1], hdr, msize);
1025   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1026   tc->rn = rn;
1027   tc->rn_cls = rn_cls;
1028   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
1029                                                    msize,
1030                                                    timeout,
1031                                                    auto_retry,
1032                                                    &transmit_for_response,
1033                                                    tc))
1034     {
1035       GNUNET_break (0);
1036       GNUNET_free (tc);
1037       return GNUNET_SYSERR;
1038     }
1039   sock->tag = tc;
1040   return GNUNET_OK;
1041 }
1042
1043
1044
1045 /*  end of client.c */