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_NO
41 * How often do we re-try tranmsitting requests before giving up?
42 * Note that if we succeeded transmitting a request but failed to read
43 * a response, we do NOT re-try.
45 #define MAX_ATTEMPTS 10
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;
77 struct GNUNET_TIME_Absolute timeout;
80 * If we are re-trying and are delaying to do so,
81 * handle to the scheduled task managing the delay.
83 GNUNET_SCHEDULER_TaskIdentifier task;
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;
109 * Struct to refer to a GNUnet TCP connection.
110 * This is more than just a socket because if the server
111 * drops the connection, the client automatically tries
112 * to reconnect (and for that needs connection information).
114 struct GNUNET_CLIENT_Connection
118 * the socket handle, NULL if not live
120 struct GNUNET_CONNECTION_Handle *sock;
125 struct GNUNET_SCHEDULER_Handle *sched;
130 const struct GNUNET_CONFIGURATION_Handle *cfg;
133 * Name of the service we interact with.
138 * Handler for current receiver task.
140 GNUNET_CLIENT_MessageHandler receiver_handler;
143 * Closure for receiver_handler.
145 void *receiver_handler_cls;
148 * Handle for a pending transmission request, NULL if there is
151 struct GNUNET_CLIENT_TransmitHandle *th;
154 * Handler for service test completion (NULL unless in service_test)
156 GNUNET_SCHEDULER_Task test_cb;
159 * Closure for test_cb (NULL unless in service_test)
164 * Buffer for received message.
169 * Timeout for receiving a response (absolute time).
171 struct GNUNET_TIME_Absolute receive_timeout;
174 * Number of bytes in received_buf that are valid.
179 * Size of received_buf.
181 unsigned int received_size;
184 * Do we have a complete response in received_buf?
189 * Are we currently busy doing receive-processing?
190 * GNUNET_YES if so, GNUNET_NO if not, GNUNET_SYSERR
191 * if the handle should be destroyed as soon as the
192 * receive processing is done.
199 static struct GNUNET_CONNECTION_Handle *
200 do_connect (struct GNUNET_SCHEDULER_Handle *sched,
201 const char *service_name,
202 const struct GNUNET_CONFIGURATION_Handle *cfg)
204 struct GNUNET_CONNECTION_Handle *sock;
206 unsigned long long port;
209 GNUNET_CONFIGURATION_get_value_number (cfg,
215 GNUNET_CONFIGURATION_get_value_string (cfg,
217 "HOSTNAME", &hostname)))
219 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
220 _("Could not determine valid hostname and port for service `%s' from configuration.\n"),
224 if (0 == strlen (hostname))
226 GNUNET_free (hostname);
227 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
228 _("Need a non-empty hostname for service `%s'.\n"),
232 sock = GNUNET_CONNECTION_create_from_connect (sched,
236 GNUNET_SERVER_MAX_MESSAGE_SIZE);
237 GNUNET_free (hostname);
243 * Get a connection with a service.
245 * @param sched scheduler to use
246 * @param service_name name of the service
247 * @param cfg configuration to use
248 * @return NULL on error (service unknown to configuration)
250 struct GNUNET_CLIENT_Connection *
251 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
252 const char *service_name,
253 const struct GNUNET_CONFIGURATION_Handle *cfg)
255 struct GNUNET_CLIENT_Connection *ret;
256 struct GNUNET_CONNECTION_Handle *sock;
258 sock = do_connect (sched, service_name, cfg);
261 ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
264 ret->service_name = GNUNET_strdup (service_name);
271 * Receiver task has completed, free rest of client
275 finish_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
277 struct GNUNET_CLIENT_Connection *sock = cls;
279 if (sock->th != NULL)
280 GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
281 GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
282 GNUNET_free (sock->service_name);
288 * Destroy connection with the service. This will automatically
289 * cancel any pending "receive" request (however, the handler will
290 * *NOT* be called, not even with a NULL message). Any pending
291 * transmission request will also be cancelled UNLESS the callback for
292 * the transmission request has already been called, in which case the
293 * transmission is guaranteed to complete before the socket is fully
296 * @param sock handle to the service connection
299 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
301 GNUNET_assert (sock->sock != NULL);
302 GNUNET_CONNECTION_destroy (sock->sock);
304 sock->receiver_handler = NULL;
305 if (sock->in_receive == GNUNET_YES)
306 sock->in_receive = GNUNET_SYSERR;
308 GNUNET_SCHEDULER_add_after (sock->sched,
310 GNUNET_SCHEDULER_PRIORITY_KEEP,
311 GNUNET_SCHEDULER_NO_TASK,
312 &finish_cleanup, sock);
317 * Check if message is complete
320 check_complete (struct GNUNET_CLIENT_Connection *conn)
322 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
323 (conn->received_pos >=
324 ntohs (((const struct GNUNET_MessageHeader *) conn->
325 received_buf)->size)))
326 conn->msg_complete = GNUNET_YES;
331 * Callback function for data received from the network. Note that
332 * both "available" and "errCode" would be 0 if the read simply timed out.
335 * @param buf pointer to received data
336 * @param available number of bytes availabe in "buf",
337 * possibly 0 (on errors)
338 * @param addr address of the sender
339 * @param addrlen size of addr
340 * @param errCode value of errno (on errors receiving)
343 receive_helper (void *cls,
346 const struct sockaddr *addr, socklen_t addrlen, int errCode)
348 struct GNUNET_CLIENT_Connection *conn = cls;
349 struct GNUNET_TIME_Relative remaining;
351 GNUNET_assert (conn->msg_complete == GNUNET_NO);
352 if (GNUNET_SYSERR == conn->in_receive)
353 GNUNET_SCHEDULER_add_after (conn->sched,
355 GNUNET_SCHEDULER_PRIORITY_KEEP,
356 GNUNET_SCHEDULER_NO_TASK,
359 conn->in_receive = GNUNET_NO;
360 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
362 /* signal timeout! */
363 if (conn->receiver_handler != NULL)
365 conn->receiver_handler (conn->receiver_handler_cls, NULL);
366 conn->receiver_handler = NULL;
371 /* FIXME: optimize for common fast case where buf contains the
372 entire message and we need no copying... */
375 /* slow path: append to array */
376 if (conn->received_size < conn->received_pos + available)
377 GNUNET_array_grow (conn->received_buf,
378 conn->received_size, conn->received_pos + available);
379 memcpy (&conn->received_buf[conn->received_pos], buf, available);
380 conn->received_pos += available;
381 check_complete (conn);
382 /* check for timeout */
383 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
384 if (remaining.value == 0)
386 /* signal timeout! */
387 conn->receiver_handler (conn->receiver_handler_cls, NULL);
390 /* back to receive -- either for more data or to call callback! */
391 GNUNET_CLIENT_receive (conn,
392 conn->receiver_handler,
393 conn->receiver_handler_cls, remaining);
398 * Continuation to call the receive callback.
401 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
403 struct GNUNET_CLIENT_Connection *sock = scls;
404 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
405 const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
406 void *cls = sock->receiver_handler_cls;
407 uint16_t msize = ntohs (cmsg->size);
409 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
411 if (GNUNET_SYSERR == sock->in_receive)
412 GNUNET_SCHEDULER_add_after (sock->sched,
414 GNUNET_SCHEDULER_PRIORITY_KEEP,
415 GNUNET_SCHEDULER_NO_TASK,
418 sock->in_receive = GNUNET_NO;
419 GNUNET_assert (GNUNET_YES == sock->msg_complete);
420 GNUNET_assert (sock->received_pos >= msize);
421 memcpy (msg, cmsg, msize);
422 memmove (sock->received_buf,
423 &sock->received_buf[msize], sock->received_pos - msize);
424 sock->received_pos -= msize;
425 sock->msg_complete = GNUNET_NO;
426 sock->receiver_handler = NULL;
427 check_complete (sock);
434 * Read from the service.
436 * @param sock the service
437 * @param handler function to call with the message
438 * @param handler_cls closure for handler
439 * @param timeout how long to wait until timing out
442 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
443 GNUNET_CLIENT_MessageHandler handler,
444 void *handler_cls, struct GNUNET_TIME_Relative timeout)
446 if (sock->sock == NULL)
448 /* already disconnected, fail instantly! */
449 GNUNET_break (0); /* this should not happen in well-written code! */
450 handler (handler_cls, NULL);
453 sock->receiver_handler = handler;
454 sock->receiver_handler_cls = handler_cls;
455 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
456 sock->in_receive = GNUNET_YES;
457 if (GNUNET_YES == sock->msg_complete)
458 GNUNET_SCHEDULER_add_after (sock->sched,
460 GNUNET_SCHEDULER_PRIORITY_KEEP,
461 GNUNET_SCHEDULER_NO_TASK,
462 &receive_task, sock);
464 GNUNET_CONNECTION_receive (sock->sock,
465 GNUNET_SERVER_MAX_MESSAGE_SIZE,
467 &receive_helper, sock);
472 * If possible, write a shutdown message to the target
473 * buffer and destroy the client connection.
475 * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
476 * @param size number of bytes available in buf
477 * @param buf NULL on error, otherwise target buffer
478 * @return number of bytes written to buf
481 write_shutdown (void *cls, size_t size, void *buf)
483 struct GNUNET_MessageHeader *msg;
484 struct GNUNET_CLIENT_Connection *sock = cls;
486 GNUNET_CLIENT_disconnect (sock);
487 if (size < sizeof (struct GNUNET_MessageHeader))
489 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
490 _("Failed to transmit shutdown request to client.\n"));
491 return 0; /* client disconnected */
493 msg = (struct GNUNET_MessageHeader *) buf;
494 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
495 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
496 return sizeof (struct GNUNET_MessageHeader);
501 * Request that the service should shutdown.
502 * Afterwards, the connection should be disconnected.
504 * @param sock the socket connected to the service
507 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
509 GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
510 sizeof (struct GNUNET_MessageHeader),
511 GNUNET_TIME_UNIT_FOREVER_REL,
512 &write_shutdown, sock);
517 * Report service unavailable.
520 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
521 GNUNET_SCHEDULER_Task task, void *task_cls)
523 GNUNET_SCHEDULER_add_continuation (s,
527 GNUNET_SCHEDULER_REASON_TIMEOUT);
532 * Receive confirmation from test, service is up.
535 * @param msg message received, NULL on timeout or fatal error
538 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
540 struct GNUNET_CLIENT_Connection *conn = cls;
541 /* We may want to consider looking at the reply in more
542 detail in the future, for example, is this the
543 correct service? FIXME! */
547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
548 "Received confirmation that service is running.\n");
550 GNUNET_SCHEDULER_add_continuation (conn->sched,
554 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
558 service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
560 GNUNET_CLIENT_disconnect (conn);
565 write_test (void *cls, size_t size, void *buf)
567 struct GNUNET_MessageHeader *msg;
569 if (size < sizeof (struct GNUNET_MessageHeader))
572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573 _("Failure to transmit TEST request.\n"));
575 return 0; /* client disconnected */
578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
580 msg = (struct GNUNET_MessageHeader *) buf;
581 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
582 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
583 return sizeof (struct GNUNET_MessageHeader);
588 * Wait until the service is running.
590 * @param sched scheduler to use
591 * @param service name of the service to wait for
592 * @param cfg configuration to use
593 * @param timeout how long to wait at most in ms
594 * @param task task to run if service is running
595 * (reason will be "PREREQ_DONE" (service running)
596 * or "TIMEOUT" (service not known to be running))
597 * @param task_cls closure for task
600 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
602 const struct GNUNET_CONFIGURATION_Handle *cfg,
603 struct GNUNET_TIME_Relative timeout,
604 GNUNET_SCHEDULER_Task task, void *task_cls)
606 struct GNUNET_CLIENT_Connection *conn;
609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
610 "Testing if service `%s' is running.\n", service);
612 conn = GNUNET_CLIENT_connect (sched, service, cfg);
615 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
617 ("Could not connect to service `%s', must not be running.\n"),
619 service_test_error (sched, task, task_cls);
622 conn->test_cb = task;
623 conn->test_cb_cls = task_cls;
625 GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
627 GNUNET_MessageHeader),
628 timeout, &write_test, NULL))
630 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
631 _("Failure to transmit request to service `%s'\n"),
633 service_test_error (sched, task, task_cls);
634 GNUNET_CLIENT_disconnect (conn);
637 GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
642 * Connection notifies us about failure or success of
643 * a transmission request. Either pass it on to our
644 * user or, if possible, retry.
646 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
647 * @param size number of bytes available for transmission
648 * @param buf where to write them
649 * @return number of bytes written to buf
652 client_notify (void *cls,
659 * This task is run if we should re-try connection to the
660 * service after a while.
662 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
666 client_delayed_retry (void *cls,
667 const struct GNUNET_SCHEDULER_TaskContext *tc)
669 struct GNUNET_CLIENT_TransmitHandle *th = cls;
671 th->task = GNUNET_SCHEDULER_NO_TASK;
672 th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
674 GNUNET_TIME_absolute_get_remaining (th->timeout),
680 th->notify (th->notify_cls, 0, NULL);
688 * Connection notifies us about failure or success of
689 * a transmission request. Either pass it on to our
690 * user or, if possible, retry.
692 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
693 * @param size number of bytes available for transmission
694 * @param buf where to write them
695 * @return number of bytes written to buf
698 client_notify (void *cls,
702 struct GNUNET_CLIENT_TransmitHandle *th = cls;
704 struct GNUNET_TIME_Relative delay;
710 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
712 if ( (GNUNET_YES != th->auto_retry) ||
713 (0 == --th->attempts_left) ||
716 GNUNET_break (0 == th->notify (th->notify_cls,
723 GNUNET_CONNECTION_destroy (th->sock->sock);
724 th->sock->sock = do_connect (th->sock->sched,
725 th->sock->service_name,
727 GNUNET_assert (NULL != th->sock->sock);
728 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_SECONDS);
729 th->task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
731 GNUNET_SCHEDULER_PRIORITY_KEEP,
732 GNUNET_SCHEDULER_NO_TASK,
734 &client_delayed_retry,
739 GNUNET_assert (size >= th->size);
740 ret = th->notify (th->notify_cls,
749 * Ask the client to call us once the specified number of bytes
750 * are free in the transmission buffer. May call the notify
751 * method immediately if enough space is available.
753 * @param sock connection to the service
754 * @param size number of bytes to send
755 * @param timeout after how long should we give up (and call
756 * notify with buf NULL and size 0)?
757 * @param auto_retry if the connection to the service dies, should we
758 * automatically re-connect and retry (within the timeout period)
759 * or should we immediately fail in this case? Pass GNUNET_YES
760 * if the caller does not care about temporary connection errors,
761 * for example because the protocol is stateless
762 * @param notify function to call
763 * @param notify_cls closure for notify
764 * @return NULL if our buffer will never hold size bytes,
765 * a handle if the notify callback was queued (can be used to cancel)
767 struct GNUNET_CLIENT_TransmitHandle *
768 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
770 struct GNUNET_TIME_Relative timeout,
772 GNUNET_CONNECTION_TransmitReadyNotify
773 notify, void *notify_cls)
775 struct GNUNET_CLIENT_TransmitHandle *th;
777 if (NULL != sock->th)
779 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
782 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
783 th->auto_retry = auto_retry;
785 th->notify_cls = notify_cls;
786 th->attempts_left = MAX_ATTEMPTS;
787 th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
804 * Cancel a request for notification.
806 * @param th handle from the original request.
809 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle *th)
811 if (th->task != GNUNET_SCHEDULER_NO_TASK)
813 GNUNET_break (NULL == th->th);
814 GNUNET_SCHEDULER_cancel (th->sock->sched,
819 GNUNET_break (NULL != th->th);
820 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
828 * Context for processing
829 * "GNUNET_CLIENT_transmit_and_get_response" requests.
836 struct GNUNET_CLIENT_Connection *sock;
839 * Message to transmit; do not free, allocated
840 * right after this struct.
842 const struct GNUNET_MessageHeader *hdr;
847 struct GNUNET_TIME_Absolute timeout;
850 * Function to call when done.
852 GNUNET_CLIENT_MessageHandler rn;
862 * Function called to notify a client about the socket
863 * begin ready to queue the message. "buf" will be
864 * NULL and "size" zero if the socket was closed for
865 * writing in the meantime.
867 * @param cls closure of type "struct TARCtx*"
868 * @param size number of bytes available in buf
869 * @param buf where the callee should write the message
870 * @return number of bytes written to buf
873 transmit_for_response (void *cls,
877 struct TARCtx *tc = cls;
880 msize = ntohs(tc->hdr->size);
883 tc->rn (tc->rn_cls, NULL);
887 GNUNET_assert (size >= msize);
888 memcpy (buf, tc->hdr, msize);
889 GNUNET_CLIENT_receive (tc->sock,
892 GNUNET_TIME_absolute_get_remaining (tc->timeout));
899 * Convenience API that combines sending a request
900 * to the service and waiting for a response.
901 * If either operation times out, the callback
902 * will be called with a "NULL" response (in which
903 * case the connection should probably be destroyed).
905 * @param sock connection to use
906 * @param hdr message to transmit
907 * @param timeout when to give up (for both transmission
908 * and for waiting for a response)
909 * @param auto_retry if the connection to the service dies, should we
910 * automatically re-connect and retry (within the timeout period)
911 * or should we immediately fail in this case? Pass GNUNET_YES
912 * if the caller does not care about temporary connection errors,
913 * for example because the protocol is stateless
914 * @param rn function to call with the response
915 * @param rn_cls closure for rn
916 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
920 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
921 const struct GNUNET_MessageHeader *hdr,
922 struct GNUNET_TIME_Relative timeout,
924 GNUNET_CLIENT_MessageHandler rn,
930 if (NULL != sock->th)
931 return GNUNET_SYSERR;
932 msize = ntohs(hdr->size);
933 tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
935 tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1];
936 memcpy (&tc[1], hdr, msize);
937 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
940 if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
944 &transmit_for_response,
949 return GNUNET_SYSERR;
956 /* end of client.c */