2 This file is part of GNUnet.
3 (C) 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.
22 * @file transport/gnunet-service-transport.c
23 * @brief low-level P2P messaging
24 * @author Christian Grothoff
27 * - if we do not receive an ACK in response to our
28 * HELLO, retransmit HELLO!
31 #include "gnunet_client_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_getopt_lib.h"
34 #include "gnunet_hello_lib.h"
35 #include "gnunet_os_lib.h"
36 #include "gnunet_peerinfo_service.h"
37 #include "gnunet_plugin_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_service_lib.h"
40 #include "gnunet_signatures.h"
41 #include "plugin_transport.h"
42 #include "transport.h"
45 * How many messages can we have pending for a given client process
46 * before we start to drop incoming messages? We typically should
47 * have only one client and so this would be the primary buffer for
48 * messages, so the number should be chosen rather generously.
50 * The expectation here is that most of the time the queue is large
51 * enough so that a drop is virtually never required.
53 #define MAX_PENDING 128
56 * How often should we try to reconnect to a peer using a particular
57 * transport plugin before giving up? Note that the plugin may be
58 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
60 #define MAX_CONNECT_RETRY 3
63 * How often must a peer violate bandwidth quotas before we start
64 * to simply drop its messages?
66 #define QUOTA_VIOLATION_DROP_THRESHOLD 100
69 * How long until a HELLO verification attempt should time out?
70 * Must be rather small, otherwise a partially successful HELLO
71 * validation (some addresses working) might not be available
72 * before a client's request for a connection fails for good.
73 * Besides, if a single request to an address takes a long time,
74 * then the peer is unlikely worthwhile anyway.
76 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
79 * How often do we re-add (cheaper) plugins to our list of plugins
80 * to try for a given connected peer?
82 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
85 * After how long do we expire an address in a HELLO
86 * that we just validated? This value is also used
87 * for our own addresses when we create a HELLO.
89 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
93 * Entry in linked list of network addresses.
98 * This is a linked list.
100 struct AddressList *next;
103 * The address, actually a pointer to the end
104 * of this struct. Do not free!
109 * How long until we auto-expire this address (unless it is
110 * re-confirmed by the transport)?
112 struct GNUNET_TIME_Absolute expires;
123 * Entry in linked list of all of our plugins.
125 struct TransportPlugin
129 * This is a linked list.
131 struct TransportPlugin *next;
134 * API of the transport as returned by the plugin's
135 * initialization function.
137 struct GNUNET_TRANSPORT_PluginFunctions *api;
140 * Short name for the plugin (i.e. "tcp").
145 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
150 * List of our known addresses for this transport.
152 struct AddressList *addresses;
155 * Environment this transport service is using
158 struct GNUNET_TRANSPORT_PluginEnvironment env;
161 * ID of task that is used to clean up expired addresses.
163 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
167 * Set to GNUNET_YES if we need to scrap the existing
168 * list of "addresses" and start fresh when we receive
169 * the next address update from a transport. Set to
170 * GNUNET_NO if we should just add the new address
171 * to the list and wait for the commit call.
176 struct NeighbourList;
179 * For each neighbour we keep a list of messages
180 * that we still want to transmit to the neighbour.
186 * This is a linked list.
188 struct MessageQueue *next;
191 * The message we want to transmit.
193 struct GNUNET_MessageHeader *message;
196 * Client responsible for queueing the message;
197 * used to check that a client has not two messages
198 * pending for the same target. Can be NULL.
200 struct TransportClient *client;
203 * Neighbour this entry belongs to.
205 struct NeighbourList *neighbour;
208 * Plugin that we used for the transmission.
209 * NULL until we scheduled a transmission.
211 struct TransportPlugin *plugin;
214 * Internal message of the transport system that should not be
215 * included in the usual SEND-SEND_OK transmission confirmation
216 * traffic management scheme. Typically, "internal_msg" will
217 * be set whenever "client" is NULL (but it is not strictly
223 * How important is the message?
225 unsigned int priority;
231 * For a given Neighbour, which plugins are available
232 * to talk to this peer and what are their costs?
238 * This is a linked list.
240 struct ReadyList *next;
243 * Which of our transport plugins does this entry
246 struct TransportPlugin *plugin;
249 * Neighbour this entry belongs to.
251 struct NeighbourList *neighbour;
254 * Opaque handle (specific to the plugin) for the
255 * connection to our target; can be NULL.
260 * What was the last latency observed for this plugin
261 * and peer? Invalid if connected is GNUNET_NO.
263 struct GNUNET_TIME_Relative latency;
266 * If we did not successfully transmit a message to the
267 * given peer via this connection during the specified
268 * time, we should consider the connection to be dead.
269 * This is used in the case that a TCP transport simply
270 * stalls writing to the stream but does not formerly
271 * get a signal that the other peer died.
273 struct GNUNET_TIME_Absolute timeout;
276 * Is this plugin currently connected? The first time
277 * we transmit or send data to a peer via a particular
278 * plugin, we set this to GNUNET_YES. If we later get
279 * an error (disconnect notification or transmission
280 * failure), we set it back to GNUNET_NO. Each time the
281 * value is set to GNUNET_YES, we increment the
282 * "connect_attempts" counter. If that one reaches a
283 * particular threshold, we consider the plugin to not
284 * be working properly at this time for the given peer
285 * and remove it from the eligible list.
290 * How often have we tried to connect using this plugin?
292 unsigned int connect_attempts;
295 * Is this plugin ready to transmit to the specific
296 * target? GNUNET_NO if not. Initially, all plugins
297 * are marked ready. If a transmission is in progress,
298 * "transmit_ready" is set to GNUNET_NO.
306 * Entry in linked list of all of our current neighbours.
312 * This is a linked list.
314 struct NeighbourList *next;
317 * Which of our transports is connected to this peer
318 * and what is their status?
320 struct ReadyList *plugins;
323 * List of messages we would like to send to this peer;
324 * must contain at most one message per client.
326 struct MessageQueue *messages;
329 * Identity of this neighbour.
331 struct GNUNET_PeerIdentity id;
334 * ID of task scheduled to run when this peer is about to
335 * time out (will free resources associated with the peer).
337 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
340 * How long until we should consider this peer dead
341 * (if we don't receive another message in the
344 struct GNUNET_TIME_Absolute peer_timeout;
347 * At what time did we reset last_received last?
349 struct GNUNET_TIME_Absolute last_quota_update;
352 * At what time should we try to again add plugins to
355 struct GNUNET_TIME_Absolute retry_plugins_time;
358 * How many bytes have we received since the "last_quota_update"
361 uint64_t last_received;
364 * Global quota for inbound traffic for the neighbour in bytes/ms.
369 * How often has the other peer (recently) violated the
370 * inbound traffic limit? Incremented by 10 per violation,
371 * decremented by 1 per non-violation (for each
374 unsigned int quota_violation_count;
377 * Have we seen an ACK from this neighbour in the past?
378 * (used to make up a fake ACK for clients connecting after
379 * the neighbour connected to us).
387 * Linked list of messages to be transmitted to
388 * the client. Each entry is followed by the
391 struct ClientMessageQueueEntry
394 * This is a linked list.
396 struct ClientMessageQueueEntry *next;
401 * Client connected to the transport service.
403 struct TransportClient
407 * This is a linked list.
409 struct TransportClient *next;
412 * Handle to the client.
414 struct GNUNET_SERVER_Client *client;
417 * Linked list of messages yet to be transmitted to
420 struct ClientMessageQueueEntry *message_queue_head;
423 * Tail of linked list of messages yet to be transmitted to the
426 struct ClientMessageQueueEntry *message_queue_tail;
429 * Is a call to "transmit_send_continuation" pending? If so, we
430 * must not free this struct (even if the corresponding client
431 * disconnects) and instead only remove it from the linked list and
432 * set the "client" field to NULL.
437 * Length of the list of messages pending for this client.
439 unsigned int message_count;
445 * For each HELLO, we may have to validate multiple addresses;
446 * each address gets its own request entry.
448 struct ValidationAddress
451 * This is a linked list.
453 struct ValidationAddress *next;
456 * Name of the transport.
458 char *transport_name;
461 * When should this validated address expire?
463 struct GNUNET_TIME_Absolute expiration;
466 * Length of the address we are validating.
471 * Challenge number we used.
476 * Set to GNUNET_YES if the challenge was met,
477 * GNUNET_SYSERR if we know it failed, GNUNET_NO
478 * if we are waiting on a response.
485 * Entry in linked list of all HELLOs awaiting validation.
487 struct ValidationList
491 * This is a linked list.
493 struct ValidationList *next;
496 * Linked list with one entry per address from the HELLO
497 * that needs to be validated.
499 struct ValidationAddress *addresses;
502 * The public key of the peer.
504 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
507 * When does this record time-out? (assuming the
508 * challenge goes unanswered)
510 struct GNUNET_TIME_Absolute timeout;
516 * HELLOs awaiting validation.
518 static struct ValidationList *pending_validations;
523 static struct GNUNET_HELLO_Message *our_hello;
526 * "version" of "our_hello". Used to see if a given
527 * neighbour has already been sent the latest version
528 * of our HELLO message.
530 static unsigned int our_hello_version;
535 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
540 static struct GNUNET_PeerIdentity my_identity;
545 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
550 struct GNUNET_SCHEDULER_Handle *sched;
555 const struct GNUNET_CONFIGURATION_Handle *cfg;
558 * Linked list of all clients to this service.
560 static struct TransportClient *clients;
563 * All loaded plugins.
565 static struct TransportPlugin *plugins;
570 static struct GNUNET_SERVER_Handle *server;
573 * All known neighbours and their HELLOs.
575 static struct NeighbourList *neighbours;
578 * Number of neighbours we'd like to have.
580 static uint32_t max_connect_per_transport;
584 * Find an entry in the neighbour list for a particular peer.
586 * @return NULL if not found.
588 static struct NeighbourList *
589 find_neighbour (const struct GNUNET_PeerIdentity *key)
591 struct NeighbourList *head = neighbours;
592 while ((head != NULL) &&
593 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
600 * Find an entry in the transport list for a particular transport.
602 * @return NULL if not found.
604 static struct TransportPlugin *
605 find_transport (const char *short_name)
607 struct TransportPlugin *head = plugins;
608 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
615 * Update the quota values for the given neighbour now.
618 update_quota (struct NeighbourList *n)
620 struct GNUNET_TIME_Relative delta;
624 delta = GNUNET_TIME_absolute_get_duration (n->last_quota_update);
625 if (delta.value < MIN_QUOTA_REFRESH_TIME)
626 return; /* not enough time passed for doing quota update */
627 allowed = delta.value * n->quota_in;
628 if (n->last_received < allowed)
630 remaining = allowed - n->last_received;
632 remaining /= n->quota_in;
635 if (remaining > MAX_BANDWIDTH_CARRY)
636 remaining = MAX_BANDWIDTH_CARRY;
637 n->last_received = 0;
638 n->last_quota_update = GNUNET_TIME_absolute_get ();
639 n->last_quota_update.value -= remaining;
640 if (n->quota_violation_count > 0)
641 n->quota_violation_count--;
645 n->last_received -= allowed;
646 n->last_quota_update = GNUNET_TIME_absolute_get ();
647 if (n->last_received > allowed)
649 /* more than twice the allowed rate! */
650 n->quota_violation_count += 10;
657 * Function called to notify a client about the socket
658 * being ready to queue more data. "buf" will be
659 * NULL and "size" zero if the socket was closed for
660 * writing in the meantime.
663 * @param size number of bytes available in buf
664 * @param buf where the callee should write the message
665 * @return number of bytes written to buf
668 transmit_to_client_callback (void *cls, size_t size, void *buf)
670 struct TransportClient *client = cls;
671 struct ClientMessageQueueEntry *q;
674 const struct GNUNET_MessageHeader *msg;
675 struct GNUNET_CONNECTION_TransmitHandle *th;
680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681 "Transmission to client failed, closing connection.\n");
682 /* fatal error with client, free message queue! */
683 while (NULL != (q = client->message_queue_head))
685 client->message_queue_head = q->next;
688 client->message_queue_tail = NULL;
689 client->message_count = 0;
694 while (NULL != (q = client->message_queue_head))
696 msg = (const struct GNUNET_MessageHeader *) &q[1];
697 msize = ntohs (msg->size);
698 if (msize + tsize > size)
701 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
702 "Transmitting message of type %u to client.\n",
705 client->message_queue_head = q->next;
707 client->message_queue_tail = NULL;
708 memcpy (&cbuf[tsize], msg, msize);
711 client->message_count--;
715 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
716 th = GNUNET_SERVER_notify_transmit_ready (client->client,
718 GNUNET_TIME_UNIT_FOREVER_REL,
719 &transmit_to_client_callback,
721 GNUNET_assert (th != NULL);
728 * Send the specified message to the specified client. Since multiple
729 * messages may be pending for the same client at a time, this code
730 * makes sure that no message is lost.
732 * @param client client to transmit the message to
733 * @param msg the message to send
734 * @param may_drop can this message be dropped if the
735 * message queue for this client is getting far too large?
738 transmit_to_client (struct TransportClient *client,
739 const struct GNUNET_MessageHeader *msg, int may_drop)
741 struct ClientMessageQueueEntry *q;
743 struct GNUNET_CONNECTION_TransmitHandle *th;
745 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
747 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
749 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
750 client->message_count, MAX_PENDING);
751 /* TODO: call to statistics... */
754 client->message_count++;
755 msize = ntohs (msg->size);
756 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
757 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
758 memcpy (&q[1], msg, msize);
759 /* append to message queue */
760 if (client->message_queue_tail == NULL)
762 client->message_queue_tail = q;
766 client->message_queue_tail->next = q;
767 client->message_queue_tail = q;
769 if (client->message_queue_head == NULL)
771 client->message_queue_head = q;
772 th = GNUNET_SERVER_notify_transmit_ready (client->client,
774 GNUNET_TIME_UNIT_FOREVER_REL,
775 &transmit_to_client_callback,
777 GNUNET_assert (th != NULL);
783 * Find alternative plugins for communication.
785 * @param neighbour for which neighbour should we try to find
789 try_alternative_plugins (struct NeighbourList *neighbour)
791 struct ReadyList *rl;
793 if ((neighbour->plugins != NULL) &&
794 (neighbour->retry_plugins_time.value >
795 GNUNET_TIME_absolute_get ().value))
796 return; /* don't try right now */
797 neighbour->retry_plugins_time
798 = GNUNET_TIME_relative_to_absolute (PLUGIN_RETRY_FREQUENCY);
800 rl = neighbour->plugins;
803 if (rl->connect_attempts > 0)
804 rl->connect_attempts--; /* amnesty */
812 * The peer specified by the given neighbour has timed-out or a plugin
813 * has disconnected. We may either need to do nothing (other plugins
814 * still up), or trigger a full disconnect and clean up. This
815 * function updates our state and do the necessary notifications.
816 * Also notifies our clients that the neighbour is now officially
819 * @param n the neighbour list entry for the peer
820 * @param check should we just check if all plugins
821 * disconnected or must we ask all plugins to
825 disconnect_neighbour (struct NeighbourList *n,
830 * Check the ready list for the given neighbour and
831 * if a plugin is ready for transmission (and if we
832 * have a message), do so!
834 * @param neighbour target peer for which to check the plugins
837 try_transmission_to_peer (struct NeighbourList *neighbour);
841 * Function called by the GNUNET_TRANSPORT_TransmitFunction
842 * upon "completion" of a send request. This tells the API
843 * that it is now legal to send another message to the given
846 * @param cls closure, identifies the entry on the
847 * message queue that was transmitted and the
848 * client responsible for queueing the message
849 * @param rl identifies plugin used for the transmission for
850 * this neighbour; needs to be re-enabled for
851 * future transmissions
852 * @param target the peer receiving the message
853 * @param result GNUNET_OK on success, if the transmission
854 * failed, we should not tell the client to transmit
858 transmit_send_continuation (void *cls,
859 struct ReadyList *rl,
860 const struct GNUNET_PeerIdentity *target,
863 struct MessageQueue *mq = cls;
864 struct SendOkMessage send_ok_msg;
865 struct NeighbourList *n;
867 GNUNET_assert (mq != NULL);
869 GNUNET_assert (n != NULL);
871 memcmp (&n->id, target,
872 sizeof (struct GNUNET_PeerIdentity)));
876 while ((rl != NULL) && (rl->plugin != mq->plugin))
878 GNUNET_assert (rl != NULL);
880 if (result == GNUNET_OK)
882 rl->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887 "Transmission to peer `%s' failed, marking connection as down.\n",
889 rl->connected = GNUNET_NO;
890 rl->plugin_handle = NULL;
892 if (!mq->internal_msg)
893 rl->transmit_ready = GNUNET_YES;
894 if (mq->client != NULL)
896 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
897 "Notifying client %p about failed transission to peer `%4s'.\n",
900 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
901 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
902 send_ok_msg.success = htonl (result);
903 send_ok_msg.peer = n->id;
904 transmit_to_client (mq->client, &send_ok_msg.header, GNUNET_NO);
906 GNUNET_free (mq->message);
908 /* one plugin just became ready again, try transmitting
909 another message (if available) */
910 if (result == GNUNET_OK)
911 try_transmission_to_peer (n);
913 disconnect_neighbour (n, GNUNET_YES);
918 * Check the ready list for the given neighbour and
919 * if a plugin is ready for transmission (and if we
920 * have a message), do so!
923 try_transmission_to_peer (struct NeighbourList *neighbour)
925 struct ReadyList *pos;
926 struct GNUNET_TIME_Relative min_latency;
927 struct ReadyList *rl;
928 struct MessageQueue *mq;
929 struct GNUNET_TIME_Absolute now;
931 if (neighbour->messages == NULL)
932 return; /* nothing to do */
933 try_alternative_plugins (neighbour);
934 min_latency = GNUNET_TIME_UNIT_FOREVER_REL;
936 mq = neighbour->messages;
937 now = GNUNET_TIME_absolute_get ();
938 pos = neighbour->plugins;
941 /* set plugins that are inactive for a long time back to disconnected */
942 if ((pos->timeout.value < now.value) && (pos->connected == GNUNET_YES))
945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946 "Marking long-time inactive connection to `%4s' as down.\n",
947 GNUNET_i2s (&neighbour->id));
949 pos->connected = GNUNET_NO;
951 if (((GNUNET_YES == pos->transmit_ready) ||
952 (mq->internal_msg)) &&
953 (pos->connect_attempts < MAX_CONNECT_RETRY) &&
954 ((rl == NULL) || (min_latency.value > pos->latency.value)))
957 min_latency = pos->latency;
964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965 "No plugin ready to transmit message\n");
967 return; /* nobody ready */
969 if (GNUNET_NO == rl->connected)
971 rl->connect_attempts++;
972 rl->connected = GNUNET_YES;
974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975 "Establishing fresh connection with `%4s' via plugin `%s'\n",
976 GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
979 neighbour->messages = mq->next;
980 mq->plugin = rl->plugin;
981 if (!mq->internal_msg)
982 rl->transmit_ready = GNUNET_NO;
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Giving message of type `%u' for `%4s' to plugin `%s'\n",
986 ntohs (mq->message->type),
987 GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
990 = rl->plugin->api->send (rl->plugin->api->cls,
996 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
997 &transmit_send_continuation, mq);
1002 * Send the specified message to the specified peer.
1004 * @param client source of the transmission request (can be NULL)
1005 * @param priority how important is the message
1006 * @param msg message to send
1007 * @param is_internal is this an internal message
1008 * @param neighbour handle to the neighbour for transmission
1011 transmit_to_peer (struct TransportClient *client,
1012 unsigned int priority,
1013 const struct GNUNET_MessageHeader *msg,
1014 int is_internal, struct NeighbourList *neighbour)
1016 struct MessageQueue *mq;
1017 struct MessageQueue *mqe;
1018 struct GNUNET_MessageHeader *m;
1021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1022 _("Sending message of type %u to peer `%4s'\n"),
1023 ntohs (msg->type), GNUNET_i2s (&neighbour->id));
1027 /* check for duplicate submission */
1028 mq = neighbour->messages;
1031 if (mq->client == client)
1033 /* client transmitted to same peer twice
1034 before getting SendOk! */
1041 mq = GNUNET_malloc (sizeof (struct MessageQueue));
1042 mq->client = client;
1043 m = GNUNET_malloc (ntohs (msg->size));
1044 memcpy (m, msg, ntohs (msg->size));
1046 mq->neighbour = neighbour;
1047 mq->internal_msg = is_internal;
1048 mq->priority = priority;
1051 mqe = neighbour->messages;
1053 while (mqe->next != NULL)
1058 neighbour->messages = mq;
1059 try_transmission_to_peer (neighbour);
1072 struct GeneratorContext
1074 struct TransportPlugin *plug_pos;
1075 struct AddressList *addr_pos;
1076 struct GNUNET_TIME_Absolute expiration;
1084 address_generator (void *cls, size_t max, void *buf)
1086 struct GeneratorContext *gc = cls;
1089 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1091 gc->plug_pos = gc->plug_pos->next;
1092 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1094 if (NULL == gc->plug_pos)
1096 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1099 gc->addr_pos->addrlen, buf, max);
1100 gc->addr_pos = gc->addr_pos->next;
1106 * Construct our HELLO message from all of the addresses of
1107 * all of the transports.
1112 struct GNUNET_HELLO_Message *hello;
1113 struct TransportClient *cpos;
1114 struct NeighbourList *npos;
1115 struct GeneratorContext gc;
1118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1119 "Refreshing my `%s'\n",
1122 gc.plug_pos = plugins;
1123 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1124 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1125 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1127 while (cpos != NULL)
1129 transmit_to_client (cpos,
1130 (const struct GNUNET_MessageHeader *) hello,
1135 GNUNET_free_non_null (our_hello);
1137 our_hello_version++;
1139 while (npos != NULL)
1142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1143 "Transmitting updated `%s' to neighbour `%4s'\n",
1145 GNUNET_i2s(&npos->id));
1147 transmit_to_peer (NULL, 0,
1148 (const struct GNUNET_MessageHeader *) our_hello,
1156 * Task used to clean up expired addresses for a plugin.
1158 * @param cls closure
1162 expire_address_task (void *cls,
1163 const struct GNUNET_SCHEDULER_TaskContext *tc);
1167 * Update the list of addresses for this plugin,
1168 * expiring those that are past their expiration date.
1170 * @param plugin addresses of which plugin should be recomputed?
1171 * @param fresh set to GNUNET_YES if a new address was added
1172 * and we need to regenerate the HELLO even if nobody
1176 update_addresses (struct TransportPlugin *plugin, int fresh)
1178 struct GNUNET_TIME_Relative min_remaining;
1179 struct GNUNET_TIME_Relative remaining;
1180 struct GNUNET_TIME_Absolute now;
1181 struct AddressList *pos;
1182 struct AddressList *prev;
1183 struct AddressList *next;
1186 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1187 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1188 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1189 now = GNUNET_TIME_absolute_get ();
1190 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1191 expired = GNUNET_NO;
1193 pos = plugin->addresses;
1197 if (pos->expires.value < now.value)
1199 expired = GNUNET_YES;
1201 plugin->addresses = pos->next;
1203 prev->next = pos->next;
1208 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1209 if (remaining.value < min_remaining.value)
1210 min_remaining = remaining;
1216 if (expired || fresh)
1218 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1219 plugin->address_update_task
1220 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1222 &expire_address_task, plugin);
1228 * Task used to clean up expired addresses for a plugin.
1230 * @param cls closure
1234 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1236 struct TransportPlugin *plugin = cls;
1237 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1238 update_addresses (plugin, GNUNET_NO);
1243 * Function that must be called by each plugin to notify the
1244 * transport service about the addresses under which the transport
1245 * provided by the plugin can be reached.
1247 * @param cls closure
1248 * @param name name of the transport that generated the address
1249 * @param addr one of the addresses of the host, NULL for the last address
1250 * the specific address format depends on the transport
1251 * @param addrlen length of the address
1252 * @param expires when should this address automatically expire?
1255 plugin_env_notify_address (void *cls,
1259 struct GNUNET_TIME_Relative expires)
1261 struct TransportPlugin *p = cls;
1262 struct AddressList *al;
1263 struct GNUNET_TIME_Absolute abex;
1265 abex = GNUNET_TIME_relative_to_absolute (expires);
1266 GNUNET_assert (p == find_transport (name));
1271 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1273 if (al->expires.value < abex.value)
1280 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1281 "Plugin `%s' informs us about a new address `%s'\n", name,
1282 GNUNET_a2s(addr, addrlen));
1284 al = GNUNET_malloc (sizeof (struct AddressList) + addrlen);
1286 al->next = p->addresses;
1289 al->addrlen = addrlen;
1290 memcpy (&al[1], addr, addrlen);
1291 update_addresses (p, GNUNET_YES);
1298 struct LookupHelloContext
1300 GNUNET_TRANSPORT_AddressCallback iterator;
1310 lookup_address_callback (void *cls,
1312 struct GNUNET_TIME_Absolute expiration,
1313 const void *addr, size_t addrlen)
1315 struct LookupHelloContext *lhc = cls;
1316 lhc->iterator (lhc->iterator_cls, tname, addr, addrlen);
1325 lookup_hello_callback (void *cls,
1326 const struct GNUNET_PeerIdentity *peer,
1327 const struct GNUNET_HELLO_Message *h, uint32_t trust)
1329 struct LookupHelloContext *lhc = cls;
1333 lhc->iterator (lhc->iterator_cls, NULL, NULL, 0);
1339 GNUNET_HELLO_iterate_addresses (h,
1340 GNUNET_NO, &lookup_address_callback, lhc);
1345 * Function that allows a transport to query the known
1346 * network addresses for a given peer.
1348 * @param cls closure
1349 * @param timeout after how long should we time out?
1350 * @param target which peer are we looking for?
1351 * @param iter function to call for each known address
1352 * @param iter_cls closure for iter
1355 plugin_env_lookup_address (void *cls,
1356 struct GNUNET_TIME_Relative timeout,
1357 const struct GNUNET_PeerIdentity *target,
1358 GNUNET_TRANSPORT_AddressCallback iter,
1361 struct LookupHelloContext *lhc;
1363 lhc = GNUNET_malloc (sizeof (struct LookupHelloContext));
1364 lhc->iterator = iter;
1365 lhc->iterator_cls = iter_cls;
1366 GNUNET_PEERINFO_for_all (cfg,
1368 target, 0, timeout, &lookup_hello_callback, &lhc);
1373 * Notify all of our clients about a peer connecting.
1376 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1377 struct GNUNET_TIME_Relative latency)
1379 struct ConnectInfoMessage cim;
1380 struct TransportClient *cpos;
1383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1384 "Informing clients about peer `%4s' connecting to us\n",
1387 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1388 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1389 cim.quota_out = htonl (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT / (60*1000));
1390 cim.latency = GNUNET_TIME_relative_hton (latency);
1391 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1393 while (cpos != NULL)
1395 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1402 * Notify all of our clients about a peer disconnecting.
1405 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1407 struct DisconnectInfoMessage dim;
1408 struct TransportClient *cpos;
1411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412 "Informing clients about peer `%4s' disconnecting\n",
1415 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1416 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1417 dim.reserved = htonl (0);
1418 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1420 while (cpos != NULL)
1422 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1429 * Copy any validated addresses to buf.
1431 * @return 0 once all addresses have been
1435 list_validated_addresses (void *cls, size_t max, void *buf)
1437 struct ValidationAddress **va = cls;
1440 while ((NULL != *va) && ((*va)->ok != GNUNET_YES))
1444 ret = GNUNET_HELLO_add_address ((*va)->transport_name,
1446 &(*va)[1], (*va)->addr_len, buf, max);
1453 * HELLO validation cleanup task.
1456 cleanup_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1458 struct ValidationAddress *va;
1459 struct ValidationList *pos;
1460 struct ValidationList *prev;
1461 struct GNUNET_TIME_Absolute now;
1462 struct GNUNET_TIME_Absolute first;
1463 struct GNUNET_HELLO_Message *hello;
1464 struct GNUNET_PeerIdentity pid;
1465 struct NeighbourList *n;
1468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1469 "HELLO validation cleanup background task running...\n");
1471 now = GNUNET_TIME_absolute_get ();
1473 pos = pending_validations;
1476 if (pos->timeout.value < now.value)
1479 pending_validations = pos->next;
1481 prev->next = pos->next;
1482 va = pos->addresses;
1483 hello = GNUNET_HELLO_create (&pos->publicKey,
1484 &list_validated_addresses, &va);
1485 GNUNET_CRYPTO_hash (&pos->publicKey,
1487 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1491 "Creating persistent `%s' message for peer `%4s' based on confirmed addresses.\n",
1492 "HELLO", GNUNET_i2s (&pid));
1494 GNUNET_PEERINFO_add_peer (cfg, sched, &pid, hello);
1495 n = find_neighbour (&pid);
1497 try_transmission_to_peer (n);
1498 GNUNET_free (hello);
1499 while (NULL != (va = pos->addresses))
1501 pos->addresses = va->next;
1502 GNUNET_free (va->transport_name);
1507 pos = pending_validations;
1516 /* finally, reschedule cleanup if needed; list is
1517 ordered by timeout, so we need the last element... */
1518 if (NULL != pending_validations)
1520 first = pending_validations->timeout;
1521 pos = pending_validations;
1524 first = GNUNET_TIME_absolute_min (first, pos->timeout);
1527 GNUNET_SCHEDULER_add_delayed (sched,
1528 GNUNET_TIME_absolute_get_remaining (first),
1529 &cleanup_validation, NULL);
1537 * Function that will be called if we receive a validation
1538 * of an address challenge that we transmitted to another
1539 * peer. Note that the validation should only be considered
1540 * acceptable if the challenge matches AND if the sender
1541 * address is at least a plausible address for this peer
1542 * (otherwise we may be seeing a MiM attack).
1544 * @param cls closure
1545 * @param name name of the transport that generated the address
1546 * @param peer who responded to our challenge
1547 * @param challenge the challenge number we presumably used
1548 * @param sender_addr string describing our sender address (as observed
1549 * by the other peer in human-readable format)
1552 plugin_env_notify_validation (void *cls,
1554 const struct GNUNET_PeerIdentity *peer,
1556 const char *sender_addr)
1558 unsigned int not_done;
1560 struct ValidationList *pos;
1561 struct ValidationAddress *va;
1562 struct GNUNET_PeerIdentity id;
1564 pos = pending_validations;
1567 GNUNET_CRYPTO_hash (&pos->publicKey,
1569 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1572 memcmp (peer, &id, sizeof (struct GNUNET_PeerIdentity)))
1578 /* TODO: call statistics (unmatched PONG) */
1579 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1581 ("Received validation response but have no record of any validation request for `%4s'. Ignoring.\n"),
1586 matched = GNUNET_NO;
1587 va = pos->addresses;
1590 if (va->challenge == challenge)
1593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1594 "Confirmed validity of address, peer `%4s' has address `%s'.\n",
1596 GNUNET_a2s ((const struct sockaddr*) &va[1],
1599 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1600 _("Another peer saw us using the address `%s' via `%s'. If this is not plausible, this address should be listed in the configuration as implausible to avoid MiM attacks.\n"),
1603 va->ok = GNUNET_YES;
1605 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1606 matched = GNUNET_YES;
1608 if (va->ok != GNUNET_YES)
1612 if (GNUNET_NO == matched)
1614 /* TODO: call statistics (unmatched PONG) */
1615 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1617 ("Received `%s' message but have no record of a matching `%s' message. Ignoring.\n"),
1623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1624 "All addresses validated, will now construct `%s' for `%4s'.\n",
1628 pos->timeout.value = 0;
1629 GNUNET_SCHEDULER_add_with_priority (sched,
1630 GNUNET_SCHEDULER_PRIORITY_IDLE,
1631 &cleanup_validation, NULL);
1636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1637 "Still waiting for %u additional `%s' messages before constructing `%s' for `%4s'.\n",
1647 struct CheckHelloValidatedContext
1650 * Plugin for which we are validating.
1652 struct TransportPlugin *plugin;
1655 * Hello that we are validating.
1657 struct GNUNET_HELLO_Message *hello;
1660 * Validation list being build.
1662 struct ValidationList *e;
1668 * Append the given address to the list of entries
1669 * that need to be validated.
1672 run_validation (void *cls,
1674 struct GNUNET_TIME_Absolute expiration,
1675 const void *addr, size_t addrlen)
1677 struct ValidationList *e = cls;
1678 struct TransportPlugin *tp;
1679 struct ValidationAddress *va;
1680 struct GNUNET_PeerIdentity id;
1682 tp = find_transport (tname);
1685 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1686 GNUNET_ERROR_TYPE_BULK,
1688 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
1692 GNUNET_CRYPTO_hash (&e->publicKey,
1694 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1697 "Scheduling validation of address `%s' via `%s' for `%4s'\n",
1698 GNUNET_a2s(addr, addrlen),
1702 va = GNUNET_malloc (sizeof (struct ValidationAddress) + addrlen);
1703 va->next = e->addresses;
1705 va->transport_name = GNUNET_strdup (tname);
1706 va->addr_len = addrlen;
1707 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1709 memcpy (&va[1], addr, addrlen);
1715 * Check if addresses in validated hello "h" overlap with
1716 * those in "chvc->hello" and update "chvc->hello" accordingly,
1717 * removing those addresses that have already been validated.
1720 check_hello_validated (void *cls,
1721 const struct GNUNET_PeerIdentity *peer,
1722 const struct GNUNET_HELLO_Message *h,
1725 struct CheckHelloValidatedContext *chvc = cls;
1726 struct ValidationAddress *va;
1727 struct TransportPlugin *tp;
1729 struct GNUNET_PeerIdentity apeer;
1731 first_call = GNUNET_NO;
1732 if (chvc->e == NULL)
1734 first_call = GNUNET_YES;
1735 chvc->e = GNUNET_malloc (sizeof (struct ValidationList));
1736 GNUNET_assert (GNUNET_OK ==
1737 GNUNET_HELLO_get_key (h != NULL ? h : chvc->hello,
1738 &chvc->e->publicKey));
1740 GNUNET_TIME_relative_to_absolute (HELLO_VERIFICATION_TIMEOUT);
1741 chvc->e->next = pending_validations;
1742 pending_validations = chvc->e;
1746 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
1748 GNUNET_TIME_absolute_get (),
1749 &run_validation, chvc->e);
1751 else if (GNUNET_YES == first_call)
1753 /* no existing HELLO, all addresses are new */
1754 GNUNET_HELLO_iterate_addresses (chvc->hello,
1755 GNUNET_NO, &run_validation, chvc->e);
1758 return; /* wait for next call */
1759 /* finally, transmit validation attempts */
1760 GNUNET_assert (GNUNET_OK ==
1761 GNUNET_HELLO_get_id (chvc->hello,
1764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1765 "Ready to validate addresses from `%s' message for peer `%4s'\n",
1766 "HELLO", GNUNET_i2s (&apeer));
1768 va = chvc->e->addresses;
1772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773 "Establishing `%s' connection to validate `%s' address `%s' of `%4s'\n",
1776 GNUNET_a2s ((const struct sockaddr*) &va[1],
1778 GNUNET_i2s (&apeer));
1780 tp = find_transport (va->transport_name);
1781 GNUNET_assert (tp != NULL);
1783 tp->api->validate (tp->api->cls,
1786 HELLO_VERIFICATION_TIMEOUT,
1789 va->ok = GNUNET_SYSERR;
1792 GNUNET_SCHEDULER_add_delayed (sched,
1793 GNUNET_TIME_absolute_get_remaining (chvc->e->timeout),
1794 &cleanup_validation, NULL);
1800 * Process HELLO-message.
1802 * @param plugin transport involved, may be NULL
1803 * @param message the actual message
1804 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
1807 process_hello (struct TransportPlugin *plugin,
1808 const struct GNUNET_MessageHeader *message)
1810 struct ValidationList *e;
1812 struct GNUNET_PeerIdentity target;
1813 const struct GNUNET_HELLO_Message *hello;
1814 struct CheckHelloValidatedContext *chvc;
1815 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
1817 hsize = ntohs (message->size);
1818 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1819 (hsize < sizeof (struct GNUNET_MessageHeader)))
1822 return GNUNET_SYSERR;
1824 /* first, check if load is too high */
1825 if (GNUNET_OS_load_cpu_get (cfg) > 100)
1827 /* TODO: call to stats? */
1830 hello = (const struct GNUNET_HELLO_Message *) message;
1831 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
1833 GNUNET_break_op (0);
1834 return GNUNET_SYSERR;
1836 GNUNET_CRYPTO_hash (&publicKey,
1837 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1838 &target.hashPubKey);
1840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1841 "Processing `%s' message for `%4s'\n",
1842 "HELLO", GNUNET_i2s (&target));
1844 /* check if a HELLO for this peer is already on the validation list */
1845 e = pending_validations;
1848 if (0 == memcmp (&e->publicKey,
1851 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
1853 /* TODO: call to stats? */
1855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1856 "`%s' message for peer `%4s' is already pending; ignoring new message\n",
1857 "HELLO", GNUNET_i2s (&target));
1863 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
1864 chvc->plugin = plugin;
1865 chvc->hello = (struct GNUNET_HELLO_Message *) &chvc[1];
1866 memcpy (chvc->hello, hello, hsize);
1867 /* finally, check if HELLO was previously validated
1868 (continuation will then schedule actual validation) */
1869 GNUNET_PEERINFO_for_all (cfg,
1873 HELLO_VERIFICATION_TIMEOUT,
1874 &check_hello_validated, chvc);
1880 * The peer specified by the given neighbour has timed-out or a plugin
1881 * has disconnected. We may either need to do nothing (other plugins
1882 * still up), or trigger a full disconnect and clean up. This
1883 * function updates our state and do the necessary notifications.
1884 * Also notifies our clients that the neighbour is now officially
1887 * @param n the neighbour list entry for the peer
1888 * @param check should we just check if all plugins
1889 * disconnected or must we ask all plugins to
1893 disconnect_neighbour (struct NeighbourList *n,
1896 struct ReadyList *rpos;
1897 struct NeighbourList *npos;
1898 struct NeighbourList *nprev;
1899 struct MessageQueue *mq;
1901 if (GNUNET_YES == check)
1904 while (NULL != rpos)
1906 if (GNUNET_YES == rpos->connected)
1907 return; /* still connected */
1913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1914 "Disconnecting from `%4s'\n",
1915 GNUNET_i2s(&n->id));
1917 /* remove n from neighbours list */
1920 while ((npos != NULL) && (npos != n))
1925 GNUNET_assert (npos != NULL);
1927 neighbours = n->next;
1929 nprev->next = n->next;
1931 /* notify all clients about disconnect */
1932 notify_clients_disconnect (&n->id);
1934 /* clean up all plugins, cancel connections and pending transmissions */
1935 while (NULL != (rpos = n->plugins))
1937 n->plugins = rpos->next;
1938 GNUNET_assert (rpos->neighbour == n);
1939 if (GNUNET_YES == rpos->connected)
1940 rpos->plugin->api->cancel (rpos->plugin->api->cls,
1941 rpos->plugin_handle,
1947 /* free all messages on the queue */
1948 while (NULL != (mq = n->messages))
1950 n->messages = mq->next;
1951 GNUNET_assert (mq->neighbour == n);
1954 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1955 GNUNET_SCHEDULER_cancel (sched,
1957 /* finally, free n itself */
1963 * Add an entry for each of our transport plugins
1964 * (that are able to send) to the list of plugins
1965 * for this neighbour.
1967 * @param neighbour to initialize
1970 add_plugins (struct NeighbourList *neighbour)
1972 struct TransportPlugin *tp;
1973 struct ReadyList *rl;
1975 neighbour->retry_plugins_time
1976 = GNUNET_TIME_relative_to_absolute (PLUGIN_RETRY_FREQUENCY);
1980 if (tp->api->send != NULL)
1982 rl = GNUNET_malloc (sizeof (struct ReadyList));
1983 rl->next = neighbour->plugins;
1984 neighbour->plugins = rl;
1986 rl->neighbour = neighbour;
1987 rl->transmit_ready = GNUNET_YES;
1995 neighbour_timeout_task (void *cls,
1996 const struct GNUNET_SCHEDULER_TaskContext *tc)
1998 struct NeighbourList *n = cls;
2001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2002 "Neighbour `%4s' has timed out!\n",
2003 GNUNET_i2s(&n->id));
2005 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2006 disconnect_neighbour (n, GNUNET_NO);
2011 * Create a fresh entry in our neighbour list for the given peer.
2012 * Will try to transmit our current HELLO to the new neighbour. Also
2013 * notifies our clients about the new "connection".
2015 * @param peer the peer for which we create the entry
2016 * @return the new neighbour list entry
2018 static struct NeighbourList *
2019 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2021 struct NeighbourList *n;
2024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2025 "Setting up new neighbour `%4s', sending our HELLO to introduce ourselves\n",
2028 GNUNET_assert (our_hello != NULL);
2029 n = GNUNET_malloc (sizeof (struct NeighbourList));
2030 n->next = neighbours;
2033 n->last_quota_update = GNUNET_TIME_absolute_get ();
2035 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2036 n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2038 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2039 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2040 &neighbour_timeout_task, n);
2041 transmit_to_peer (NULL, 0,
2042 (const struct GNUNET_MessageHeader *) our_hello,
2044 notify_clients_connect (peer, GNUNET_TIME_UNIT_FOREVER_REL);
2050 * Function called by the plugin for each received message.
2051 * Update data volumes, possibly notify plugins about
2052 * reducing the rate at which they read from the socket
2053 * and generally forward to our receive callback.
2055 * @param cls the "struct TransportPlugin *" we gave to the plugin
2056 * @param plugin_context value to pass to this plugin
2057 * to respond to the given peer (use is optional,
2058 * but may speed up processing)
2059 * @param service_context value passed to the transport-service
2060 * to identify the neighbour; will be NULL on the first
2061 * call for a given peer
2062 * @param latency estimated latency for communicating with the
2064 * @param peer (claimed) identity of the other peer
2065 * @param message the message, NULL if peer was disconnected
2066 * @return the new service_context that the plugin should use
2067 * for future receive calls for messages from this
2070 static struct ReadyList *
2071 plugin_env_receive (void *cls,
2072 void *plugin_context,
2073 struct ReadyList *service_context,
2074 struct GNUNET_TIME_Relative latency,
2075 const struct GNUNET_PeerIdentity *peer,
2076 const struct GNUNET_MessageHeader *message)
2078 const struct GNUNET_MessageHeader ack = {
2079 htons (sizeof (struct GNUNET_MessageHeader)),
2080 htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ACK)
2082 struct TransportPlugin *plugin = cls;
2083 struct TransportClient *cpos;
2084 struct InboundMessage *im;
2086 struct NeighbourList *n;
2088 if (service_context != NULL)
2090 n = service_context->neighbour;
2091 GNUNET_assert (n != NULL);
2095 n = find_neighbour (peer);
2098 if (message == NULL)
2099 return NULL; /* disconnect of peer already marked down */
2100 n = setup_new_neighbour (peer);
2102 service_context = n->plugins;
2103 while ((service_context != NULL) && (plugin != service_context->plugin))
2104 service_context = service_context->next;
2105 GNUNET_assert ((plugin->api->send == NULL) ||
2106 (service_context != NULL));
2108 if (message == NULL)
2111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2112 "Receive failed from `%4s', triggering disconnect\n",
2113 GNUNET_i2s(&n->id));
2115 /* TODO: call stats */
2116 if ((service_context != NULL) &&
2117 (service_context->plugin_handle == plugin_context))
2119 service_context->connected = GNUNET_NO;
2120 service_context->plugin_handle = NULL;
2122 disconnect_neighbour (n, GNUNET_YES);
2126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2127 "Processing message of type `%u' received by plugin...\n",
2128 ntohs (message->type));
2130 if (service_context != NULL)
2132 if (service_context->connected == GNUNET_NO)
2134 service_context->connected = GNUNET_YES;
2135 service_context->transmit_ready = GNUNET_YES;
2136 service_context->connect_attempts++;
2138 service_context->timeout
2139 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2140 service_context->plugin_handle = plugin_context;
2141 service_context->latency = latency;
2143 /* update traffic received amount ... */
2144 msize = ntohs (message->size);
2145 n->last_received += msize;
2146 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2148 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2150 GNUNET_SCHEDULER_add_delayed (sched,
2151 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2152 &neighbour_timeout_task, n);
2154 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2156 /* dropping message due to frequent inbound volume violations! */
2157 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2158 GNUNET_ERROR_TYPE_BULK,
2160 ("Dropping incoming message due to repeated bandwidth quota violations.\n"));
2161 /* TODO: call stats */
2162 GNUNET_assert ( (service_context == NULL) ||
2163 (NULL != service_context->neighbour) );
2164 return service_context;
2166 switch (ntohs (message->type))
2168 case GNUNET_MESSAGE_TYPE_HELLO:
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "Receiving `%s' message from `%4s'.\n", "HELLO",
2174 process_hello (plugin, message);
2176 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177 "Sending `%s' message to connecting peer `%4s'.\n", "ACK",
2180 transmit_to_peer (NULL, 0, &ack, GNUNET_YES, n);
2182 case GNUNET_MESSAGE_TYPE_TRANSPORT_ACK:
2183 n->saw_ack = GNUNET_YES;
2184 /* intentional fall-through! */
2187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188 "Received message of type %u from `%4s', sending to all clients.\n",
2189 ntohs (message->type),
2192 /* transmit message to all clients */
2193 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2194 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2195 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2196 im->latency = GNUNET_TIME_relative_hton (latency);
2198 memcpy (&im[1], message, msize);
2201 while (cpos != NULL)
2203 transmit_to_client (cpos, &im->header, GNUNET_YES);
2208 GNUNET_assert ( (service_context == NULL) ||
2209 (NULL != service_context->neighbour) );
2210 return service_context;
2215 * Handle START-message. This is the first message sent to us
2216 * by any client which causes us to add it to our list.
2218 * @param cls closure (always NULL)
2219 * @param client identification of the client
2220 * @param message the actual message
2223 handle_start (void *cls,
2224 struct GNUNET_SERVER_Client *client,
2225 const struct GNUNET_MessageHeader *message)
2227 struct TransportClient *c;
2228 struct ConnectInfoMessage cim;
2229 struct NeighbourList *n;
2230 struct InboundMessage *im;
2231 struct GNUNET_MessageHeader *ack;
2234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2235 "Received `%s' request from client\n", "START");
2240 if (c->client == client)
2242 /* client already on our list! */
2244 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2249 c = GNUNET_malloc (sizeof (struct TransportClient));
2253 if (our_hello != NULL)
2256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2257 "Sending our own `%s' to new client\n",
2260 transmit_to_client (c,
2261 (const struct GNUNET_MessageHeader *) our_hello,
2263 /* tell new client about all existing connections */
2264 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2265 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2266 cim.quota_out = htonl (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT / (60 * 1000));
2267 cim.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_ZERO); /* FIXME? */
2268 im = GNUNET_malloc (sizeof (struct InboundMessage) +
2269 sizeof (struct GNUNET_MessageHeader));
2270 im->header.size = htons (sizeof (struct InboundMessage) +
2271 sizeof (struct GNUNET_MessageHeader));
2272 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2273 im->latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_ZERO); /* FIXME? */
2274 ack = (struct GNUNET_MessageHeader *) &im[1];
2275 ack->size = htons (sizeof (struct GNUNET_MessageHeader));
2276 ack->type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ACK);
2277 for (n = neighbours; n != NULL; n = n->next)
2280 transmit_to_client (c, &cim.header, GNUNET_NO);
2284 transmit_to_client (c, &im->header, GNUNET_NO);
2289 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2294 * Handle HELLO-message.
2296 * @param cls closure (always NULL)
2297 * @param client identification of the client
2298 * @param message the actual message
2301 handle_hello (void *cls,
2302 struct GNUNET_SERVER_Client *client,
2303 const struct GNUNET_MessageHeader *message)
2308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309 "Received `%s' request from client\n", "HELLO");
2311 ret = process_hello (NULL, message);
2312 GNUNET_SERVER_receive_done (client, ret);
2317 * Handle SEND-message.
2319 * @param cls closure (always NULL)
2320 * @param client identification of the client
2321 * @param message the actual message
2324 handle_send (void *cls,
2325 struct GNUNET_SERVER_Client *client,
2326 const struct GNUNET_MessageHeader *message)
2328 struct TransportClient *tc;
2329 struct NeighbourList *n;
2330 const struct OutboundMessage *obm;
2331 const struct GNUNET_MessageHeader *obmm;
2335 size = ntohs (message->size);
2337 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2340 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2343 obm = (const struct OutboundMessage *) message;
2345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2346 "Received `%s' request from client with target `%4s'\n",
2347 "SEND", GNUNET_i2s (&obm->peer));
2349 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2350 msize = ntohs (obmm->size);
2351 if (size != msize + sizeof (struct OutboundMessage))
2354 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2357 n = find_neighbour (&obm->peer);
2359 n = setup_new_neighbour (&obm->peer);
2361 while ((tc != NULL) && (tc->client != client))
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2368 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2370 transmit_to_peer (tc, ntohl(obm->priority), obmm, GNUNET_NO, n);
2371 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2376 * Handle SET_QUOTA-message.
2378 * @param cls closure (always NULL)
2379 * @param client identification of the client
2380 * @param message the actual message
2383 handle_set_quota (void *cls,
2384 struct GNUNET_SERVER_Client *client,
2385 const struct GNUNET_MessageHeader *message)
2387 const struct QuotaSetMessage *qsm =
2388 (const struct QuotaSetMessage *) message;
2389 struct NeighbourList *n;
2390 struct TransportPlugin *p;
2391 struct ReadyList *rl;
2394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2395 "Received `%s' request from client for peer `%4s'\n",
2396 "SET_QUOTA", GNUNET_i2s (&qsm->peer));
2398 n = find_neighbour (&qsm->peer);
2401 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2405 if (n->quota_in < ntohl (qsm->quota_in))
2406 n->last_quota_update = GNUNET_TIME_absolute_get ();
2407 n->quota_in = ntohl (qsm->quota_in);
2412 p->api->set_receive_quota (p->api->cls,
2413 &qsm->peer, ntohl (qsm->quota_in));
2416 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2421 * Handle TRY_CONNECT-message.
2423 * @param cls closure (always NULL)
2424 * @param client identification of the client
2425 * @param message the actual message
2428 handle_try_connect (void *cls,
2429 struct GNUNET_SERVER_Client *client,
2430 const struct GNUNET_MessageHeader *message)
2432 const struct TryConnectMessage *tcm;
2434 tcm = (const struct TryConnectMessage *) message;
2436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437 "Received `%s' request from client %p asking to connect to `%4s'\n",
2440 GNUNET_i2s (&tcm->peer));
2442 if (NULL == find_neighbour (&tcm->peer))
2443 setup_new_neighbour (&tcm->peer);
2446 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2447 "Client asked to connect to `%4s', but connection already exists\n",
2449 GNUNET_i2s (&tcm->peer));
2451 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2456 * List of handlers for the messages understood by this
2459 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2460 {&handle_start, NULL,
2461 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2462 {&handle_hello, NULL,
2463 GNUNET_MESSAGE_TYPE_HELLO, 0},
2464 {&handle_send, NULL,
2465 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2466 {&handle_set_quota, NULL,
2467 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2468 {&handle_try_connect, NULL,
2469 GNUNET_MESSAGE_TYPE_TRANSPORT_TRY_CONNECT,
2470 sizeof (struct TryConnectMessage)},
2476 * Setup the environment for this plugin.
2479 create_environment (struct TransportPlugin *plug)
2481 plug->env.cfg = cfg;
2482 plug->env.sched = sched;
2483 plug->env.my_public_key = &my_public_key;
2484 plug->env.my_private_key = my_private_key;
2485 plug->env.my_identity = &my_identity;
2486 plug->env.cls = plug;
2487 plug->env.receive = &plugin_env_receive;
2488 plug->env.lookup = &plugin_env_lookup_address;
2489 plug->env.notify_address = &plugin_env_notify_address;
2490 plug->env.notify_validation = &plugin_env_notify_validation;
2491 plug->env.default_quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2492 plug->env.max_connections = max_connect_per_transport;
2497 * Start the specified transport (load the plugin).
2500 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2502 struct TransportPlugin *plug;
2505 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2506 _("Loading `%s' transport plugin\n"), name);
2507 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2508 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2509 create_environment (plug);
2510 plug->short_name = GNUNET_strdup (name);
2511 plug->lib_name = libname;
2512 plug->next = plugins;
2514 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
2515 if (plug->api == NULL)
2517 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2518 _("Failed to load transport plugin for `%s'\n"), name);
2519 GNUNET_free (plug->short_name);
2520 plugins = plug->next;
2521 GNUNET_free (libname);
2528 * Called whenever a client is disconnected. Frees our
2529 * resources associated with that client.
2531 * @param cls closure
2532 * @param client identification of the client
2535 client_disconnect_notification (void *cls,
2536 struct GNUNET_SERVER_Client *client)
2538 struct TransportClient *pos;
2539 struct TransportClient *prev;
2540 struct ClientMessageQueueEntry *mqe;
2543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2544 "Client disconnected, cleaning up.\n");
2548 while ((pos != NULL) && (pos->client != client))
2555 while (NULL != (mqe = pos->message_queue_head))
2557 pos->message_queue_head = mqe->next;
2560 pos->message_queue_head = NULL;
2562 clients = pos->next;
2564 prev->next = pos->next;
2565 if (GNUNET_YES == pos->tcs_pending)
2575 * Function called when the service shuts down. Unloads our plugins.
2577 * @param cls closure, unused
2578 * @param tc task context (unused)
2581 unload_plugins (void *cls,
2582 const struct GNUNET_SCHEDULER_TaskContext *tc)
2584 struct TransportPlugin *plug;
2585 struct AddressList *al;
2588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2589 "Transport service is unloading plugins...\n");
2591 while (NULL != (plug = plugins))
2593 plugins = plug->next;
2594 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
2595 GNUNET_free (plug->lib_name);
2596 GNUNET_free (plug->short_name);
2597 while (NULL != (al = plug->addresses))
2599 plug->addresses = al->next;
2604 if (my_private_key != NULL)
2605 GNUNET_CRYPTO_rsa_key_free (my_private_key);
2606 GNUNET_free_non_null (our_hello);
2611 * Initiate transport service.
2613 * @param cls closure
2614 * @param s scheduler to use
2615 * @param serv the initialized server
2616 * @param c configuration to use
2620 struct GNUNET_SCHEDULER_Handle *s,
2621 struct GNUNET_SERVER_Handle *serv,
2622 const struct GNUNET_CONFIGURATION_Handle *c)
2627 unsigned long long tneigh;
2632 /* parse configuration */
2634 GNUNET_CONFIGURATION_get_value_number (c,
2639 GNUNET_CONFIGURATION_get_value_filename (c,
2641 "HOSTKEY", &keyfile)))
2643 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2645 ("Transport service is lacking key configuration settings. Exiting.\n"));
2646 GNUNET_SCHEDULER_shutdown (s);
2649 max_connect_per_transport = (uint32_t) tneigh;
2650 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2651 GNUNET_free (keyfile);
2652 if (my_private_key == NULL)
2654 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2656 ("Transport service could not access hostkey. Exiting.\n"));
2657 GNUNET_SCHEDULER_shutdown (s);
2660 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
2661 GNUNET_CRYPTO_hash (&my_public_key,
2662 sizeof (my_public_key), &my_identity.hashPubKey);
2663 /* setup notification */
2665 GNUNET_SERVER_disconnect_notify (server,
2666 &client_disconnect_notification, NULL);
2667 /* load plugins... */
2670 GNUNET_CONFIGURATION_get_value_string (c,
2671 "TRANSPORT", "PLUGINS", &plugs))
2673 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2674 _("Starting transport plugins `%s'\n"), plugs);
2675 pos = strtok (plugs, " ");
2678 start_transport (server, pos);
2680 pos = strtok (NULL, " ");
2682 GNUNET_free (plugs);
2684 GNUNET_SCHEDULER_add_delayed (sched,
2685 GNUNET_TIME_UNIT_FOREVER_REL,
2686 &unload_plugins, NULL);
2690 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2691 _("Transport service ready.\n"));
2693 /* process client requests */
2694 GNUNET_SERVER_add_handlers (server, handlers);
2699 * The main function for the transport service.
2701 * @param argc number of arguments from the command line
2702 * @param argv command line arguments
2703 * @return 0 ok, 1 on error
2706 main (int argc, char *const *argv)
2708 return (GNUNET_OK ==
2709 GNUNET_SERVICE_run (argc,
2712 GNUNET_SERVICE_OPTION_NONE,
2713 &run, NULL)) ? 0 : 1;
2716 /* end of gnunet-service-transport.c */