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 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);
265 ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
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);
283 GNUNET_CONFIGURATION_destroy (sock->cfg);
289 * Destroy connection with the service. This will automatically
290 * cancel any pending "receive" request (however, the handler will
291 * *NOT* be called, not even with a NULL message). Any pending
292 * transmission request will also be cancelled UNLESS the callback for
293 * the transmission request has already been called, in which case the
294 * transmission is guaranteed to complete before the socket is fully
297 * @param sock handle to the service connection
300 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
302 GNUNET_assert (sock->sock != NULL);
303 GNUNET_CONNECTION_destroy (sock->sock);
305 sock->receiver_handler = NULL;
306 if (sock->in_receive == GNUNET_YES)
307 sock->in_receive = GNUNET_SYSERR;
309 GNUNET_SCHEDULER_add_after (sock->sched,
311 GNUNET_SCHEDULER_PRIORITY_KEEP,
312 GNUNET_SCHEDULER_NO_TASK,
313 &finish_cleanup, sock);
318 * Check if message is complete
321 check_complete (struct GNUNET_CLIENT_Connection *conn)
323 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
324 (conn->received_pos >=
325 ntohs (((const struct GNUNET_MessageHeader *) conn->
326 received_buf)->size)))
327 conn->msg_complete = GNUNET_YES;
332 * Callback function for data received from the network. Note that
333 * both "available" and "errCode" would be 0 if the read simply timed out.
336 * @param buf pointer to received data
337 * @param available number of bytes availabe in "buf",
338 * possibly 0 (on errors)
339 * @param addr address of the sender
340 * @param addrlen size of addr
341 * @param errCode value of errno (on errors receiving)
344 receive_helper (void *cls,
347 const struct sockaddr *addr, socklen_t addrlen, int errCode)
349 struct GNUNET_CLIENT_Connection *conn = cls;
350 struct GNUNET_TIME_Relative remaining;
352 GNUNET_assert (conn->msg_complete == GNUNET_NO);
353 if (GNUNET_SYSERR == conn->in_receive)
354 GNUNET_SCHEDULER_add_after (conn->sched,
356 GNUNET_SCHEDULER_PRIORITY_KEEP,
357 GNUNET_SCHEDULER_NO_TASK,
360 conn->in_receive = GNUNET_NO;
361 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
363 /* signal timeout! */
364 if (conn->receiver_handler != NULL)
366 conn->receiver_handler (conn->receiver_handler_cls, NULL);
367 conn->receiver_handler = NULL;
372 /* FIXME: optimize for common fast case where buf contains the
373 entire message and we need no copying... */
376 /* slow path: append to array */
377 if (conn->received_size < conn->received_pos + available)
378 GNUNET_array_grow (conn->received_buf,
379 conn->received_size, conn->received_pos + available);
380 memcpy (&conn->received_buf[conn->received_pos], buf, available);
381 conn->received_pos += available;
382 check_complete (conn);
383 /* check for timeout */
384 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
385 if (remaining.value == 0)
387 /* signal timeout! */
388 conn->receiver_handler (conn->receiver_handler_cls, NULL);
391 /* back to receive -- either for more data or to call callback! */
392 GNUNET_CLIENT_receive (conn,
393 conn->receiver_handler,
394 conn->receiver_handler_cls, remaining);
399 * Continuation to call the receive callback.
402 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
404 struct GNUNET_CLIENT_Connection *sock = scls;
405 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
406 const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
407 void *cls = sock->receiver_handler_cls;
408 uint16_t msize = ntohs (cmsg->size);
410 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
412 if (GNUNET_SYSERR == sock->in_receive)
413 GNUNET_SCHEDULER_add_after (sock->sched,
415 GNUNET_SCHEDULER_PRIORITY_KEEP,
416 GNUNET_SCHEDULER_NO_TASK,
419 sock->in_receive = GNUNET_NO;
420 GNUNET_assert (GNUNET_YES == sock->msg_complete);
421 GNUNET_assert (sock->received_pos >= msize);
422 memcpy (msg, cmsg, msize);
423 memmove (sock->received_buf,
424 &sock->received_buf[msize], sock->received_pos - msize);
425 sock->received_pos -= msize;
426 sock->msg_complete = GNUNET_NO;
427 sock->receiver_handler = NULL;
428 check_complete (sock);
435 * Read from the service.
437 * @param sock the service
438 * @param handler function to call with the message
439 * @param handler_cls closure for handler
440 * @param timeout how long to wait until timing out
443 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
444 GNUNET_CLIENT_MessageHandler handler,
445 void *handler_cls, struct GNUNET_TIME_Relative timeout)
447 if (sock->sock == NULL)
449 /* already disconnected, fail instantly! */
450 GNUNET_break (0); /* this should not happen in well-written code! */
451 handler (handler_cls, NULL);
454 sock->receiver_handler = handler;
455 sock->receiver_handler_cls = handler_cls;
456 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
457 sock->in_receive = GNUNET_YES;
458 if (GNUNET_YES == sock->msg_complete)
459 GNUNET_SCHEDULER_add_after (sock->sched,
461 GNUNET_SCHEDULER_PRIORITY_KEEP,
462 GNUNET_SCHEDULER_NO_TASK,
463 &receive_task, sock);
465 GNUNET_CONNECTION_receive (sock->sock,
466 GNUNET_SERVER_MAX_MESSAGE_SIZE,
468 &receive_helper, sock);
473 * If possible, write a shutdown message to the target
474 * buffer and destroy the client connection.
476 * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
477 * @param size number of bytes available in buf
478 * @param buf NULL on error, otherwise target buffer
479 * @return number of bytes written to buf
482 write_shutdown (void *cls, size_t size, void *buf)
484 struct GNUNET_MessageHeader *msg;
485 struct GNUNET_CLIENT_Connection *sock = cls;
487 GNUNET_CLIENT_disconnect (sock);
488 if (size < sizeof (struct GNUNET_MessageHeader))
490 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
491 _("Failed to transmit shutdown request to client.\n"));
492 return 0; /* client disconnected */
494 msg = (struct GNUNET_MessageHeader *) buf;
495 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
496 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
497 return sizeof (struct GNUNET_MessageHeader);
502 * Request that the service should shutdown.
503 * Afterwards, the connection should be disconnected.
505 * @param sock the socket connected to the service
508 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
510 GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
511 sizeof (struct GNUNET_MessageHeader),
512 GNUNET_TIME_UNIT_FOREVER_REL,
513 &write_shutdown, sock);
518 * Report service unavailable.
521 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
522 GNUNET_SCHEDULER_Task task, void *task_cls)
524 GNUNET_SCHEDULER_add_continuation (s,
528 GNUNET_SCHEDULER_REASON_TIMEOUT);
533 * Receive confirmation from test, service is up.
536 * @param msg message received, NULL on timeout or fatal error
539 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
541 struct GNUNET_CLIENT_Connection *conn = cls;
542 /* We may want to consider looking at the reply in more
543 detail in the future, for example, is this the
544 correct service? FIXME! */
548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
549 "Received confirmation that service is running.\n");
551 GNUNET_SCHEDULER_add_continuation (conn->sched,
555 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
559 service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
561 GNUNET_CLIENT_disconnect (conn);
566 write_test (void *cls, size_t size, void *buf)
568 struct GNUNET_MessageHeader *msg;
570 if (size < sizeof (struct GNUNET_MessageHeader))
573 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
574 _("Failure to transmit TEST request.\n"));
576 return 0; /* client disconnected */
579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
581 msg = (struct GNUNET_MessageHeader *) buf;
582 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
583 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
584 return sizeof (struct GNUNET_MessageHeader);
589 * Wait until the service is running.
591 * @param sched scheduler to use
592 * @param service name of the service to wait for
593 * @param cfg configuration to use
594 * @param timeout how long to wait at most in ms
595 * @param task task to run if service is running
596 * (reason will be "PREREQ_DONE" (service running)
597 * or "TIMEOUT" (service not known to be running))
598 * @param task_cls closure for task
601 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
603 const struct GNUNET_CONFIGURATION_Handle *cfg,
604 struct GNUNET_TIME_Relative timeout,
605 GNUNET_SCHEDULER_Task task, void *task_cls)
607 struct GNUNET_CLIENT_Connection *conn;
610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611 "Testing if service `%s' is running.\n", service);
613 conn = GNUNET_CLIENT_connect (sched, service, cfg);
616 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
618 ("Could not connect to service `%s', must not be running.\n"),
620 service_test_error (sched, task, task_cls);
623 conn->test_cb = task;
624 conn->test_cb_cls = task_cls;
626 GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
628 GNUNET_MessageHeader),
629 timeout, &write_test, NULL))
631 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
632 _("Failure to transmit request to service `%s'\n"),
634 service_test_error (sched, task, task_cls);
635 GNUNET_CLIENT_disconnect (conn);
638 GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
643 * Connection notifies us about failure or success of
644 * a transmission request. Either pass it on to our
645 * user or, if possible, retry.
647 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
648 * @param size number of bytes available for transmission
649 * @param buf where to write them
650 * @return number of bytes written to buf
653 client_notify (void *cls,
660 * This task is run if we should re-try connection to the
661 * service after a while.
663 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
667 client_delayed_retry (void *cls,
668 const struct GNUNET_SCHEDULER_TaskContext *tc)
670 struct GNUNET_CLIENT_TransmitHandle *th = cls;
672 th->task = GNUNET_SCHEDULER_NO_TASK;
673 th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
675 GNUNET_TIME_absolute_get_remaining (th->timeout),
681 th->notify (th->notify_cls, 0, NULL);
689 * Connection notifies us about failure or success of
690 * a transmission request. Either pass it on to our
691 * user or, if possible, retry.
693 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
694 * @param size number of bytes available for transmission
695 * @param buf where to write them
696 * @return number of bytes written to buf
699 client_notify (void *cls,
703 struct GNUNET_CLIENT_TransmitHandle *th = cls;
705 struct GNUNET_TIME_Relative delay;
711 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
713 if ( (GNUNET_YES != th->auto_retry) ||
714 (0 == --th->attempts_left) ||
717 GNUNET_break (0 == th->notify (th->notify_cls,
724 GNUNET_CONNECTION_destroy (th->sock->sock);
725 th->sock->sock = do_connect (th->sock->sched,
726 th->sock->service_name,
728 GNUNET_assert (NULL != th->sock->sock);
729 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_SECONDS);
730 th->task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
732 GNUNET_SCHEDULER_PRIORITY_KEEP,
733 GNUNET_SCHEDULER_NO_TASK,
735 &client_delayed_retry,
740 GNUNET_assert (size >= th->size);
741 ret = th->notify (th->notify_cls,
750 * Ask the client to call us once the specified number of bytes
751 * are free in the transmission buffer. May call the notify
752 * method immediately if enough space is available.
754 * @param sock connection to the service
755 * @param size number of bytes to send
756 * @param timeout after how long should we give up (and call
757 * notify with buf NULL and size 0)?
758 * @param auto_retry if the connection to the service dies, should we
759 * automatically re-connect and retry (within the timeout period)
760 * or should we immediately fail in this case? Pass GNUNET_YES
761 * if the caller does not care about temporary connection errors,
762 * for example because the protocol is stateless
763 * @param notify function to call
764 * @param notify_cls closure for notify
765 * @return NULL if our buffer will never hold size bytes,
766 * a handle if the notify callback was queued (can be used to cancel)
768 struct GNUNET_CLIENT_TransmitHandle *
769 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
771 struct GNUNET_TIME_Relative timeout,
773 GNUNET_CONNECTION_TransmitReadyNotify
774 notify, void *notify_cls)
776 struct GNUNET_CLIENT_TransmitHandle *th;
778 if (NULL != sock->th)
780 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
783 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
784 th->auto_retry = auto_retry;
786 th->notify_cls = notify_cls;
787 th->attempts_left = MAX_ATTEMPTS;
788 th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
805 * Cancel a request for notification.
807 * @param th handle from the original request.
810 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle *th)
812 if (th->task != GNUNET_SCHEDULER_NO_TASK)
814 GNUNET_break (NULL == th->th);
815 GNUNET_SCHEDULER_cancel (th->sock->sched,
820 GNUNET_break (NULL != th->th);
821 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
829 * Context for processing
830 * "GNUNET_CLIENT_transmit_and_get_response" requests.
837 struct GNUNET_CLIENT_Connection *sock;
840 * Message to transmit; do not free, allocated
841 * right after this struct.
843 const struct GNUNET_MessageHeader *hdr;
848 struct GNUNET_TIME_Absolute timeout;
851 * Function to call when done.
853 GNUNET_CLIENT_MessageHandler rn;
863 * Function called to notify a client about the socket
864 * begin ready to queue the message. "buf" will be
865 * NULL and "size" zero if the socket was closed for
866 * writing in the meantime.
868 * @param cls closure of type "struct TARCtx*"
869 * @param size number of bytes available in buf
870 * @param buf where the callee should write the message
871 * @return number of bytes written to buf
874 transmit_for_response (void *cls,
878 struct TARCtx *tc = cls;
881 msize = ntohs(tc->hdr->size);
884 tc->rn (tc->rn_cls, NULL);
888 GNUNET_assert (size >= msize);
889 memcpy (buf, tc->hdr, msize);
890 GNUNET_CLIENT_receive (tc->sock,
893 GNUNET_TIME_absolute_get_remaining (tc->timeout));
900 * Convenience API that combines sending a request
901 * to the service and waiting for a response.
902 * If either operation times out, the callback
903 * will be called with a "NULL" response (in which
904 * case the connection should probably be destroyed).
906 * @param sock connection to use
907 * @param hdr message to transmit
908 * @param timeout when to give up (for both transmission
909 * and for waiting for a response)
910 * @param auto_retry if the connection to the service dies, should we
911 * automatically re-connect and retry (within the timeout period)
912 * or should we immediately fail in this case? Pass GNUNET_YES
913 * if the caller does not care about temporary connection errors,
914 * for example because the protocol is stateless
915 * @param rn function to call with the response
916 * @param rn_cls closure for rn
917 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
921 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
922 const struct GNUNET_MessageHeader *hdr,
923 struct GNUNET_TIME_Relative timeout,
925 GNUNET_CLIENT_MessageHandler rn,
931 if (NULL != sock->th)
932 return GNUNET_SYSERR;
933 msize = ntohs(hdr->size);
934 tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
936 tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1];
937 memcpy (&tc[1], hdr, msize);
938 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
941 if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
945 &transmit_for_response,
950 return GNUNET_SYSERR;
957 /* end of client.c */