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);
226 sock->receiver_handler = NULL;
227 if (sock->in_receive == GNUNET_YES)
228 sock->in_receive = GNUNET_SYSERR;
230 GNUNET_SCHEDULER_add_after (sock->sched,
232 GNUNET_SCHEDULER_PRIORITY_KEEP,
233 GNUNET_SCHEDULER_NO_TASK,
234 &finish_cleanup, sock);
239 * Check if message is complete
242 check_complete (struct GNUNET_CLIENT_Connection *conn)
244 if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
245 (conn->received_pos >=
246 ntohs (((const struct GNUNET_MessageHeader *) conn->
247 received_buf)->size)))
248 conn->msg_complete = GNUNET_YES;
253 * Callback function for data received from the network. Note that
254 * both "available" and "errCode" would be 0 if the read simply timed out.
257 * @param buf pointer to received data
258 * @param available number of bytes availabe in "buf",
259 * possibly 0 (on errors)
260 * @param addr address of the sender
261 * @param addrlen size of addr
262 * @param errCode value of errno (on errors receiving)
265 receive_helper (void *cls,
268 const struct sockaddr *addr, socklen_t addrlen, int errCode)
270 struct GNUNET_CLIENT_Connection *conn = cls;
271 struct GNUNET_TIME_Relative remaining;
273 GNUNET_assert (conn->msg_complete == GNUNET_NO);
274 if (GNUNET_SYSERR == conn->in_receive)
275 GNUNET_SCHEDULER_add_after (conn->sched,
277 GNUNET_SCHEDULER_PRIORITY_KEEP,
278 GNUNET_SCHEDULER_NO_TASK,
281 conn->in_receive = GNUNET_NO;
282 if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
284 /* signal timeout! */
285 if (conn->receiver_handler != NULL)
287 conn->receiver_handler (conn->receiver_handler_cls, NULL);
288 conn->receiver_handler = NULL;
293 /* FIXME: optimize for common fast case where buf contains the
294 entire message and we need no copying... */
297 /* slow path: append to array */
298 if (conn->received_size < conn->received_pos + available)
299 GNUNET_array_grow (conn->received_buf,
300 conn->received_size, conn->received_pos + available);
301 memcpy (&conn->received_buf[conn->received_pos], buf, available);
302 conn->received_pos += available;
303 check_complete (conn);
304 /* check for timeout */
305 remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
306 if (remaining.value == 0)
308 /* signal timeout! */
309 conn->receiver_handler (conn->receiver_handler_cls, NULL);
312 /* back to receive -- either for more data or to call callback! */
313 GNUNET_CLIENT_receive (conn,
314 conn->receiver_handler,
315 conn->receiver_handler_cls, remaining);
320 * Continuation to call the receive callback.
323 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
325 struct GNUNET_CLIENT_Connection *sock = scls;
326 GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
327 const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
328 void *cls = sock->receiver_handler_cls;
329 uint16_t msize = ntohs (cmsg->size);
331 struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
333 if (GNUNET_SYSERR == sock->in_receive)
334 GNUNET_SCHEDULER_add_after (sock->sched,
336 GNUNET_SCHEDULER_PRIORITY_KEEP,
337 GNUNET_SCHEDULER_NO_TASK,
340 sock->in_receive = GNUNET_NO;
341 GNUNET_assert (GNUNET_YES == sock->msg_complete);
342 GNUNET_assert (sock->received_pos >= msize);
343 memcpy (msg, cmsg, msize);
344 memmove (sock->received_buf,
345 &sock->received_buf[msize], sock->received_pos - msize);
346 sock->received_pos -= msize;
347 sock->msg_complete = GNUNET_NO;
348 sock->receiver_handler = NULL;
349 check_complete (sock);
356 * Read from the service.
358 * @param sock the service
359 * @param handler function to call with the message
360 * @param handler_cls closure for handler
361 * @param timeout how long to wait until timing out
364 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
365 GNUNET_CLIENT_MessageHandler handler,
366 void *handler_cls, struct GNUNET_TIME_Relative timeout)
368 if (sock->sock == NULL)
370 /* already disconnected, fail instantly! */
371 GNUNET_break (0); /* this should not happen in well-written code! */
372 handler (handler_cls, NULL);
375 sock->receiver_handler = handler;
376 sock->receiver_handler_cls = handler_cls;
377 sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
378 sock->in_receive = GNUNET_YES;
379 if (GNUNET_YES == sock->msg_complete)
380 GNUNET_SCHEDULER_add_after (sock->sched,
382 GNUNET_SCHEDULER_PRIORITY_KEEP,
383 GNUNET_SCHEDULER_NO_TASK,
384 &receive_task, sock);
386 GNUNET_CONNECTION_receive (sock->sock,
387 GNUNET_SERVER_MAX_MESSAGE_SIZE,
389 &receive_helper, sock);
394 write_shutdown (void *cls, size_t size, void *buf)
396 struct GNUNET_MessageHeader *msg;
398 if (size < sizeof (struct GNUNET_MessageHeader))
399 return 0; /* client disconnected */
400 msg = (struct GNUNET_MessageHeader *) buf;
401 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
402 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
403 return sizeof (struct GNUNET_MessageHeader);
408 * Request that the service should shutdown.
409 * Afterwards, the connection should be disconnected.
411 * @param sock the socket connected to the service
414 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
416 GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
417 sizeof (struct GNUNET_MessageHeader),
418 GNUNET_TIME_UNIT_FOREVER_REL,
419 &write_shutdown, NULL);
424 * Report service unavailable.
427 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
428 GNUNET_SCHEDULER_Task task, void *task_cls)
430 GNUNET_SCHEDULER_add_continuation (s,
434 GNUNET_SCHEDULER_REASON_TIMEOUT);
439 * Receive confirmation from test, service is up.
442 * @param msg message received, NULL on timeout or fatal error
445 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
447 struct GNUNET_CLIENT_Connection *conn = cls;
448 /* We may want to consider looking at the reply in more
449 detail in the future, for example, is this the
450 correct service? FIXME! */
454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
455 "Received confirmation that service is running.\n");
457 GNUNET_SCHEDULER_add_continuation (conn->sched,
461 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
465 service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
467 GNUNET_CLIENT_disconnect (conn);
472 write_test (void *cls, size_t size, void *buf)
474 struct GNUNET_MessageHeader *msg;
476 if (size < sizeof (struct GNUNET_MessageHeader))
479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
480 _("Failure to transmit TEST request.\n"));
482 return 0; /* client disconnected */
485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
487 msg = (struct GNUNET_MessageHeader *) buf;
488 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
489 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
490 return sizeof (struct GNUNET_MessageHeader);
495 * Wait until the service is running.
497 * @param sched scheduler to use
498 * @param service name of the service to wait for
499 * @param cfg configuration to use
500 * @param timeout how long to wait at most in ms
501 * @param task task to run if service is running
502 * (reason will be "PREREQ_DONE" (service running)
503 * or "TIMEOUT" (service not known to be running))
504 * @param task_cls closure for task
507 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
509 const struct GNUNET_CONFIGURATION_Handle *cfg,
510 struct GNUNET_TIME_Relative timeout,
511 GNUNET_SCHEDULER_Task task, void *task_cls)
513 struct GNUNET_CLIENT_Connection *conn;
516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
517 "Testing if service `%s' is running.\n", service);
519 conn = GNUNET_CLIENT_connect (sched, service, cfg);
522 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
524 ("Could not connect to service `%s', must not be running.\n"),
526 service_test_error (sched, task, task_cls);
529 conn->test_cb = task;
530 conn->test_cb_cls = task_cls;
532 GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
534 GNUNET_MessageHeader),
535 timeout, &write_test, NULL))
537 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
538 _("Failure to transmit request to service `%s'\n"),
540 service_test_error (sched, task, task_cls);
541 GNUNET_CLIENT_disconnect (conn);
544 GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
549 * Handle for a transmission request.
551 struct GNUNET_CLIENT_TransmitHandle
556 struct GNUNET_CLIENT_Connection *sock;
559 * Function to call to get the data for transmission.
561 GNUNET_CONNECTION_TransmitReadyNotify notify;
564 * Closure for notify.
569 * Handle to the transmission with the underlying
572 struct GNUNET_CONNECTION_TransmitHandle *th;
577 struct GNUNET_TIME_Absolute timeout;
580 * If we are re-trying and are delaying to do so,
581 * handle to the scheduled task managing the delay.
583 GNUNET_SCHEDULER_TaskIdentifier task;
586 * Number of bytes requested.
591 * Are we allowed to re-try to connect without telling
592 * the user (of this API) about the connection troubles?
597 * Number of attempts left for transmitting the request. We may
598 * fail the first time (say because the service is not yet up), in
599 * which case (if auto_retry is set) we wait a bit and re-try
600 * (timeout permitting).
602 unsigned int attempts_left;
609 * Connection notifies us about failure or success of
610 * a transmission request. Either pass it on to our
611 * user or, if possible, retry.
613 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
614 * @param size number of bytes available for transmission
615 * @param buf where to write them
616 * @return number of bytes written to buf
619 client_notify (void *cls,
626 * This task is run if we should re-try connection to the
627 * service after a while.
629 * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
633 client_delayed_retry (void *cls,
634 const struct GNUNET_SCHEDULER_TaskContext *tc)
636 struct GNUNET_CLIENT_TransmitHandle *th = cls;
638 th->task = GNUNET_SCHEDULER_NO_TASK;
639 th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
641 GNUNET_TIME_absolute_get_remaining (th->timeout),
647 th->notify (th->notify_cls, 0, NULL);
655 * Connection notifies us about failure or success of
656 * a transmission request. Either pass it on to our
657 * user or, if possible, retry.
659 * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
660 * @param size number of bytes available for transmission
661 * @param buf where to write them
662 * @return number of bytes written to buf
665 client_notify (void *cls,
669 struct GNUNET_CLIENT_TransmitHandle *th = cls;
671 struct GNUNET_TIME_Relative delay;
676 delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
678 if ( (GNUNET_YES != th->auto_retry) ||
679 (0 == --th->attempts_left) ||
682 GNUNET_break (0 == th->notify (th->notify_cls,
689 GNUNET_CONNECTION_destroy (th->sock->sock);
690 th->sock->sock = do_connect (th->sock->sched,
691 th->sock->service_name,
693 delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_SECONDS);
694 th->task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
696 GNUNET_SCHEDULER_PRIORITY_KEEP,
697 GNUNET_SCHEDULER_NO_TASK,
699 &client_delayed_retry,
703 GNUNET_assert (size >= th->size);
704 ret = th->notify (th->notify_cls,
713 * Ask the client to call us once the specified number of bytes
714 * are free in the transmission buffer. May call the notify
715 * method immediately if enough space is available.
717 * @param sock connection to the service
718 * @param size number of bytes to send
719 * @param timeout after how long should we give up (and call
720 * notify with buf NULL and size 0)?
721 * @param auto_retry if the connection to the service dies, should we
722 * automatically re-connect and retry (within the timeout period)
723 * or should we immediately fail in this case? Pass GNUNET_YES
724 * if the caller does not care about temporary connection errors,
725 * for example because the protocol is stateless
726 * @param notify function to call
727 * @param notify_cls closure for notify
728 * @return NULL if our buffer will never hold size bytes,
729 * a handle if the notify callback was queued (can be used to cancel)
731 struct GNUNET_CLIENT_TransmitHandle *
732 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
734 struct GNUNET_TIME_Relative timeout,
736 GNUNET_CONNECTION_TransmitReadyNotify
737 notify, void *notify_cls)
739 struct GNUNET_CLIENT_TransmitHandle *th;
741 th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
744 th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
745 th->auto_retry = auto_retry;
747 th->notify_cls = notify_cls;
748 th->attempts_left = MAX_ATTEMPTS;
749 th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
764 * Cancel a request for notification.
766 * @param th handle from the original request.
769 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle *th)
771 if (th->task != GNUNET_SCHEDULER_NO_TASK)
773 GNUNET_break (NULL == th->th);
774 GNUNET_SCHEDULER_cancel (th->sock->sched,
779 GNUNET_break (NULL != th->th);
780 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
787 * Context for processing
788 * "GNUNET_CLIENT_transmit_and_get_response" requests.
795 struct GNUNET_CLIENT_Connection *sock;
798 * Message to transmit; do not free, allocated
799 * right after this struct.
801 const struct GNUNET_MessageHeader *hdr;
806 struct GNUNET_TIME_Absolute timeout;
809 * Function to call when done.
811 GNUNET_CLIENT_MessageHandler rn;
821 * Function called to notify a client about the socket
822 * begin ready to queue the message. "buf" will be
823 * NULL and "size" zero if the socket was closed for
824 * writing in the meantime.
826 * @param cls closure of type "struct TARCtx*"
827 * @param size number of bytes available in buf
828 * @param buf where the callee should write the message
829 * @return number of bytes written to buf
832 transmit_for_response (void *cls,
836 struct TARCtx *tc = cls;
839 msize = ntohs(tc->hdr->size);
842 tc->rn (tc->rn_cls, NULL);
846 GNUNET_assert (size >= msize);
847 memcpy (buf, tc->hdr, msize);
848 GNUNET_CLIENT_receive (tc->sock,
851 GNUNET_TIME_absolute_get_remaining (tc->timeout));
858 * Convenience API that combines sending a request
859 * to the service and waiting for a response.
860 * If either operation times out, the callback
861 * will be called with a "NULL" response (in which
862 * case the connection should probably be destroyed).
864 * @param sock connection to use
865 * @param hdr message to transmit
866 * @param timeout when to give up (for both transmission
867 * and for waiting for a response)
868 * @param auto_retry if the connection to the service dies, should we
869 * automatically re-connect and retry (within the timeout period)
870 * or should we immediately fail in this case? Pass GNUNET_YES
871 * if the caller does not care about temporary connection errors,
872 * for example because the protocol is stateless
873 * @param rn function to call with the response
874 * @param rn_cls closure for rn
875 * @return GNUNET_OK on success, GNUNET_SYSERR if a request
879 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
880 const struct GNUNET_MessageHeader *hdr,
881 struct GNUNET_TIME_Relative timeout,
883 GNUNET_CLIENT_MessageHandler rn,
889 msize = ntohs(hdr->size);
890 tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
892 tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1];
893 memcpy (&tc[1], hdr, msize);
894 tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
897 if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
901 &transmit_for_response,
905 return GNUNET_SYSERR;
912 /* end of client.c */