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"
37 #define DEBUG_CLIENT GNUNET_EXTRA_LOGGING
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.
44 #define MAX_ATTEMPTS 50
46 #define LOG(kind,...) GNUNET_log_from (kind, "util",__VA_ARGS__)
49 * Handle for a transmission request.
51 struct GNUNET_CLIENT_TransmitHandle
56 struct GNUNET_CLIENT_Connection *sock;
59 * Function to call to get the data for transmission.
61 GNUNET_CONNECTION_TransmitReadyNotify notify;
69 * Handle to the transmission with the underlying
72 struct GNUNET_CONNECTION_TransmitHandle *th;
75 * If we are re-trying and are delaying to do so,
76 * handle to the scheduled task managing the delay.
78 GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
81 * Timeout for the operation overall.
83 struct GNUNET_TIME_Absolute timeout;
86 * Number of bytes requested.
91 * Are we allowed to re-try to connect without telling
92 * the user (of this API) about the connection troubles?
97 * Number of attempts left for transmitting the request. We may
98 * fail the first time (say because the service is not yet up), in
99 * which case (if auto_retry is set) we wait a bit and re-try
100 * (timeout permitting).
102 unsigned int attempts_left;
108 * Context for processing
109 * "GNUNET_CLIENT_transmit_and_get_response" requests.
111 struct TransmitGetResponseContext
116 struct GNUNET_CLIENT_Connection *sock;
119 * Message to transmit; do not free, allocated
120 * right after this struct.
122 const struct GNUNET_MessageHeader *hdr;
127 struct GNUNET_TIME_Absolute timeout;
130 * Function to call when done.
132 GNUNET_CLIENT_MessageHandler rn;
141 * Struct to refer to a GNUnet TCP connection.
142 * This is more than just a socket because if the server
143 * drops the connection, the client automatically tries
144 * to reconnect (and for that needs connection information).
146 struct GNUNET_CLIENT_Connection
150 * the socket handle, NULL if not live
152 struct GNUNET_CONNECTION_Handle *sock;
157 const struct GNUNET_CONFIGURATION_Handle *cfg;
160 * Name of the service we interact with.
165 * Context of a transmit_and_get_response operation, NULL
166 * if no such operation is pending.
168 struct TransmitGetResponseContext *tag;
171 * Handler for current receiver task.
173 GNUNET_CLIENT_MessageHandler receiver_handler;
176 * Closure for receiver_handler.
178 void *receiver_handler_cls;
181 * Handle for a pending transmission request, NULL if there is
184 struct GNUNET_CLIENT_TransmitHandle *th;
187 * Handler for service test completion (NULL unless in service_test)
189 GNUNET_SCHEDULER_Task test_cb;
192 * Deadline for calling 'test_cb'.
194 struct GNUNET_TIME_Absolute test_deadline;
197 * If we are re-trying and are delaying to do so,
198 * handle to the scheduled task managing the delay.
200 GNUNET_SCHEDULER_TaskIdentifier receive_task;
203 * Closure for test_cb (NULL unless in service_test)
208 * Buffer for received message.
213 * Timeout for receiving a response (absolute time).
215 struct GNUNET_TIME_Absolute receive_timeout;
218 * Current value for our incremental back-off (for
221 struct GNUNET_TIME_Relative back_off;
224 * Number of bytes in received_buf that are valid.
229 * Size of received_buf.
231 unsigned int received_size;
234 * Do we have a complete response in received_buf?
239 * Are we currently busy doing receive-processing?
240 * GNUNET_YES if so, GNUNET_NO if not.
245 * How often have we tried to connect?
247 unsigned int attempts;
253 * Try to connect to the service.
255 * @param service_name name of service to connect to
256 * @param cfg configuration to use
257 * @param attempt counter used to alternate between IP and UNIX domain sockets
258 * @return NULL on error
260 static struct GNUNET_CONNECTION_Handle *
261 do_connect (const char *service_name,
262 const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned int attempt)
264 struct GNUNET_CONNECTION_Handle *sock;
267 unsigned long long port;
271 if (0 == (attempt % 2))
273 /* on even rounds, try UNIX */
275 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? */
277 sock = GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
281 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to unixpath `%s'!\n",
284 GNUNET_free (unixpath);
288 GNUNET_free_non_null (unixpath);
293 GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
296 GNUNET_CONFIGURATION_get_value_number (cfg, service_name, "PORT", &port))
299 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "HOSTNAME",
302 LOG (GNUNET_ERROR_TYPE_WARNING,
304 ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
308 if (0 == strlen (hostname))
310 GNUNET_free (hostname);
311 LOG (GNUNET_ERROR_TYPE_WARNING,
312 _("Need a non-empty hostname for service `%s'.\n"), service_name);
318 /* unspecified means 0 (disabled) */
325 if (0 != (attempt % 2))
330 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH",
332 (0 < strlen (unixpath)))
335 GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
338 GNUNET_free (unixpath);
339 GNUNET_free_non_null (hostname);
343 GNUNET_free_non_null (unixpath);
347 LOG (GNUNET_ERROR_TYPE_DEBUG,
348 "Port is 0 for service `%s', UNIXPATH did not work, returning NULL!\n",
351 GNUNET_free_non_null (hostname);
355 sock = GNUNET_CONNECTION_create_from_connect (cfg, hostname, port);
356 GNUNET_free (hostname);
362 * Get a connection with a service.
364 * @param service_name name of the service
365 * @param cfg configuration to use
366 * @return NULL on error (service unknown to configuration)
368 struct GNUNET_CLIENT_Connection *
369 GNUNET_CLIENT_connect (const char *service_name,
370 const struct GNUNET_CONFIGURATION_Handle *cfg)
372 struct GNUNET_CLIENT_Connection *ret;
373 struct GNUNET_CONNECTION_Handle *sock;
375 sock = do_connect (service_name, cfg, 0);
376 ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
379 ret->service_name = GNUNET_strdup (service_name);
381 ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
387 * Destroy connection with the service. This will automatically
388 * cancel any pending "receive" request (however, the handler will
389 * *NOT* be called, not even with a NULL message). Any pending
390 * transmission request will also be cancelled UNLESS the callback for
391 * the transmission request has already been called, in which case the
392 * transmission 'finish_pending_write' argument determines whether or
393 * not the write is guaranteed to complete before the socket is fully
394 * destroyed (unless, of course, there is an error with the server in
395 * which case the message may still be lost).
397 * @param finish_pending_write should a transmission already passed to the
398 * handle be completed?
399 * @param sock handle to the service connection
402 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
403 int finish_pending_write)
405 if (sock->in_receive == GNUNET_YES)
407 GNUNET_CONNECTION_receive_cancel (sock->sock);
408 sock->in_receive = GNUNET_NO;
410 if (sock->th != NULL)
412 GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
415 if (NULL != sock->sock)
417 GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
420 if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
422 GNUNET_SCHEDULER_cancel (sock->receive_task);
423 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
425 if (sock->tag != NULL)
427 GNUNET_free (sock->tag);
430 sock->receiver_handler = NULL;
431 GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
432 GNUNET_free (sock->service_name);
438 * Check if message is complete
441 check_complete (struct GNUNET_CLIENT_Connection *conn)
443 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
444 (conn->received_pos >=
445 ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
447 conn->msg_complete = GNUNET_YES;
452 * Callback function for data received from the network. Note that
453 * both "available" and "errCode" would be 0 if the read simply timed out.
456 * @param buf pointer to received data
457 * @param available number of bytes availabe in "buf",
458 * possibly 0 (on errors)
459 * @param addr address of the sender
460 * @param addrlen size of addr
461 * @param errCode value of errno (on errors receiving)
464 receive_helper (void *cls, const void *buf, size_t available,
465 const struct sockaddr *addr, socklen_t addrlen, int errCode)
467 struct GNUNET_CLIENT_Connection *conn = cls;
468 struct GNUNET_TIME_Relative remaining;
469 GNUNET_CLIENT_MessageHandler receive_handler;
470 void *receive_handler_cls;
472 GNUNET_assert (conn->msg_complete == GNUNET_NO);
473 conn->in_receive = GNUNET_NO;
474 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
476 /* signal timeout! */
478 LOG (GNUNET_ERROR_TYPE_DEBUG,
479 "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n",
480 (unsigned int) available, conn->sock == NULL ? "NULL" : "non-NULL",
483 if (NULL != (receive_handler = conn->receiver_handler))
485 receive_handler_cls = conn->receiver_handler_cls;
486 conn->receiver_handler = NULL;
487 receive_handler (receive_handler_cls, NULL);
492 /* FIXME: optimize for common fast case where buf contains the
493 * entire message and we need no copying... */
496 /* slow path: append to array */
497 if (conn->received_size < conn->received_pos + available)
498 GNUNET_array_grow (conn->received_buf, conn->received_size,
499 conn->received_pos + available);
500 memcpy (&conn->received_buf[conn->received_pos], buf, available);
501 conn->received_pos += available;
502 check_complete (conn);
503 /* check for timeout */
504 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
505 if (remaining.rel_value == 0)
507 /* signal timeout! */
508 if (NULL != conn->receiver_handler)
509 conn->receiver_handler (conn->receiver_handler_cls, NULL);
512 /* back to receive -- either for more data or to call callback! */
513 GNUNET_CLIENT_receive (conn, conn->receiver_handler,
514 conn->receiver_handler_cls, remaining);
519 * Continuation to call the receive callback.
521 * @param cls our handle to the client connection
522 * @param tc scheduler context
525 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
527 struct GNUNET_CLIENT_Connection *sock = cls;
528 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
529 const struct GNUNET_MessageHeader *cmsg =
530 (const struct GNUNET_MessageHeader *) sock->received_buf;
531 void *handler_cls = sock->receiver_handler_cls;
532 uint16_t msize = ntohs (cmsg->size);
534 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
537 LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u and size %u\n",
538 ntohs (cmsg->type), msize);
540 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
541 GNUNET_assert (GNUNET_YES == sock->msg_complete);
542 GNUNET_assert (sock->received_pos >= msize);
543 memcpy (msg, cmsg, msize);
544 memmove (sock->received_buf, &sock->received_buf[msize],
545 sock->received_pos - msize);
546 sock->received_pos -= msize;
547 sock->msg_complete = GNUNET_NO;
548 sock->receiver_handler = NULL;
549 check_complete (sock);
551 handler (handler_cls, msg);
556 * Read from the service.
558 * @param sock the service
559 * @param handler function to call with the message
560 * @param handler_cls closure for handler
561 * @param timeout how long to wait until timing out
564 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
565 GNUNET_CLIENT_MessageHandler handler, void *handler_cls,
566 struct GNUNET_TIME_Relative timeout)
568 if (sock->sock == NULL)
570 /* already disconnected, fail instantly! */
571 GNUNET_break (0); /* this should not happen in well-written code! */
573 handler (handler_cls, NULL);
576 sock->receiver_handler = handler;
577 sock->receiver_handler_cls = handler_cls;
578 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
579 if (GNUNET_YES == sock->msg_complete)
581 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->receive_task);
582 sock->receive_task = GNUNET_SCHEDULER_add_now (&receive_task, sock);
586 GNUNET_assert (sock->in_receive == GNUNET_NO);
587 sock->in_receive = GNUNET_YES;
589 LOG (GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
591 GNUNET_CONNECTION_receive (sock->sock, GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
592 timeout, &receive_helper, sock);
598 * Report service unavailable.
601 service_test_error (GNUNET_SCHEDULER_Task task, void *task_cls)
603 GNUNET_SCHEDULER_add_continuation (task, task_cls,
604 GNUNET_SCHEDULER_REASON_TIMEOUT);
609 * Receive confirmation from test, service is up.
612 * @param msg message received, NULL on timeout or fatal error
615 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
617 struct GNUNET_CLIENT_Connection *conn = cls;
619 /* We may want to consider looking at the reply in more
620 * detail in the future, for example, is this the
621 * correct service? FIXME! */
625 LOG (GNUNET_ERROR_TYPE_DEBUG,
626 "Received confirmation that service is running.\n");
628 GNUNET_SCHEDULER_add_continuation (conn->test_cb, conn->test_cb_cls,
629 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
633 service_test_error (conn->test_cb, conn->test_cb_cls);
635 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
640 * Send the 'TEST' message to the service. If successful, prepare to
643 * @param cls the 'struct GNUNET_CLIENT_Connection' of the connection to test
644 * @param size number of bytes available in buf
645 * @param buf where to write the message
646 * @return number of bytes written to buf
649 write_test (void *cls, size_t size, void *buf)
651 struct GNUNET_CLIENT_Connection *conn = cls;
652 struct GNUNET_MessageHeader *msg;
654 if (size < sizeof (struct GNUNET_MessageHeader))
657 LOG (GNUNET_ERROR_TYPE_DEBUG, _("Failure to transmit TEST request.\n"));
659 service_test_error (conn->test_cb, conn->test_cb_cls);
660 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
661 return 0; /* client disconnected */
664 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "TEST");
666 msg = (struct GNUNET_MessageHeader *) buf;
667 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
668 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
669 GNUNET_CLIENT_receive (conn, &confirm_handler, conn,
670 GNUNET_TIME_absolute_get_remaining
671 (conn->test_deadline));
672 return sizeof (struct GNUNET_MessageHeader);
677 * Test if the service is running. If we are given a UNIXPATH or a local address,
678 * we do this NOT by trying to connect to the service, but by trying to BIND to
679 * the same port. If the BIND fails, we know the service is running.
681 * @param service name of the service to wait for
682 * @param cfg configuration to use
683 * @param timeout how long to wait at most
684 * @param task task to run if service is running
685 * (reason will be "PREREQ_DONE" (service running)
686 * or "TIMEOUT" (service not known to be running))
687 * @param task_cls closure for task
690 GNUNET_CLIENT_service_test (const char *service,
691 const struct GNUNET_CONFIGURATION_Handle *cfg,
692 struct GNUNET_TIME_Relative timeout,
693 GNUNET_SCHEDULER_Task task, void *task_cls)
696 unsigned long long port;
697 struct GNUNET_NETWORK_Handle *sock;
698 struct GNUNET_CLIENT_Connection *conn;
701 LOG (GNUNET_ERROR_TYPE_DEBUG, "Testing if service `%s' is running.\n",
706 /* probe UNIX support */
707 struct sockaddr_un s_un;
712 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? */
714 if (strlen (unixpath) >= sizeof (s_un.sun_path))
716 LOG (GNUNET_ERROR_TYPE_WARNING,
717 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
718 sizeof (s_un.sun_path));
722 sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
725 memset (&s_un, 0, sizeof (s_un));
726 s_un.sun_family = AF_UNIX;
727 slen = strlen (unixpath) + 1;
728 if (slen >= sizeof (s_un.sun_path))
729 slen = sizeof (s_un.sun_path) - 1;
730 memcpy (s_un.sun_path, unixpath, slen);
731 s_un.sun_path[slen] = '\0';
732 slen = sizeof (struct sockaddr_un);
734 s_un.sun_path[0] = '\0';
736 #if HAVE_SOCKADDR_IN_SIN_LEN
737 s_un.sun_len = (u_char) slen;
740 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_un,
743 /* failed to bind => service must be running */
744 GNUNET_free (unixpath);
745 (void) GNUNET_NETWORK_socket_close (sock);
746 GNUNET_SCHEDULER_add_continuation (task, task_cls,
747 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
750 (void) GNUNET_NETWORK_socket_close (sock);
755 GNUNET_free_non_null (unixpath);
761 GNUNET_CONFIGURATION_get_value_number (cfg, service, "PORT", &port)) ||
764 GNUNET_CONFIGURATION_get_value_string (cfg, service, "HOSTNAME",
767 /* UNIXPATH failed (if possible) AND IP failed => error */
768 service_test_error (task, task_cls);
772 if (0 == strcmp ("localhost", hostname)
778 /* can test using 'bind' */
779 struct sockaddr_in s_in;
781 memset (&s_in, 0, sizeof (s_in));
782 #if HAVE_SOCKADDR_IN_SIN_LEN
783 s_in.sin_len = sizeof (struct sockaddr_in);
785 s_in.sin_family = AF_INET;
786 s_in.sin_port = htons (port);
788 sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
792 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in,
795 /* failed to bind => service must be running */
796 GNUNET_free (hostname);
797 (void) GNUNET_NETWORK_socket_close (sock);
798 GNUNET_SCHEDULER_add_continuation (task, task_cls,
799 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
802 (void) GNUNET_NETWORK_socket_close (sock);
806 if (0 == strcmp ("ip6-localhost", hostname)
812 /* can test using 'bind' */
813 struct sockaddr_in6 s_in6;
815 memset (&s_in6, 0, sizeof (s_in6));
816 #if HAVE_SOCKADDR_IN_SIN_LEN
817 s_in6.sin6_len = sizeof (struct sockaddr_in6);
819 s_in6.sin6_family = AF_INET6;
820 s_in6.sin6_port = htons (port);
822 sock = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
826 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in6,
829 /* failed to bind => service must be running */
830 GNUNET_free (hostname);
831 (void) GNUNET_NETWORK_socket_close (sock);
832 GNUNET_SCHEDULER_add_continuation (task, task_cls,
833 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
836 (void) GNUNET_NETWORK_socket_close (sock);
840 if (((0 == strcmp ("localhost", hostname)) ||
841 (0 == strcmp ("ip6-localhost", hostname)))
847 /* all binds succeeded => claim service not running right now */
848 GNUNET_free_non_null (hostname);
849 service_test_error (task, task_cls);
852 GNUNET_free_non_null (hostname);
854 /* non-localhost, try 'connect' method */
855 conn = GNUNET_CLIENT_connect (service, cfg);
858 LOG (GNUNET_ERROR_TYPE_INFO,
859 _("Could not connect to service `%s', must not be running.\n"),
861 service_test_error (task, task_cls);
864 conn->test_cb = task;
865 conn->test_cb_cls = task_cls;
866 conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
869 GNUNET_CLIENT_notify_transmit_ready (conn,
870 sizeof (struct GNUNET_MessageHeader),
871 timeout, GNUNET_YES, &write_test,
874 LOG (GNUNET_ERROR_TYPE_WARNING,
875 _("Failure to transmit request to service `%s'\n"), service);
876 service_test_error (task, task_cls);
877 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
884 * Connection notifies us about failure or success of
885 * a transmission request. Either pass it on to our
886 * user or, if possible, retry.
888 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
889 * @param size number of bytes available for transmission
890 * @param buf where to write them
891 * @return number of bytes written to buf
894 client_notify (void *cls, size_t size, void *buf);
898 * This task is run if we should re-try connection to the
899 * service after a while.
901 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
905 client_delayed_retry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
907 struct GNUNET_CLIENT_TransmitHandle *th = cls;
908 struct GNUNET_TIME_Relative delay;
910 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
911 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
914 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission failed due to shutdown.\n");
917 th->notify (th->notify_cls, 0, NULL);
922 do_connect (th->sock->service_name, th->sock->cfg, th->sock->attempts++);
923 if (NULL == th->sock->sock)
925 /* could happen if we're out of sockets */
927 GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
928 (th->timeout), th->sock->back_off);
930 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
931 (th->sock->back_off, 2),
932 GNUNET_TIME_UNIT_SECONDS);
934 LOG (GNUNET_ERROR_TYPE_DEBUG,
935 "Transmission failed %u times, trying again in %llums.\n",
936 MAX_ATTEMPTS - th->attempts_left,
937 (unsigned long long) delay.rel_value);
940 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
944 GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock, th->size,
945 GNUNET_TIME_absolute_get_remaining
946 (th->timeout), &client_notify,
952 th->notify (th->notify_cls, 0, NULL);
960 * Connection notifies us about failure or success of a transmission
961 * request. Either pass it on to our user or, if possible, retry.
963 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
964 * @param size number of bytes available for transmission
965 * @param buf where to write them
966 * @return number of bytes written to buf
969 client_notify (void *cls, size_t size, void *buf)
971 struct GNUNET_CLIENT_TransmitHandle *th = cls;
973 struct GNUNET_TIME_Relative delay;
979 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
980 delay.rel_value /= 2;
982 (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
983 (GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
984 (delay.rel_value < 1))
987 LOG (GNUNET_ERROR_TYPE_DEBUG,
988 "Transmission failed %u times, giving up.\n",
989 MAX_ATTEMPTS - th->attempts_left);
991 GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
997 LOG (GNUNET_ERROR_TYPE_DEBUG,
998 "Failed to connect to `%s', automatically trying again.\n",
999 th->sock->service_name);
1001 GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
1002 th->sock->sock = NULL;
1003 delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
1004 th->sock->back_off =
1005 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
1006 (th->sock->back_off, 2),
1007 GNUNET_TIME_UNIT_SECONDS);
1009 LOG (GNUNET_ERROR_TYPE_DEBUG,
1010 "Transmission failed %u times, trying again in %llums.\n",
1011 MAX_ATTEMPTS - th->attempts_left,
1012 (unsigned long long) delay.rel_value);
1015 th->reconnect_task =
1016 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
1019 GNUNET_assert (size >= th->size);
1020 ret = th->notify (th->notify_cls, size, buf);
1027 * Ask the client to call us once the specified number of bytes
1028 * are free in the transmission buffer. May call the notify
1029 * method immediately if enough space is available.
1031 * @param sock connection to the service
1032 * @param size number of bytes to send
1033 * @param timeout after how long should we give up (and call
1034 * notify with buf NULL and size 0)?
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 notify function to call
1041 * @param notify_cls closure for notify
1042 * @return NULL if our buffer will never hold size bytes,
1043 * a handle if the notify callback was queued (can be used to cancel)
1045 struct GNUNET_CLIENT_TransmitHandle *
1046 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1048 struct GNUNET_TIME_Relative timeout,
1050 GNUNET_CONNECTION_TransmitReadyNotify
1051 notify, void *notify_cls)
1053 struct GNUNET_CLIENT_TransmitHandle *th;
1055 if (NULL != sock->th)
1057 /* If this breaks, you most likley called this function twice without waiting
1058 * for completion or canceling the request */
1062 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1065 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1066 th->auto_retry = auto_retry;
1067 th->notify = notify;
1068 th->notify_cls = notify_cls;
1069 th->attempts_left = MAX_ATTEMPTS;
1071 if (sock->sock == NULL)
1073 th->reconnect_task =
1074 GNUNET_SCHEDULER_add_delayed (sock->back_off, &client_delayed_retry,
1081 GNUNET_CONNECTION_notify_transmit_ready (sock->sock, size, timeout,
1082 &client_notify, th);
1096 * Cancel a request for notification.
1098 * @param th handle from the original request.
1101 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1104 if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1106 GNUNET_assert (NULL == th->th);
1107 GNUNET_SCHEDULER_cancel (th->reconnect_task);
1108 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1112 GNUNET_assert (NULL != th->th);
1113 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1115 th->sock->th = NULL;
1121 * Function called to notify a client about the socket
1122 * begin ready to queue the message. "buf" will be
1123 * NULL and "size" zero if the socket was closed for
1124 * writing in the meantime.
1126 * @param cls closure of type "struct TransmitGetResponseContext*"
1127 * @param size number of bytes available in buf
1128 * @param buf where the callee should write the message
1129 * @return number of bytes written to buf
1132 transmit_for_response (void *cls, size_t size, void *buf)
1134 struct TransmitGetResponseContext *tc = cls;
1137 tc->sock->tag = NULL;
1138 msize = ntohs (tc->hdr->size);
1142 LOG (GNUNET_ERROR_TYPE_DEBUG,
1143 _("Could not submit request, not expecting to receive a response.\n"));
1146 tc->rn (tc->rn_cls, NULL);
1150 GNUNET_assert (size >= msize);
1151 memcpy (buf, tc->hdr, msize);
1152 GNUNET_CLIENT_receive (tc->sock, tc->rn, tc->rn_cls,
1153 GNUNET_TIME_absolute_get_remaining (tc->timeout));
1160 * Convenience API that combines sending a request
1161 * to the service and waiting for a response.
1162 * If either operation times out, the callback
1163 * will be called with a "NULL" response (in which
1164 * case the connection should probably be destroyed).
1166 * @param sock connection to use
1167 * @param hdr message to transmit
1168 * @param timeout when to give up (for both transmission
1169 * and for waiting for a response)
1170 * @param auto_retry if the connection to the service dies, should we
1171 * automatically re-connect and retry (within the timeout period)
1172 * or should we immediately fail in this case? Pass GNUNET_YES
1173 * if the caller does not care about temporary connection errors,
1174 * for example because the protocol is stateless
1175 * @param rn function to call with the response
1176 * @param rn_cls closure for rn
1177 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1178 * is already pending
1181 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
1182 const struct GNUNET_MessageHeader *hdr,
1183 struct GNUNET_TIME_Relative timeout,
1185 GNUNET_CLIENT_MessageHandler rn,
1188 struct TransmitGetResponseContext *tc;
1191 if (NULL != sock->th)
1192 return GNUNET_SYSERR;
1193 GNUNET_assert (sock->tag == NULL);
1194 msize = ntohs (hdr->size);
1195 tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1197 tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1198 memcpy (&tc[1], hdr, msize);
1199 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1201 tc->rn_cls = rn_cls;
1203 GNUNET_CLIENT_notify_transmit_ready (sock, msize, timeout, auto_retry,
1204 &transmit_for_response, tc))
1208 return GNUNET_SYSERR;
1216 /* end of client.c */