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
48 * Struct to refer to a GNUnet TCP connection.
49 * This is more than just a socket because if the server
50 * drops the connection, the client automatically tries
51 * to reconnect (and for that needs connection information).
53 struct GNUNET_CLIENT_Connection
57 * the socket handle, NULL if not live
59 struct GNUNET_CONNECTION_Handle *sock;
64 struct GNUNET_SCHEDULER_Handle *sched;
69 const struct GNUNET_CONFIGURATION_Handle *cfg;
72 * Name of the service we interact with.
77 * Handler for current receiver task.
79 GNUNET_CLIENT_MessageHandler receiver_handler;
82 * Closure for receiver_handler.
84 void *receiver_handler_cls;
87 * Handler for service test completion (NULL unless in service_test)
89 GNUNET_SCHEDULER_Task test_cb;
92 * Closure for test_cb (NULL unless in service_test)
97 * Buffer for received message.
102 * Timeout for receiving a response (absolute time).
104 struct GNUNET_TIME_Absolute receive_timeout;
107 * Number of bytes in received_buf that are valid.
112 * Size of received_buf.
114 unsigned int received_size;
117 * Do we have a complete response in received_buf?
122 * Are we currently busy doing receive-processing?
123 * GNUNET_YES if so, GNUNET_NO if not, GNUNET_SYSERR
124 * if the handle should be destroyed as soon as the
125 * receive processing is done.
132 static struct GNUNET_CONNECTION_Handle *
133 do_connect (struct GNUNET_SCHEDULER_Handle *sched,
134 const char *service_name,
135 const struct GNUNET_CONFIGURATION_Handle *cfg)
137 struct GNUNET_CONNECTION_Handle *sock;
139 unsigned long long port;
142 GNUNET_CONFIGURATION_get_value_number (cfg,
148 GNUNET_CONFIGURATION_get_value_string (cfg,
150 "HOSTNAME", &hostname)))
152 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
153 _("Could not determine valid hostname and port for service `%s' from configuration.\n"),
157 if (0 == strlen (hostname))
159 GNUNET_free (hostname);
160 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
161 _("Need a non-empty hostname for service `%s'.\n"),
165 sock = GNUNET_CONNECTION_create_from_connect (sched,
169 GNUNET_SERVER_MAX_MESSAGE_SIZE);
170 GNUNET_free (hostname);
176 * Get a connection with a service.
178 * @param sched scheduler to use
179 * @param service_name name of the service
180 * @param cfg configuration to use
181 * @return NULL on error (service unknown to configuration)
183 struct GNUNET_CLIENT_Connection *
184 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
185 const char *service_name,
186 const struct GNUNET_CONFIGURATION_Handle *cfg)
188 struct GNUNET_CLIENT_Connection *ret;
189 struct GNUNET_CONNECTION_Handle *sock;
191 sock = do_connect (sched, service_name, cfg);
194 ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
197 ret->service_name = GNUNET_strdup (service_name);
204 * Receiver task has completed, free rest of client
208 finish_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
210 struct GNUNET_CLIENT_Connection *sock = cls;
212 GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
213 GNUNET_free (sock->service_name);
219 * Destroy connection with the service.
222 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
224 GNUNET_assert (sock->sock != NULL);
225 GNUNET_CONNECTION_destroy (sock->sock);
227 sock->receiver_handler = NULL;
228 if (sock->in_receive == GNUNET_YES)
229 sock->in_receive = GNUNET_SYSERR;
231 GNUNET_SCHEDULER_add_after (sock->sched,
233 GNUNET_SCHEDULER_PRIORITY_KEEP,
234 GNUNET_SCHEDULER_NO_TASK,
235 &finish_cleanup, sock);
240 * Check if message is complete
243 check_complete (struct GNUNET_CLIENT_Connection *conn)
245 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
246 (conn->received_pos >=
247 ntohs (((const struct GNUNET_MessageHeader *) conn->
248 received_buf)->size)))
249 conn->msg_complete = GNUNET_YES;
254 * Callback function for data received from the network. Note that
255 * both "available" and "errCode" would be 0 if the read simply timed out.
258 * @param buf pointer to received data
259 * @param available number of bytes availabe in "buf",
260 * possibly 0 (on errors)
261 * @param addr address of the sender
262 * @param addrlen size of addr
263 * @param errCode value of errno (on errors receiving)
266 receive_helper (void *cls,
269 const struct sockaddr *addr, socklen_t addrlen, int errCode)
271 struct GNUNET_CLIENT_Connection *conn = cls;
272 struct GNUNET_TIME_Relative remaining;
274 GNUNET_assert (conn->msg_complete == GNUNET_NO);
275 if (GNUNET_SYSERR == conn->in_receive)
276 GNUNET_SCHEDULER_add_after (conn->sched,
278 GNUNET_SCHEDULER_PRIORITY_KEEP,
279 GNUNET_SCHEDULER_NO_TASK,
282 conn->in_receive = GNUNET_NO;
283 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
285 /* signal timeout! */
286 if (conn->receiver_handler != NULL)
288 conn->receiver_handler (conn->receiver_handler_cls, NULL);
289 conn->receiver_handler = NULL;
294 /* FIXME: optimize for common fast case where buf contains the
295 entire message and we need no copying... */
298 /* slow path: append to array */
299 if (conn->received_size < conn->received_pos + available)
300 GNUNET_array_grow (conn->received_buf,
301 conn->received_size, conn->received_pos + available);
302 memcpy (&conn->received_buf[conn->received_pos], buf, available);
303 conn->received_pos += available;
304 check_complete (conn);
305 /* check for timeout */
306 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
307 if (remaining.value == 0)
309 /* signal timeout! */
310 conn->receiver_handler (conn->receiver_handler_cls, NULL);
313 /* back to receive -- either for more data or to call callback! */
314 GNUNET_CLIENT_receive (conn,
315 conn->receiver_handler,
316 conn->receiver_handler_cls, remaining);
321 * Continuation to call the receive callback.
324 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
326 struct GNUNET_CLIENT_Connection *sock = scls;
327 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
328 const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
329 void *cls = sock->receiver_handler_cls;
330 uint16_t msize = ntohs (cmsg->size);
332 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
334 if (GNUNET_SYSERR == sock->in_receive)
335 GNUNET_SCHEDULER_add_after (sock->sched,
337 GNUNET_SCHEDULER_PRIORITY_KEEP,
338 GNUNET_SCHEDULER_NO_TASK,
341 sock->in_receive = GNUNET_NO;
342 GNUNET_assert (GNUNET_YES == sock->msg_complete);
343 GNUNET_assert (sock->received_pos >= msize);
344 memcpy (msg, cmsg, msize);
345 memmove (sock->received_buf,
346 &sock->received_buf[msize], sock->received_pos - msize);
347 sock->received_pos -= msize;
348 sock->msg_complete = GNUNET_NO;
349 sock->receiver_handler = NULL;
350 check_complete (sock);
357 * Read from the service.
359 * @param sock the service
360 * @param handler function to call with the message
361 * @param handler_cls closure for handler
362 * @param timeout how long to wait until timing out
365 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
366 GNUNET_CLIENT_MessageHandler handler,
367 void *handler_cls, struct GNUNET_TIME_Relative timeout)
369 if (sock->sock == NULL)
371 /* already disconnected, fail instantly! */
372 GNUNET_break (0); /* this should not happen in well-written code! */
373 handler (handler_cls, NULL);
376 sock->receiver_handler = handler;
377 sock->receiver_handler_cls = handler_cls;
378 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
379 sock->in_receive = GNUNET_YES;
380 if (GNUNET_YES == sock->msg_complete)
381 GNUNET_SCHEDULER_add_after (sock->sched,
383 GNUNET_SCHEDULER_PRIORITY_KEEP,
384 GNUNET_SCHEDULER_NO_TASK,
385 &receive_task, sock);
387 GNUNET_CONNECTION_receive (sock->sock,
388 GNUNET_SERVER_MAX_MESSAGE_SIZE,
390 &receive_helper, sock);
395 write_shutdown (void *cls, size_t size, void *buf)
397 struct GNUNET_MessageHeader *msg;
399 if (size < sizeof (struct GNUNET_MessageHeader))
400 return 0; /* client disconnected */
401 msg = (struct GNUNET_MessageHeader *) buf;
402 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
403 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
404 return sizeof (struct GNUNET_MessageHeader);
409 * Request that the service should shutdown.
410 * Afterwards, the connection should be disconnected.
412 * @param sock the socket connected to the service
415 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
417 GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
418 sizeof (struct GNUNET_MessageHeader),
419 GNUNET_TIME_UNIT_FOREVER_REL,
420 &write_shutdown, NULL);
425 * Report service unavailable.
428 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
429 GNUNET_SCHEDULER_Task task, void *task_cls)
431 GNUNET_SCHEDULER_add_continuation (s,
435 GNUNET_SCHEDULER_REASON_TIMEOUT);
440 * Receive confirmation from test, service is up.
443 * @param msg message received, NULL on timeout or fatal error
446 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
448 struct GNUNET_CLIENT_Connection *conn = cls;
449 /* We may want to consider looking at the reply in more
450 detail in the future, for example, is this the
451 correct service? FIXME! */
455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
456 "Received confirmation that service is running.\n");
458 GNUNET_SCHEDULER_add_continuation (conn->sched,
462 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
466 service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
468 GNUNET_CLIENT_disconnect (conn);
473 write_test (void *cls, size_t size, void *buf)
475 struct GNUNET_MessageHeader *msg;
477 if (size < sizeof (struct GNUNET_MessageHeader))
480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481 _("Failure to transmit TEST request.\n"));
483 return 0; /* client disconnected */
486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
488 msg = (struct GNUNET_MessageHeader *) buf;
489 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
490 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
491 return sizeof (struct GNUNET_MessageHeader);
496 * Wait until the service is running.
498 * @param sched scheduler to use
499 * @param service name of the service to wait for
500 * @param cfg configuration to use
501 * @param timeout how long to wait at most in ms
502 * @param task task to run if service is running
503 * (reason will be "PREREQ_DONE" (service running)
504 * or "TIMEOUT" (service not known to be running))
505 * @param task_cls closure for task
508 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
510 const struct GNUNET_CONFIGURATION_Handle *cfg,
511 struct GNUNET_TIME_Relative timeout,
512 GNUNET_SCHEDULER_Task task, void *task_cls)
514 struct GNUNET_CLIENT_Connection *conn;
517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
518 "Testing if service `%s' is running.\n", service);
520 conn = GNUNET_CLIENT_connect (sched, service, cfg);
523 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
525 ("Could not connect to service `%s', must not be running.\n"),
527 service_test_error (sched, task, task_cls);
530 conn->test_cb = task;
531 conn->test_cb_cls = task_cls;
533 GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
535 GNUNET_MessageHeader),
536 timeout, &write_test, NULL))
538 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
539 _("Failure to transmit request to service `%s'\n"),
541 service_test_error (sched, task, task_cls);
542 GNUNET_CLIENT_disconnect (conn);
545 GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
550 * Handle for a transmission request.
552 struct GNUNET_CLIENT_TransmitHandle
557 struct GNUNET_CLIENT_Connection *sock;
560 * Function to call to get the data for transmission.
562 GNUNET_CONNECTION_TransmitReadyNotify notify;
565 * Closure for notify.
570 * Handle to the transmission with the underlying
573 struct GNUNET_CONNECTION_TransmitHandle *th;
578 struct GNUNET_TIME_Absolute timeout;
581 * If we are re-trying and are delaying to do so,
582 * handle to the scheduled task managing the delay.
584 GNUNET_SCHEDULER_TaskIdentifier task;
587 * Number of bytes requested.
592 * Are we allowed to re-try to connect without telling
593 * the user (of this API) about the connection troubles?
598 * Number of attempts left for transmitting the request. We may
599 * fail the first time (say because the service is not yet up), in
600 * which case (if auto_retry is set) we wait a bit and re-try
601 * (timeout permitting).
603 unsigned int attempts_left;
610 * Connection notifies us about failure or success of
611 * a transmission request. Either pass it on to our
612 * user or, if possible, retry.
614 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
615 * @param size number of bytes available for transmission
616 * @param buf where to write them
617 * @return number of bytes written to buf
620 client_notify (void *cls,
627 * This task is run if we should re-try connection to the
628 * service after a while.
630 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
634 client_delayed_retry (void *cls,
635 const struct GNUNET_SCHEDULER_TaskContext *tc)
637 struct GNUNET_CLIENT_TransmitHandle *th = cls;
639 th->task = GNUNET_SCHEDULER_NO_TASK;
640 th->sock->sock = do_connect (th->sock->sched,
641 th->sock->service_name,
643 th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
645 GNUNET_TIME_absolute_get_remaining (th->timeout),
651 th->notify (th->notify_cls, 0, NULL);
659 * Connection notifies us about failure or success of
660 * a transmission request. Either pass it on to our
661 * user or, if possible, retry.
663 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
664 * @param size number of bytes available for transmission
665 * @param buf where to write them
666 * @return number of bytes written to buf
669 client_notify (void *cls,
673 struct GNUNET_CLIENT_TransmitHandle *th = cls;
675 struct GNUNET_TIME_Relative delay;
680 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
682 if ( (GNUNET_YES != th->auto_retry) ||
683 (0 == --th->attempts_left) ||
686 GNUNET_break (0 == th->notify (th->notify_cls,
693 GNUNET_CONNECTION_destroy (th->sock->sock);
694 th->sock->sock = NULL;
695 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_SECONDS);
696 th->task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
698 GNUNET_SCHEDULER_PRIORITY_KEEP,
699 GNUNET_SCHEDULER_NO_TASK,
701 &client_delayed_retry,
705 GNUNET_assert (size >= th->size);
706 ret = th->notify (th->notify_cls,
715 * Ask the client to call us once the specified number of bytes
716 * are free in the transmission buffer. May call the notify
717 * method immediately if enough space is available.
719 * @param sock connection to the service
720 * @param size number of bytes to send
721 * @param timeout after how long should we give up (and call
722 * notify with buf NULL and size 0)?
723 * @param auto_retry if the connection to the service dies, should we
724 * automatically re-connect and retry (within the timeout period)
725 * or should we immediately fail in this case? Pass GNUNET_YES
726 * if the caller does not care about temporary connection errors,
727 * for example because the protocol is stateless
728 * @param notify function to call
729 * @param notify_cls closure for notify
730 * @return NULL if our buffer will never hold size bytes,
731 * a handle if the notify callback was queued (can be used to cancel)
733 struct GNUNET_CLIENT_TransmitHandle *
734 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
736 struct GNUNET_TIME_Relative timeout,
738 GNUNET_CONNECTION_TransmitReadyNotify
739 notify, void *notify_cls)
741 struct GNUNET_CLIENT_TransmitHandle *th;
743 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
746 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
747 th->auto_retry = auto_retry;
749 th->notify_cls = notify_cls;
750 th->attempts_left = MAX_ATTEMPTS;
751 th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
766 * Cancel a request for notification.
768 * @param th handle from the original request.
771 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle *th)
773 if (th->task != GNUNET_SCHEDULER_NO_TASK)
775 GNUNET_break (NULL == th->th);
776 GNUNET_SCHEDULER_cancel (th->sock->sched,
781 GNUNET_break (NULL != th->th);
782 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
789 * Context for processing
790 * "GNUNET_CLIENT_transmit_and_get_response" requests.
797 struct GNUNET_CLIENT_Connection *sock;
800 * Message to transmit; do not free, allocated
801 * right after this struct.
803 const struct GNUNET_MessageHeader *hdr;
808 struct GNUNET_TIME_Absolute timeout;
811 * Function to call when done.
813 GNUNET_CLIENT_MessageHandler rn;
823 * Function called to notify a client about the socket
824 * begin ready to queue the message. "buf" will be
825 * NULL and "size" zero if the socket was closed for
826 * writing in the meantime.
828 * @param cls closure of type "struct TARCtx*"
829 * @param size number of bytes available in buf
830 * @param buf where the callee should write the message
831 * @return number of bytes written to buf
834 transmit_for_response (void *cls,
838 struct TARCtx *tc = cls;
841 msize = ntohs(tc->hdr->size);
844 tc->rn (tc->rn_cls, NULL);
848 GNUNET_assert (size >= msize);
849 memcpy (buf, tc->hdr, msize);
850 GNUNET_CLIENT_receive (tc->sock,
853 GNUNET_TIME_absolute_get_remaining (tc->timeout));
860 * Convenience API that combines sending a request
861 * to the service and waiting for a response.
862 * If either operation times out, the callback
863 * will be called with a "NULL" response (in which
864 * case the connection should probably be destroyed).
866 * @param sock connection to use
867 * @param hdr message to transmit
868 * @param timeout when to give up (for both transmission
869 * and for waiting for a response)
870 * @param auto_retry if the connection to the service dies, should we
871 * automatically re-connect and retry (within the timeout period)
872 * or should we immediately fail in this case? Pass GNUNET_YES
873 * if the caller does not care about temporary connection errors,
874 * for example because the protocol is stateless
875 * @param rn function to call with the response
876 * @param rn_cls closure for rn
877 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
881 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
882 const struct GNUNET_MessageHeader *hdr,
883 struct GNUNET_TIME_Relative timeout,
885 GNUNET_CLIENT_MessageHandler rn,
891 msize = ntohs(hdr->size);
892 tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
894 tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1];
895 memcpy (&tc[1], hdr, msize);
896 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
899 if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
903 &transmit_for_response,
907 return GNUNET_SYSERR;
914 /* end of client.c */