2 This file is part of GNUnet.
3 (C) 2001, 2002, 2006, 2008, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
23 * @brief code for access to services
24 * @author Christian Grothoff
26 * Generic TCP code for reliable, record-oriented TCP
27 * connections between clients and service providers.
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"
39 * How often do we re-try tranmsitting requests before giving up?
40 * Note that if we succeeded transmitting a request but failed to read
41 * a response, we do NOT re-try.
43 #define MAX_ATTEMPTS 50
45 #define LOG(kind,...) GNUNET_log_from (kind, "util",__VA_ARGS__)
48 * Handle for a transmission request.
50 struct GNUNET_CLIENT_TransmitHandle
55 struct GNUNET_CLIENT_Connection *sock;
58 * Function to call to get the data for transmission.
60 GNUNET_CONNECTION_TransmitReadyNotify notify;
68 * Handle to the transmission with the underlying
71 struct GNUNET_CONNECTION_TransmitHandle *th;
74 * If we are re-trying and are delaying to do so,
75 * handle to the scheduled task managing the delay.
77 GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
80 * Timeout for the operation overall.
82 struct GNUNET_TIME_Absolute timeout;
85 * Number of bytes requested.
90 * Are we allowed to re-try to connect without telling
91 * the user (of this API) about the connection troubles?
96 * Number of attempts left for transmitting the request. We may
97 * fail the first time (say because the service is not yet up), in
98 * which case (if auto_retry is set) we wait a bit and re-try
99 * (timeout permitting).
101 unsigned int attempts_left;
107 * Context for processing
108 * "GNUNET_CLIENT_transmit_and_get_response" requests.
110 struct TransmitGetResponseContext
115 struct GNUNET_CLIENT_Connection *sock;
118 * Message to transmit; do not free, allocated
119 * right after this struct.
121 const struct GNUNET_MessageHeader *hdr;
126 struct GNUNET_TIME_Absolute timeout;
129 * Function to call when done.
131 GNUNET_CLIENT_MessageHandler rn;
140 * Struct to refer to a GNUnet TCP connection.
141 * This is more than just a socket because if the server
142 * drops the connection, the client automatically tries
143 * to reconnect (and for that needs connection information).
145 struct GNUNET_CLIENT_Connection
149 * the socket handle, NULL if not live
151 struct GNUNET_CONNECTION_Handle *sock;
156 const struct GNUNET_CONFIGURATION_Handle *cfg;
159 * Name of the service we interact with.
164 * Context of a transmit_and_get_response operation, NULL
165 * if no such operation is pending.
167 struct TransmitGetResponseContext *tag;
170 * Handler for current receiver task.
172 GNUNET_CLIENT_MessageHandler receiver_handler;
175 * Closure for receiver_handler.
177 void *receiver_handler_cls;
180 * Handle for a pending transmission request, NULL if there is
183 struct GNUNET_CLIENT_TransmitHandle *th;
186 * Handler for service test completion (NULL unless in service_test)
188 GNUNET_SCHEDULER_Task test_cb;
191 * Deadline for calling 'test_cb'.
193 struct GNUNET_TIME_Absolute test_deadline;
196 * If we are re-trying and are delaying to do so,
197 * handle to the scheduled task managing the delay.
199 GNUNET_SCHEDULER_TaskIdentifier receive_task;
202 * Closure for test_cb (NULL unless in service_test)
207 * Buffer for received message.
212 * Timeout for receiving a response (absolute time).
214 struct GNUNET_TIME_Absolute receive_timeout;
217 * Current value for our incremental back-off (for
220 struct GNUNET_TIME_Relative back_off;
223 * Number of bytes in received_buf that are valid.
228 * Size of received_buf.
230 unsigned int received_size;
233 * Do we have a complete response in received_buf?
238 * Are we currently busy doing receive-processing?
239 * GNUNET_YES if so, GNUNET_NO if not.
244 * How often have we tried to connect?
246 unsigned int attempts;
252 * Try to connect to the service.
254 * @param service_name name of service to connect to
255 * @param cfg configuration to use
256 * @param attempt counter used to alternate between IP and UNIX domain sockets
257 * @return NULL on error
259 static struct GNUNET_CONNECTION_Handle *
260 do_connect (const char *service_name,
261 const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned int attempt)
263 struct GNUNET_CONNECTION_Handle *sock;
266 unsigned long long port;
270 if (0 == (attempt % 2))
272 /* on even rounds, try UNIX */
274 if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH", &unixpath)) && (0 < strlen (unixpath))) /* We have a non-NULL unixpath, does that mean it's valid? */
276 sock = GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
279 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to unixpath `%s'!\n",
281 GNUNET_free (unixpath);
285 GNUNET_free_non_null (unixpath);
290 GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
293 GNUNET_CONFIGURATION_get_value_number (cfg, service_name, "PORT", &port))
296 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "HOSTNAME",
299 LOG (GNUNET_ERROR_TYPE_WARNING,
301 ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
305 if (0 == strlen (hostname))
307 GNUNET_free (hostname);
308 LOG (GNUNET_ERROR_TYPE_WARNING,
309 _("Need a non-empty hostname for service `%s'.\n"), service_name);
315 /* unspecified means 0 (disabled) */
322 if (0 != (attempt % 2))
327 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH",
329 (0 < strlen (unixpath)))
332 GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
335 GNUNET_free (unixpath);
336 GNUNET_free_non_null (hostname);
340 GNUNET_free_non_null (unixpath);
343 LOG (GNUNET_ERROR_TYPE_DEBUG,
344 "Port is 0 for service `%s', UNIXPATH did not work, returning NULL!\n",
346 GNUNET_free_non_null (hostname);
350 sock = GNUNET_CONNECTION_create_from_connect (cfg, hostname, port);
351 GNUNET_free (hostname);
357 * Get a connection with a service.
359 * @param service_name name of the service
360 * @param cfg configuration to use
361 * @return NULL on error (service unknown to configuration)
363 struct GNUNET_CLIENT_Connection *
364 GNUNET_CLIENT_connect (const char *service_name,
365 const struct GNUNET_CONFIGURATION_Handle *cfg)
367 struct GNUNET_CLIENT_Connection *ret;
368 struct GNUNET_CONNECTION_Handle *sock;
370 sock = do_connect (service_name, cfg, 0);
371 ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
374 ret->service_name = GNUNET_strdup (service_name);
376 ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
382 * Destroy connection with the service. This will automatically
383 * cancel any pending "receive" request (however, the handler will
384 * *NOT* be called, not even with a NULL message). Any pending
385 * transmission request will also be cancelled UNLESS the callback for
386 * the transmission request has already been called, in which case the
387 * transmission 'finish_pending_write' argument determines whether or
388 * not the write is guaranteed to complete before the socket is fully
389 * destroyed (unless, of course, there is an error with the server in
390 * which case the message may still be lost).
392 * @param finish_pending_write should a transmission already passed to the
393 * handle be completed?
394 * @param sock handle to the service connection
397 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
398 int finish_pending_write)
400 if (sock->in_receive == GNUNET_YES)
402 GNUNET_CONNECTION_receive_cancel (sock->sock);
403 sock->in_receive = GNUNET_NO;
405 if (sock->th != NULL)
407 GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
410 if (NULL != sock->sock)
412 GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
415 if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
417 GNUNET_SCHEDULER_cancel (sock->receive_task);
418 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
420 if (sock->tag != NULL)
422 GNUNET_free (sock->tag);
425 sock->receiver_handler = NULL;
426 GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
427 GNUNET_free (sock->service_name);
433 * Check if message is complete
436 check_complete (struct GNUNET_CLIENT_Connection *conn)
438 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
439 (conn->received_pos >=
440 ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
442 conn->msg_complete = GNUNET_YES;
447 * Callback function for data received from the network. Note that
448 * both "available" and "errCode" would be 0 if the read simply timed out.
451 * @param buf pointer to received data
452 * @param available number of bytes availabe in "buf",
453 * possibly 0 (on errors)
454 * @param addr address of the sender
455 * @param addrlen size of addr
456 * @param errCode value of errno (on errors receiving)
459 receive_helper (void *cls, const void *buf, size_t available,
460 const struct sockaddr *addr, socklen_t addrlen, int errCode)
462 struct GNUNET_CLIENT_Connection *conn = cls;
463 struct GNUNET_TIME_Relative remaining;
464 GNUNET_CLIENT_MessageHandler receive_handler;
465 void *receive_handler_cls;
467 GNUNET_assert (conn->msg_complete == GNUNET_NO);
468 conn->in_receive = GNUNET_NO;
469 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
471 /* signal timeout! */
472 LOG (GNUNET_ERROR_TYPE_DEBUG,
473 "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n",
474 (unsigned int) available, conn->sock == NULL ? "NULL" : "non-NULL",
476 if (NULL != (receive_handler = conn->receiver_handler))
478 receive_handler_cls = conn->receiver_handler_cls;
479 conn->receiver_handler = NULL;
480 receive_handler (receive_handler_cls, NULL);
485 /* FIXME: optimize for common fast case where buf contains the
486 * entire message and we need no copying... */
489 /* slow path: append to array */
490 if (conn->received_size < conn->received_pos + available)
491 GNUNET_array_grow (conn->received_buf, conn->received_size,
492 conn->received_pos + available);
493 memcpy (&conn->received_buf[conn->received_pos], buf, available);
494 conn->received_pos += available;
495 check_complete (conn);
496 /* check for timeout */
497 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
498 if (remaining.rel_value == 0)
500 /* signal timeout! */
501 if (NULL != conn->receiver_handler)
502 conn->receiver_handler (conn->receiver_handler_cls, NULL);
505 /* back to receive -- either for more data or to call callback! */
506 GNUNET_CLIENT_receive (conn, conn->receiver_handler,
507 conn->receiver_handler_cls, remaining);
512 * Continuation to call the receive callback.
514 * @param cls our handle to the client connection
515 * @param tc scheduler context
518 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
520 struct GNUNET_CLIENT_Connection *sock = cls;
521 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
522 const struct GNUNET_MessageHeader *cmsg =
523 (const struct GNUNET_MessageHeader *) sock->received_buf;
524 void *handler_cls = sock->receiver_handler_cls;
525 uint16_t msize = ntohs (cmsg->size);
527 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
529 LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u and size %u\n",
530 ntohs (cmsg->type), msize);
531 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
532 GNUNET_assert (GNUNET_YES == sock->msg_complete);
533 GNUNET_assert (sock->received_pos >= msize);
534 memcpy (msg, cmsg, msize);
535 memmove (sock->received_buf, &sock->received_buf[msize],
536 sock->received_pos - msize);
537 sock->received_pos -= msize;
538 sock->msg_complete = GNUNET_NO;
539 sock->receiver_handler = NULL;
540 check_complete (sock);
542 handler (handler_cls, msg);
547 * Read from the service.
549 * @param sock the service
550 * @param handler function to call with the message
551 * @param handler_cls closure for handler
552 * @param timeout how long to wait until timing out
555 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
556 GNUNET_CLIENT_MessageHandler handler, void *handler_cls,
557 struct GNUNET_TIME_Relative timeout)
559 if (sock->sock == NULL)
561 /* already disconnected, fail instantly! */
562 GNUNET_break (0); /* this should not happen in well-written code! */
564 handler (handler_cls, NULL);
567 sock->receiver_handler = handler;
568 sock->receiver_handler_cls = handler_cls;
569 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
570 if (GNUNET_YES == sock->msg_complete)
572 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->receive_task);
573 sock->receive_task = GNUNET_SCHEDULER_add_now (&receive_task, sock);
577 GNUNET_assert (sock->in_receive == GNUNET_NO);
578 sock->in_receive = GNUNET_YES;
579 LOG (GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
580 GNUNET_CONNECTION_receive (sock->sock, GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
581 timeout, &receive_helper, sock);
587 * Report service unavailable.
590 service_test_error (GNUNET_SCHEDULER_Task task, void *task_cls)
592 GNUNET_SCHEDULER_add_continuation (task, task_cls,
593 GNUNET_SCHEDULER_REASON_TIMEOUT);
598 * Receive confirmation from test, service is up.
601 * @param msg message received, NULL on timeout or fatal error
604 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
606 struct GNUNET_CLIENT_Connection *conn = cls;
608 /* We may want to consider looking at the reply in more
609 * detail in the future, for example, is this the
610 * correct service? FIXME! */
613 LOG (GNUNET_ERROR_TYPE_DEBUG,
614 "Received confirmation that service is running.\n");
615 GNUNET_SCHEDULER_add_continuation (conn->test_cb, conn->test_cb_cls,
616 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
620 service_test_error (conn->test_cb, conn->test_cb_cls);
622 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
627 * Send the 'TEST' message to the service. If successful, prepare to
630 * @param cls the 'struct GNUNET_CLIENT_Connection' of the connection to test
631 * @param size number of bytes available in buf
632 * @param buf where to write the message
633 * @return number of bytes written to buf
636 write_test (void *cls, size_t size, void *buf)
638 struct GNUNET_CLIENT_Connection *conn = cls;
639 struct GNUNET_MessageHeader *msg;
641 if (size < sizeof (struct GNUNET_MessageHeader))
643 LOG (GNUNET_ERROR_TYPE_DEBUG, _("Failure to transmit TEST request.\n"));
644 service_test_error (conn->test_cb, conn->test_cb_cls);
645 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
646 return 0; /* client disconnected */
648 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "TEST");
649 msg = (struct GNUNET_MessageHeader *) buf;
650 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
651 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
652 GNUNET_CLIENT_receive (conn, &confirm_handler, conn,
653 GNUNET_TIME_absolute_get_remaining
654 (conn->test_deadline));
655 return sizeof (struct GNUNET_MessageHeader);
660 * Test if the service is running. If we are given a UNIXPATH or a local address,
661 * we do this NOT by trying to connect to the service, but by trying to BIND to
662 * the same port. If the BIND fails, we know the service is running.
664 * @param service name of the service to wait for
665 * @param cfg configuration to use
666 * @param timeout how long to wait at most
667 * @param task task to run if service is running
668 * (reason will be "PREREQ_DONE" (service running)
669 * or "TIMEOUT" (service not known to be running))
670 * @param task_cls closure for task
673 GNUNET_CLIENT_service_test (const char *service,
674 const struct GNUNET_CONFIGURATION_Handle *cfg,
675 struct GNUNET_TIME_Relative timeout,
676 GNUNET_SCHEDULER_Task task, void *task_cls)
679 unsigned long long port;
680 struct GNUNET_NETWORK_Handle *sock;
681 struct GNUNET_CLIENT_Connection *conn;
683 LOG (GNUNET_ERROR_TYPE_DEBUG, "Testing if service `%s' is running.\n",
687 /* probe UNIX support */
688 struct sockaddr_un s_un;
693 if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, service, "UNIXPATH", &unixpath)) && (0 < strlen (unixpath))) /* We have a non-NULL unixpath, does that mean it's valid? */
695 if (strlen (unixpath) >= sizeof (s_un.sun_path))
697 LOG (GNUNET_ERROR_TYPE_WARNING,
698 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
699 sizeof (s_un.sun_path));
703 sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
706 memset (&s_un, 0, sizeof (s_un));
707 s_un.sun_family = AF_UNIX;
708 slen = strlen (unixpath) + 1;
709 if (slen >= sizeof (s_un.sun_path))
710 slen = sizeof (s_un.sun_path) - 1;
711 memcpy (s_un.sun_path, unixpath, slen);
712 s_un.sun_path[slen] = '\0';
713 slen = sizeof (struct sockaddr_un);
715 s_un.sun_path[0] = '\0';
717 #if HAVE_SOCKADDR_IN_SIN_LEN
718 s_un.sun_len = (u_char) slen;
721 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_un,
724 /* failed to bind => service must be running */
725 GNUNET_free (unixpath);
726 (void) GNUNET_NETWORK_socket_close (sock);
727 GNUNET_SCHEDULER_add_continuation (task, task_cls,
728 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
731 (void) GNUNET_NETWORK_socket_close (sock);
736 GNUNET_free_non_null (unixpath);
742 GNUNET_CONFIGURATION_get_value_number (cfg, service, "PORT", &port)) ||
745 GNUNET_CONFIGURATION_get_value_string (cfg, service, "HOSTNAME",
748 /* UNIXPATH failed (if possible) AND IP failed => error */
749 service_test_error (task, task_cls);
753 if (0 == strcmp ("localhost", hostname)
759 /* can test using 'bind' */
760 struct sockaddr_in s_in;
762 memset (&s_in, 0, sizeof (s_in));
763 #if HAVE_SOCKADDR_IN_SIN_LEN
764 s_in.sin_len = sizeof (struct sockaddr_in);
766 s_in.sin_family = AF_INET;
767 s_in.sin_port = htons (port);
769 sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
773 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in,
776 /* failed to bind => service must be running */
777 GNUNET_free (hostname);
778 (void) GNUNET_NETWORK_socket_close (sock);
779 GNUNET_SCHEDULER_add_continuation (task, task_cls,
780 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
783 (void) GNUNET_NETWORK_socket_close (sock);
787 if (0 == strcmp ("ip6-localhost", hostname)
793 /* can test using 'bind' */
794 struct sockaddr_in6 s_in6;
796 memset (&s_in6, 0, sizeof (s_in6));
797 #if HAVE_SOCKADDR_IN_SIN_LEN
798 s_in6.sin6_len = sizeof (struct sockaddr_in6);
800 s_in6.sin6_family = AF_INET6;
801 s_in6.sin6_port = htons (port);
803 sock = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
807 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in6,
810 /* failed to bind => service must be running */
811 GNUNET_free (hostname);
812 (void) GNUNET_NETWORK_socket_close (sock);
813 GNUNET_SCHEDULER_add_continuation (task, task_cls,
814 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
817 (void) GNUNET_NETWORK_socket_close (sock);
821 if (((0 == strcmp ("localhost", hostname)) ||
822 (0 == strcmp ("ip6-localhost", hostname)))
828 /* all binds succeeded => claim service not running right now */
829 GNUNET_free_non_null (hostname);
830 service_test_error (task, task_cls);
833 GNUNET_free_non_null (hostname);
835 /* non-localhost, try 'connect' method */
836 conn = GNUNET_CLIENT_connect (service, cfg);
839 LOG (GNUNET_ERROR_TYPE_INFO,
840 _("Could not connect to service `%s', must not be running.\n"),
842 service_test_error (task, task_cls);
845 conn->test_cb = task;
846 conn->test_cb_cls = task_cls;
847 conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
850 GNUNET_CLIENT_notify_transmit_ready (conn,
851 sizeof (struct GNUNET_MessageHeader),
852 timeout, GNUNET_YES, &write_test,
855 LOG (GNUNET_ERROR_TYPE_WARNING,
856 _("Failure to transmit request to service `%s'\n"), service);
857 service_test_error (task, task_cls);
858 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
865 * Connection notifies us about failure or success of
866 * a transmission request. Either pass it on to our
867 * user or, if possible, retry.
869 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
870 * @param size number of bytes available for transmission
871 * @param buf where to write them
872 * @return number of bytes written to buf
875 client_notify (void *cls, size_t size, void *buf);
879 * This task is run if we should re-try connection to the
880 * service after a while.
882 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
886 client_delayed_retry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
888 struct GNUNET_CLIENT_TransmitHandle *th = cls;
889 struct GNUNET_TIME_Relative delay;
891 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
892 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
894 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission failed due to shutdown.\n");
896 th->notify (th->notify_cls, 0, NULL);
901 do_connect (th->sock->service_name, th->sock->cfg, th->sock->attempts++);
902 if (NULL == th->sock->sock)
904 /* could happen if we're out of sockets */
906 GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
907 (th->timeout), th->sock->back_off);
909 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
910 (th->sock->back_off, 2),
911 GNUNET_TIME_UNIT_SECONDS);
912 LOG (GNUNET_ERROR_TYPE_DEBUG,
913 "Transmission failed %u times, trying again in %llums.\n",
914 MAX_ATTEMPTS - th->attempts_left,
915 (unsigned long long) delay.rel_value);
917 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
921 GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock, th->size,
922 GNUNET_TIME_absolute_get_remaining
923 (th->timeout), &client_notify,
929 th->notify (th->notify_cls, 0, NULL);
937 * Connection notifies us about failure or success of a transmission
938 * request. Either pass it on to our user or, if possible, retry.
940 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
941 * @param size number of bytes available for transmission
942 * @param buf where to write them
943 * @return number of bytes written to buf
946 client_notify (void *cls, size_t size, void *buf)
948 struct GNUNET_CLIENT_TransmitHandle *th = cls;
950 struct GNUNET_TIME_Relative delay;
956 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
957 delay.rel_value /= 2;
959 (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
960 (GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
961 (delay.rel_value < 1))
963 LOG (GNUNET_ERROR_TYPE_DEBUG,
964 "Transmission failed %u times, giving up.\n",
965 MAX_ATTEMPTS - th->attempts_left);
966 GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
971 LOG (GNUNET_ERROR_TYPE_DEBUG,
972 "Failed to connect to `%s', automatically trying again.\n",
973 th->sock->service_name);
974 GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
975 th->sock->sock = NULL;
976 delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
978 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
979 (th->sock->back_off, 2),
980 GNUNET_TIME_UNIT_SECONDS);
981 LOG (GNUNET_ERROR_TYPE_DEBUG,
982 "Transmission failed %u times, trying again in %llums.\n",
983 MAX_ATTEMPTS - th->attempts_left,
984 (unsigned long long) delay.rel_value);
987 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
990 GNUNET_assert (size >= th->size);
991 ret = th->notify (th->notify_cls, size, buf);
998 * Ask the client to call us once the specified number of bytes
999 * are free in the transmission buffer. May call the notify
1000 * method immediately if enough space is available.
1002 * @param sock connection to the service
1003 * @param size number of bytes to send
1004 * @param timeout after how long should we give up (and call
1005 * notify with buf NULL and size 0)?
1006 * @param auto_retry if the connection to the service dies, should we
1007 * automatically re-connect and retry (within the timeout period)
1008 * or should we immediately fail in this case? Pass GNUNET_YES
1009 * if the caller does not care about temporary connection errors,
1010 * for example because the protocol is stateless
1011 * @param notify function to call
1012 * @param notify_cls closure for notify
1013 * @return NULL if our buffer will never hold size bytes,
1014 * a handle if the notify callback was queued (can be used to cancel)
1016 struct GNUNET_CLIENT_TransmitHandle *
1017 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1019 struct GNUNET_TIME_Relative timeout,
1021 GNUNET_CONNECTION_TransmitReadyNotify
1022 notify, void *notify_cls)
1024 struct GNUNET_CLIENT_TransmitHandle *th;
1026 if (NULL != sock->th)
1028 /* If this breaks, you most likley called this function twice without waiting
1029 * for completion or canceling the request */
1033 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1036 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1037 th->auto_retry = auto_retry;
1038 th->notify = notify;
1039 th->notify_cls = notify_cls;
1040 th->attempts_left = MAX_ATTEMPTS;
1042 if (sock->sock == NULL)
1044 th->reconnect_task =
1045 GNUNET_SCHEDULER_add_delayed (sock->back_off, &client_delayed_retry,
1052 GNUNET_CONNECTION_notify_transmit_ready (sock->sock, size, timeout,
1053 &client_notify, th);
1067 * Cancel a request for notification.
1069 * @param th handle from the original request.
1072 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1075 if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1077 GNUNET_assert (NULL == th->th);
1078 GNUNET_SCHEDULER_cancel (th->reconnect_task);
1079 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1083 GNUNET_assert (NULL != th->th);
1084 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1086 th->sock->th = NULL;
1092 * Function called to notify a client about the socket
1093 * begin ready to queue the message. "buf" will be
1094 * NULL and "size" zero if the socket was closed for
1095 * writing in the meantime.
1097 * @param cls closure of type "struct TransmitGetResponseContext*"
1098 * @param size number of bytes available in buf
1099 * @param buf where the callee should write the message
1100 * @return number of bytes written to buf
1103 transmit_for_response (void *cls, size_t size, void *buf)
1105 struct TransmitGetResponseContext *tc = cls;
1108 tc->sock->tag = NULL;
1109 msize = ntohs (tc->hdr->size);
1112 LOG (GNUNET_ERROR_TYPE_DEBUG,
1113 _("Could not submit request, not expecting to receive a response.\n"));
1115 tc->rn (tc->rn_cls, NULL);
1119 GNUNET_assert (size >= msize);
1120 memcpy (buf, tc->hdr, msize);
1121 GNUNET_CLIENT_receive (tc->sock, tc->rn, tc->rn_cls,
1122 GNUNET_TIME_absolute_get_remaining (tc->timeout));
1129 * Convenience API that combines sending a request
1130 * to the service and waiting for a response.
1131 * If either operation times out, the callback
1132 * will be called with a "NULL" response (in which
1133 * case the connection should probably be destroyed).
1135 * @param sock connection to use
1136 * @param hdr message to transmit
1137 * @param timeout when to give up (for both transmission
1138 * and for waiting for a response)
1139 * @param auto_retry if the connection to the service dies, should we
1140 * automatically re-connect and retry (within the timeout period)
1141 * or should we immediately fail in this case? Pass GNUNET_YES
1142 * if the caller does not care about temporary connection errors,
1143 * for example because the protocol is stateless
1144 * @param rn function to call with the response
1145 * @param rn_cls closure for rn
1146 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1147 * is already pending
1150 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
1151 const struct GNUNET_MessageHeader *hdr,
1152 struct GNUNET_TIME_Relative timeout,
1154 GNUNET_CLIENT_MessageHandler rn,
1157 struct TransmitGetResponseContext *tc;
1160 if (NULL != sock->th)
1161 return GNUNET_SYSERR;
1162 GNUNET_assert (sock->tag == NULL);
1163 msize = ntohs (hdr->size);
1164 tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1166 tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1167 memcpy (&tc[1], hdr, msize);
1168 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1170 tc->rn_cls = rn_cls;
1172 GNUNET_CLIENT_notify_transmit_ready (sock, msize, timeout, auto_retry,
1173 &transmit_for_response, tc))
1177 return GNUNET_SYSERR;
1185 /* end of client.c */