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);
280 LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to unixpath `%s'!\n",
282 GNUNET_free (unixpath);
286 GNUNET_free_non_null (unixpath);
291 GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
294 GNUNET_CONFIGURATION_get_value_number (cfg, service_name, "PORT", &port))
297 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "HOSTNAME",
300 LOG (GNUNET_ERROR_TYPE_WARNING,
302 ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
306 if (0 == strlen (hostname))
308 GNUNET_free (hostname);
309 LOG (GNUNET_ERROR_TYPE_WARNING,
310 _("Need a non-empty hostname for service `%s'.\n"), service_name);
316 /* unspecified means 0 (disabled) */
323 if (0 != (attempt % 2))
328 GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH",
330 (0 < strlen (unixpath)))
333 GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
336 GNUNET_free (unixpath);
337 GNUNET_free_non_null (hostname);
341 GNUNET_free_non_null (unixpath);
344 LOG (GNUNET_ERROR_TYPE_DEBUG,
345 "Port is 0 for service `%s', UNIXPATH did not work, returning NULL!\n",
347 GNUNET_free_non_null (hostname);
351 sock = GNUNET_CONNECTION_create_from_connect (cfg, hostname, port);
352 GNUNET_free (hostname);
358 * Get a connection with a service.
360 * @param service_name name of the service
361 * @param cfg configuration to use
362 * @return NULL on error (service unknown to configuration)
364 struct GNUNET_CLIENT_Connection *
365 GNUNET_CLIENT_connect (const char *service_name,
366 const struct GNUNET_CONFIGURATION_Handle *cfg)
368 struct GNUNET_CLIENT_Connection *ret;
369 struct GNUNET_CONNECTION_Handle *sock;
371 sock = do_connect (service_name, cfg, 0);
372 ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
375 ret->service_name = GNUNET_strdup (service_name);
377 ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
383 * Destroy connection with the service. This will automatically
384 * cancel any pending "receive" request (however, the handler will
385 * *NOT* be called, not even with a NULL message). Any pending
386 * transmission request will also be cancelled UNLESS the callback for
387 * the transmission request has already been called, in which case the
388 * transmission 'finish_pending_write' argument determines whether or
389 * not the write is guaranteed to complete before the socket is fully
390 * destroyed (unless, of course, there is an error with the server in
391 * which case the message may still be lost).
393 * @param finish_pending_write should a transmission already passed to the
394 * handle be completed?
395 * @param sock handle to the service connection
398 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
399 int finish_pending_write)
401 if (sock->in_receive == GNUNET_YES)
403 GNUNET_CONNECTION_receive_cancel (sock->sock);
404 sock->in_receive = GNUNET_NO;
406 if (sock->th != NULL)
408 GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
411 if (NULL != sock->sock)
413 GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
416 if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
418 GNUNET_SCHEDULER_cancel (sock->receive_task);
419 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
421 if (sock->tag != NULL)
423 GNUNET_free (sock->tag);
426 sock->receiver_handler = NULL;
427 GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
428 GNUNET_free (sock->service_name);
434 * Check if message is complete
437 check_complete (struct GNUNET_CLIENT_Connection *conn)
439 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
440 (conn->received_pos >=
441 ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
443 conn->msg_complete = GNUNET_YES;
448 * Callback function for data received from the network. Note that
449 * both "available" and "errCode" would be 0 if the read simply timed out.
452 * @param buf pointer to received data
453 * @param available number of bytes availabe in "buf",
454 * possibly 0 (on errors)
455 * @param addr address of the sender
456 * @param addrlen size of addr
457 * @param errCode value of errno (on errors receiving)
460 receive_helper (void *cls, const void *buf, size_t available,
461 const struct sockaddr *addr, socklen_t addrlen, int errCode)
463 struct GNUNET_CLIENT_Connection *conn = cls;
464 struct GNUNET_TIME_Relative remaining;
465 GNUNET_CLIENT_MessageHandler receive_handler;
466 void *receive_handler_cls;
468 GNUNET_assert (conn->msg_complete == GNUNET_NO);
469 conn->in_receive = GNUNET_NO;
470 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
472 /* signal timeout! */
473 LOG (GNUNET_ERROR_TYPE_DEBUG,
474 "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n",
475 (unsigned int) available, conn->sock == NULL ? "NULL" : "non-NULL",
477 if (NULL != (receive_handler = conn->receiver_handler))
479 receive_handler_cls = conn->receiver_handler_cls;
480 conn->receiver_handler = NULL;
481 receive_handler (receive_handler_cls, NULL);
486 /* FIXME: optimize for common fast case where buf contains the
487 * entire message and we need no copying... */
490 /* slow path: append to array */
491 if (conn->received_size < conn->received_pos + available)
492 GNUNET_array_grow (conn->received_buf, conn->received_size,
493 conn->received_pos + available);
494 memcpy (&conn->received_buf[conn->received_pos], buf, available);
495 conn->received_pos += available;
496 check_complete (conn);
497 /* check for timeout */
498 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
499 if (remaining.rel_value == 0)
501 /* signal timeout! */
502 if (NULL != conn->receiver_handler)
503 conn->receiver_handler (conn->receiver_handler_cls, NULL);
506 /* back to receive -- either for more data or to call callback! */
507 GNUNET_CLIENT_receive (conn, conn->receiver_handler,
508 conn->receiver_handler_cls, remaining);
513 * Continuation to call the receive callback.
515 * @param cls our handle to the client connection
516 * @param tc scheduler context
519 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
521 struct GNUNET_CLIENT_Connection *sock = cls;
522 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
523 const struct GNUNET_MessageHeader *cmsg =
524 (const struct GNUNET_MessageHeader *) sock->received_buf;
525 void *handler_cls = sock->receiver_handler_cls;
526 uint16_t msize = ntohs (cmsg->size);
528 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
530 LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u and size %u\n",
531 ntohs (cmsg->type), msize);
532 sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
533 GNUNET_assert (GNUNET_YES == sock->msg_complete);
534 GNUNET_assert (sock->received_pos >= msize);
535 memcpy (msg, cmsg, msize);
536 memmove (sock->received_buf, &sock->received_buf[msize],
537 sock->received_pos - msize);
538 sock->received_pos -= msize;
539 sock->msg_complete = GNUNET_NO;
540 sock->receiver_handler = NULL;
541 check_complete (sock);
543 handler (handler_cls, msg);
548 * Read from the service.
550 * @param sock the service
551 * @param handler function to call with the message
552 * @param handler_cls closure for handler
553 * @param timeout how long to wait until timing out
556 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
557 GNUNET_CLIENT_MessageHandler handler, void *handler_cls,
558 struct GNUNET_TIME_Relative timeout)
560 if (sock->sock == NULL)
562 /* already disconnected, fail instantly! */
563 GNUNET_break (0); /* this should not happen in well-written code! */
565 handler (handler_cls, NULL);
568 sock->receiver_handler = handler;
569 sock->receiver_handler_cls = handler_cls;
570 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
571 if (GNUNET_YES == sock->msg_complete)
573 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->receive_task);
574 sock->receive_task = GNUNET_SCHEDULER_add_now (&receive_task, sock);
578 GNUNET_assert (sock->in_receive == GNUNET_NO);
579 sock->in_receive = GNUNET_YES;
580 LOG (GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
581 GNUNET_CONNECTION_receive (sock->sock, GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
582 timeout, &receive_helper, sock);
588 * Report service unavailable.
591 service_test_error (GNUNET_SCHEDULER_Task task, void *task_cls)
593 GNUNET_SCHEDULER_add_continuation (task, task_cls,
594 GNUNET_SCHEDULER_REASON_TIMEOUT);
599 * Receive confirmation from test, service is up.
602 * @param msg message received, NULL on timeout or fatal error
605 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
607 struct GNUNET_CLIENT_Connection *conn = cls;
609 /* We may want to consider looking at the reply in more
610 * detail in the future, for example, is this the
611 * correct service? FIXME! */
614 LOG (GNUNET_ERROR_TYPE_DEBUG,
615 "Received confirmation that service is running.\n");
616 GNUNET_SCHEDULER_add_continuation (conn->test_cb, conn->test_cb_cls,
617 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
621 service_test_error (conn->test_cb, conn->test_cb_cls);
623 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
628 * Send the 'TEST' message to the service. If successful, prepare to
631 * @param cls the 'struct GNUNET_CLIENT_Connection' of the connection to test
632 * @param size number of bytes available in buf
633 * @param buf where to write the message
634 * @return number of bytes written to buf
637 write_test (void *cls, size_t size, void *buf)
639 struct GNUNET_CLIENT_Connection *conn = cls;
640 struct GNUNET_MessageHeader *msg;
642 if (size < sizeof (struct GNUNET_MessageHeader))
644 LOG (GNUNET_ERROR_TYPE_DEBUG, _("Failure to transmit TEST request.\n"));
645 service_test_error (conn->test_cb, conn->test_cb_cls);
646 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
647 return 0; /* client disconnected */
649 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "TEST");
650 msg = (struct GNUNET_MessageHeader *) buf;
651 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
652 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
653 GNUNET_CLIENT_receive (conn, &confirm_handler, conn,
654 GNUNET_TIME_absolute_get_remaining
655 (conn->test_deadline));
656 return sizeof (struct GNUNET_MessageHeader);
661 * Test if the service is running. If we are given a UNIXPATH or a local address,
662 * we do this NOT by trying to connect to the service, but by trying to BIND to
663 * the same port. If the BIND fails, we know the service is running.
665 * @param service name of the service to wait for
666 * @param cfg configuration to use
667 * @param timeout how long to wait at most
668 * @param task task to run if service is running
669 * (reason will be "PREREQ_DONE" (service running)
670 * or "TIMEOUT" (service not known to be running))
671 * @param task_cls closure for task
674 GNUNET_CLIENT_service_test (const char *service,
675 const struct GNUNET_CONFIGURATION_Handle *cfg,
676 struct GNUNET_TIME_Relative timeout,
677 GNUNET_SCHEDULER_Task task, void *task_cls)
680 unsigned long long port;
681 struct GNUNET_NETWORK_Handle *sock;
682 struct GNUNET_CLIENT_Connection *conn;
684 LOG (GNUNET_ERROR_TYPE_DEBUG, "Testing if service `%s' is running.\n",
688 /* probe UNIX support */
689 struct sockaddr_un s_un;
694 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? */
696 if (strlen (unixpath) >= sizeof (s_un.sun_path))
698 LOG (GNUNET_ERROR_TYPE_WARNING,
699 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
700 sizeof (s_un.sun_path));
704 sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
707 memset (&s_un, 0, sizeof (s_un));
708 s_un.sun_family = AF_UNIX;
709 slen = strlen (unixpath) + 1;
710 if (slen >= sizeof (s_un.sun_path))
711 slen = sizeof (s_un.sun_path) - 1;
712 memcpy (s_un.sun_path, unixpath, slen);
713 s_un.sun_path[slen] = '\0';
714 slen = sizeof (struct sockaddr_un);
716 s_un.sun_path[0] = '\0';
718 #if HAVE_SOCKADDR_IN_SIN_LEN
719 s_un.sun_len = (u_char) slen;
722 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_un,
725 /* failed to bind => service must be running */
726 GNUNET_free (unixpath);
727 (void) GNUNET_NETWORK_socket_close (sock);
728 GNUNET_SCHEDULER_add_continuation (task, task_cls,
729 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
732 (void) GNUNET_NETWORK_socket_close (sock);
737 GNUNET_free_non_null (unixpath);
743 GNUNET_CONFIGURATION_get_value_number (cfg, service, "PORT", &port)) ||
746 GNUNET_CONFIGURATION_get_value_string (cfg, service, "HOSTNAME",
749 /* UNIXPATH failed (if possible) AND IP failed => error */
750 service_test_error (task, task_cls);
754 if (0 == strcmp ("localhost", hostname)
760 /* can test using 'bind' */
761 struct sockaddr_in s_in;
763 memset (&s_in, 0, sizeof (s_in));
764 #if HAVE_SOCKADDR_IN_SIN_LEN
765 s_in.sin_len = sizeof (struct sockaddr_in);
767 s_in.sin_family = AF_INET;
768 s_in.sin_port = htons (port);
770 sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
774 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in,
777 /* failed to bind => service must be running */
778 GNUNET_free (hostname);
779 (void) GNUNET_NETWORK_socket_close (sock);
780 GNUNET_SCHEDULER_add_continuation (task, task_cls,
781 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
784 (void) GNUNET_NETWORK_socket_close (sock);
788 if (0 == strcmp ("ip6-localhost", hostname)
794 /* can test using 'bind' */
795 struct sockaddr_in6 s_in6;
797 memset (&s_in6, 0, sizeof (s_in6));
798 #if HAVE_SOCKADDR_IN_SIN_LEN
799 s_in6.sin6_len = sizeof (struct sockaddr_in6);
801 s_in6.sin6_family = AF_INET6;
802 s_in6.sin6_port = htons (port);
804 sock = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
808 GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in6,
811 /* failed to bind => service must be running */
812 GNUNET_free (hostname);
813 (void) GNUNET_NETWORK_socket_close (sock);
814 GNUNET_SCHEDULER_add_continuation (task, task_cls,
815 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
818 (void) GNUNET_NETWORK_socket_close (sock);
822 if (((0 == strcmp ("localhost", hostname)) ||
823 (0 == strcmp ("ip6-localhost", hostname)))
829 /* all binds succeeded => claim service not running right now */
830 GNUNET_free_non_null (hostname);
831 service_test_error (task, task_cls);
834 GNUNET_free_non_null (hostname);
836 /* non-localhost, try 'connect' method */
837 conn = GNUNET_CLIENT_connect (service, cfg);
840 LOG (GNUNET_ERROR_TYPE_INFO,
841 _("Could not connect to service `%s', must not be running.\n"),
843 service_test_error (task, task_cls);
846 conn->test_cb = task;
847 conn->test_cb_cls = task_cls;
848 conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
851 GNUNET_CLIENT_notify_transmit_ready (conn,
852 sizeof (struct GNUNET_MessageHeader),
853 timeout, GNUNET_YES, &write_test,
856 LOG (GNUNET_ERROR_TYPE_WARNING,
857 _("Failure to transmit request to service `%s'\n"), service);
858 service_test_error (task, task_cls);
859 GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
866 * Connection notifies us about failure or success of
867 * a transmission request. Either pass it on to our
868 * user or, if possible, retry.
870 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
871 * @param size number of bytes available for transmission
872 * @param buf where to write them
873 * @return number of bytes written to buf
876 client_notify (void *cls, size_t size, void *buf);
880 * This task is run if we should re-try connection to the
881 * service after a while.
883 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
887 client_delayed_retry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
889 struct GNUNET_CLIENT_TransmitHandle *th = cls;
890 struct GNUNET_TIME_Relative delay;
892 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
893 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
895 LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission failed due to shutdown.\n");
897 th->notify (th->notify_cls, 0, NULL);
902 do_connect (th->sock->service_name, th->sock->cfg, th->sock->attempts++);
903 if (NULL == th->sock->sock)
905 /* could happen if we're out of sockets */
907 GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
908 (th->timeout), th->sock->back_off);
910 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
911 (th->sock->back_off, 2),
912 GNUNET_TIME_UNIT_SECONDS);
913 LOG (GNUNET_ERROR_TYPE_DEBUG,
914 "Transmission failed %u times, trying again in %llums.\n",
915 MAX_ATTEMPTS - th->attempts_left,
916 (unsigned long long) delay.rel_value);
918 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
922 GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock, th->size,
923 GNUNET_TIME_absolute_get_remaining
924 (th->timeout), &client_notify,
930 th->notify (th->notify_cls, 0, NULL);
938 * Connection notifies us about failure or success of a transmission
939 * request. Either pass it on to our user or, if possible, retry.
941 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
942 * @param size number of bytes available for transmission
943 * @param buf where to write them
944 * @return number of bytes written to buf
947 client_notify (void *cls, size_t size, void *buf)
949 struct GNUNET_CLIENT_TransmitHandle *th = cls;
951 struct GNUNET_TIME_Relative delay;
957 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
958 delay.rel_value /= 2;
960 (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
961 (GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
962 (delay.rel_value < 1))
964 LOG (GNUNET_ERROR_TYPE_DEBUG,
965 "Transmission failed %u times, giving up.\n",
966 MAX_ATTEMPTS - th->attempts_left);
967 GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
972 LOG (GNUNET_ERROR_TYPE_DEBUG,
973 "Failed to connect to `%s', automatically trying again.\n",
974 th->sock->service_name);
975 GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
976 th->sock->sock = NULL;
977 delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
979 GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
980 (th->sock->back_off, 2),
981 GNUNET_TIME_UNIT_SECONDS);
982 LOG (GNUNET_ERROR_TYPE_DEBUG,
983 "Transmission failed %u times, trying again in %llums.\n",
984 MAX_ATTEMPTS - th->attempts_left,
985 (unsigned long long) delay.rel_value);
988 GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
991 GNUNET_assert (size >= th->size);
992 ret = th->notify (th->notify_cls, size, buf);
999 * Ask the client to call us once the specified number of bytes
1000 * are free in the transmission buffer. May call the notify
1001 * method immediately if enough space is available.
1003 * @param sock connection to the service
1004 * @param size number of bytes to send
1005 * @param timeout after how long should we give up (and call
1006 * notify with buf NULL and size 0)?
1007 * @param auto_retry if the connection to the service dies, should we
1008 * automatically re-connect and retry (within the timeout period)
1009 * or should we immediately fail in this case? Pass GNUNET_YES
1010 * if the caller does not care about temporary connection errors,
1011 * for example because the protocol is stateless
1012 * @param notify function to call
1013 * @param notify_cls closure for notify
1014 * @return NULL if our buffer will never hold size bytes,
1015 * a handle if the notify callback was queued (can be used to cancel)
1017 struct GNUNET_CLIENT_TransmitHandle *
1018 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1020 struct GNUNET_TIME_Relative timeout,
1022 GNUNET_CONNECTION_TransmitReadyNotify
1023 notify, void *notify_cls)
1025 struct GNUNET_CLIENT_TransmitHandle *th;
1027 if (NULL != sock->th)
1029 /* If this breaks, you most likley called this function twice without waiting
1030 * for completion or canceling the request */
1034 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1037 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1038 th->auto_retry = auto_retry;
1039 th->notify = notify;
1040 th->notify_cls = notify_cls;
1041 th->attempts_left = MAX_ATTEMPTS;
1043 if (sock->sock == NULL)
1045 th->reconnect_task =
1046 GNUNET_SCHEDULER_add_delayed (sock->back_off, &client_delayed_retry,
1053 GNUNET_CONNECTION_notify_transmit_ready (sock->sock, size, timeout,
1054 &client_notify, th);
1068 * Cancel a request for notification.
1070 * @param th handle from the original request.
1073 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1076 if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1078 GNUNET_assert (NULL == th->th);
1079 GNUNET_SCHEDULER_cancel (th->reconnect_task);
1080 th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1084 GNUNET_assert (NULL != th->th);
1085 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1087 th->sock->th = NULL;
1093 * Function called to notify a client about the socket
1094 * begin ready to queue the message. "buf" will be
1095 * NULL and "size" zero if the socket was closed for
1096 * writing in the meantime.
1098 * @param cls closure of type "struct TransmitGetResponseContext*"
1099 * @param size number of bytes available in buf
1100 * @param buf where the callee should write the message
1101 * @return number of bytes written to buf
1104 transmit_for_response (void *cls, size_t size, void *buf)
1106 struct TransmitGetResponseContext *tc = cls;
1109 tc->sock->tag = NULL;
1110 msize = ntohs (tc->hdr->size);
1113 LOG (GNUNET_ERROR_TYPE_DEBUG,
1114 _("Could not submit request, not expecting to receive a response.\n"));
1116 tc->rn (tc->rn_cls, NULL);
1120 GNUNET_assert (size >= msize);
1121 memcpy (buf, tc->hdr, msize);
1122 GNUNET_CLIENT_receive (tc->sock, tc->rn, tc->rn_cls,
1123 GNUNET_TIME_absolute_get_remaining (tc->timeout));
1130 * Convenience API that combines sending a request
1131 * to the service and waiting for a response.
1132 * If either operation times out, the callback
1133 * will be called with a "NULL" response (in which
1134 * case the connection should probably be destroyed).
1136 * @param sock connection to use
1137 * @param hdr message to transmit
1138 * @param timeout when to give up (for both transmission
1139 * and for waiting for a response)
1140 * @param auto_retry if the connection to the service dies, should we
1141 * automatically re-connect and retry (within the timeout period)
1142 * or should we immediately fail in this case? Pass GNUNET_YES
1143 * if the caller does not care about temporary connection errors,
1144 * for example because the protocol is stateless
1145 * @param rn function to call with the response
1146 * @param rn_cls closure for rn
1147 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1148 * is already pending
1151 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
1152 const struct GNUNET_MessageHeader *hdr,
1153 struct GNUNET_TIME_Relative timeout,
1155 GNUNET_CLIENT_MessageHandler rn,
1158 struct TransmitGetResponseContext *tc;
1161 if (NULL != sock->th)
1162 return GNUNET_SYSERR;
1163 GNUNET_assert (sock->tag == NULL);
1164 msize = ntohs (hdr->size);
1165 tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1167 tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1168 memcpy (&tc[1], hdr, msize);
1169 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1171 tc->rn_cls = rn_cls;
1173 GNUNET_CLIENT_notify_transmit_ready (sock, msize, timeout, auto_retry,
1174 &transmit_for_response, tc))
1178 return GNUNET_SYSERR;
1186 /* end of client.c */