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 * - This code uses 'GNUNET_a2s' for debug printing in many places,
28 * which is technically wrong since it assumes we have IP+Port
29 * (v4/v6) addresses. Once we add transports like http or smtp
30 * this will have to be changed!
33 #include "gnunet_client_lib.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_os_lib.h"
39 #include "gnunet_peerinfo_service.h"
40 #include "gnunet_plugin_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_signatures.h"
44 #include "plugin_transport.h"
45 #include "transport.h"
48 * Should we do some additional checks (to validate behavior
51 #define EXTRA_CHECKS GNUNET_YES
54 * How many messages can we have pending for a given client process
55 * before we start to drop incoming messages? We typically should
56 * have only one client and so this would be the primary buffer for
57 * messages, so the number should be chosen rather generously.
59 * The expectation here is that most of the time the queue is large
60 * enough so that a drop is virtually never required.
62 #define MAX_PENDING 128
65 * How often should we try to reconnect to a peer using a particular
66 * transport plugin before giving up? Note that the plugin may be
67 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
69 #define MAX_CONNECT_RETRY 3
72 * Limit on the number of ready-to-run tasks when validating
73 * HELLOs. If more tasks are ready to run, we will drop
74 * HELLOs instead of validating them.
76 #define MAX_HELLO_LOAD 4
79 * How often must a peer violate bandwidth quotas before we start
80 * to simply drop its messages?
82 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
85 * How long until a HELLO verification attempt should time out?
86 * Must be rather small, otherwise a partially successful HELLO
87 * validation (some addresses working) might not be available
88 * before a client's request for a connection fails for good.
89 * Besides, if a single request to an address takes a long time,
90 * then the peer is unlikely worthwhile anyway.
92 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
95 * How long will we allow sending of a ping to be delayed?
97 #define TRANSPORT_DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
100 * How often will we re-validate for latency information
102 #define TRANSPORT_DEFAULT_REVALIDATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
105 * Priority to use for PONG messages.
107 #define TRANSPORT_PONG_PRIORITY 4
110 * How often do we re-add (cheaper) plugins to our list of plugins
111 * to try for a given connected peer?
113 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
116 * After how long do we expire an address in a HELLO that we just
117 * validated? This value is also used for our own addresses when we
120 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
124 * How long before an existing address expires should we again try to
125 * validate it? Must be (significantly) smaller than
126 * HELLO_ADDRESS_EXPIRATION.
128 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
132 * List of addresses of other peers
134 struct ForeignAddressList
137 * This is a linked list.
139 struct ForeignAddressList *next;
142 * Which ready list does this entry belong to.
144 struct ReadyList *ready_list;
147 * How long until we auto-expire this address (unless it is
148 * re-confirmed by the transport)?
150 struct GNUNET_TIME_Absolute expires;
153 * Task used to re-validate addresses, updates latencies and
156 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
169 * What was the last latency observed for this plugin
170 * and peer? Invalid if connected is GNUNET_NO.
172 struct GNUNET_TIME_Relative latency;
175 * If we did not successfully transmit a message to the given peer
176 * via this connection during the specified time, we should consider
177 * the connection to be dead. This is used in the case that a TCP
178 * transport simply stalls writing to the stream but does not
179 * formerly get a signal that the other peer died.
181 struct GNUNET_TIME_Absolute timeout;
184 * Are we currently connected via this address? The first time we
185 * successfully transmit or receive data to a peer via a particular
186 * address, we set this to GNUNET_YES. If we later get an error
187 * (disconnect notification, transmission failure, timeout), we set
188 * it back to GNUNET_NO.
193 * Is this plugin currently busy transmitting to the specific target?
194 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
195 * messages do not count as 'in transmit'.
200 * Has this address been validated yet?
205 * How often have we tried to connect using this plugin? Used to
206 * discriminate against addresses that do not work well.
207 * FIXME: not yet used, but should be!
209 unsigned int connect_attempts;
212 * DV distance to this peer (1 if no DV is used).
213 * FIXME: need to set this from transport plugins!
221 * Entry in linked list of network addresses for ourselves.
223 struct OwnAddressList
226 * This is a linked list.
228 struct OwnAddressList *next;
231 * The address, actually a pointer to the end
232 * of this struct. Do not free!
237 * How long until we auto-expire this address (unless it is
238 * re-confirmed by the transport)?
240 struct GNUNET_TIME_Absolute expires;
251 * Entry in linked list of all of our plugins.
253 struct TransportPlugin
257 * This is a linked list.
259 struct TransportPlugin *next;
262 * API of the transport as returned by the plugin's
263 * initialization function.
265 struct GNUNET_TRANSPORT_PluginFunctions *api;
268 * Short name for the plugin (i.e. "tcp").
273 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
278 * List of our known addresses for this transport.
280 struct OwnAddressList *addresses;
283 * Environment this transport service is using
286 struct GNUNET_TRANSPORT_PluginEnvironment env;
289 * ID of task that is used to clean up expired addresses.
291 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
294 * Set to GNUNET_YES if we need to scrap the existing
295 * list of "addresses" and start fresh when we receive
296 * the next address update from a transport. Set to
297 * GNUNET_NO if we should just add the new address
298 * to the list and wait for the commit call.
304 struct NeighbourList;
307 * For each neighbour we keep a list of messages
308 * that we still want to transmit to the neighbour.
314 * This is a doubly linked list.
316 struct MessageQueue *next;
319 * This is a doubly linked list.
321 struct MessageQueue *prev;
324 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
325 * stuck together in memory. Allocated at the end of this struct.
327 const char *message_buf;
330 * Size of the message buf
332 size_t message_buf_size;
335 * Client responsible for queueing the message;
336 * used to check that a client has no two messages
337 * pending for the same target. Can be NULL.
339 struct TransportClient *client;
342 * Using which specific address should we send this message?
344 struct ForeignAddressList *specific_address;
347 * Peer ID of the Neighbour this entry belongs to.
349 struct GNUNET_PeerIdentity neighbour_id;
352 * Plugin that we used for the transmission.
353 * NULL until we scheduled a transmission.
355 struct TransportPlugin *plugin;
358 * At what time should we fail?
360 struct GNUNET_TIME_Absolute timeout;
363 * Internal message of the transport system that should not be
364 * included in the usual SEND-SEND_OK transmission confirmation
365 * traffic management scheme. Typically, "internal_msg" will
366 * be set whenever "client" is NULL (but it is not strictly
372 * How important is the message?
374 unsigned int priority;
380 * For a given Neighbour, which plugins are available
381 * to talk to this peer and what are their costs?
386 * This is a linked list.
388 struct ReadyList *next;
391 * Which of our transport plugins does this entry
394 struct TransportPlugin *plugin;
397 * Transport addresses, latency, and readiness for
398 * this particular plugin.
400 struct ForeignAddressList *addresses;
406 * Entry in linked list of all of our current neighbours.
412 * This is a linked list.
414 struct NeighbourList *next;
417 * Which of our transports is connected to this peer
418 * and what is their status?
420 struct ReadyList *plugins;
423 * Head of list of messages we would like to send to this peer;
424 * must contain at most one message per client.
426 struct MessageQueue *messages_head;
429 * Tail of list of messages we would like to send to this peer; must
430 * contain at most one message per client.
432 struct MessageQueue *messages_tail;
435 * Identity of this neighbour.
437 struct GNUNET_PeerIdentity id;
440 * ID of task scheduled to run when this peer is about to
441 * time out (will free resources associated with the peer).
443 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
446 * ID of task scheduled to run when we should retry transmitting
447 * the head of the message queue.
449 GNUNET_SCHEDULER_TaskIdentifier retry_task;
452 * How long until we should consider this peer dead
453 * (if we don't receive another message in the
456 struct GNUNET_TIME_Absolute peer_timeout;
459 * Tracker for inbound bandwidth.
461 struct GNUNET_BANDWIDTH_Tracker in_tracker;
464 * The latency we have seen for this particular address for
465 * this particular peer. This latency may have been calculated
466 * over multiple transports. This value reflects how long it took
467 * us to receive a response when SENDING via this particular
468 * transport/neighbour/address combination!
470 * FIXME: we need to periodically send PINGs to update this
471 * latency (at least more often than the current "huge" (11h?)
474 struct GNUNET_TIME_Relative latency;
477 * How often has the other peer (recently) violated the
478 * inbound traffic limit? Incremented by 10 per violation,
479 * decremented by 1 per non-violation (for each
482 unsigned int quota_violation_count;
485 * DV distance to this peer (1 if no DV is used).
490 * Have we seen an PONG from this neighbour in the past (and
491 * not had a disconnect since)?
498 * Message used to ask a peer to validate receipt (to check an address
501 struct TransportPingMessage
505 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
507 struct GNUNET_MessageHeader header;
510 * Random challenge number (in network byte order).
512 uint32_t challenge GNUNET_PACKED;
515 * Who is the intended recipient?
517 struct GNUNET_PeerIdentity target;
523 * Message used to validate a HELLO. The challenge is included in the
524 * confirmation to make matching of replies to requests possible. The
525 * signature signs the original challenge number, our public key, the
526 * sender's address (so that the sender can check that the address we
527 * saw is plausible for him and possibly detect a MiM attack) and a
528 * timestamp (to limit replay).<p>
530 * This message is followed by the address of the
531 * client that we are observing (which is part of what
534 struct TransportPongMessage
538 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
540 struct GNUNET_MessageHeader header;
543 * For padding, always zero.
545 uint32_t reserved GNUNET_PACKED;
550 struct GNUNET_CRYPTO_RsaSignature signature;
553 * What are we signing and why?
555 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
558 * Random challenge number (in network byte order).
560 uint32_t challenge GNUNET_PACKED;
563 * Who signed this message?
565 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
568 * Size of address appended to this message
576 * Linked list of messages to be transmitted to the client. Each
577 * entry is followed by the actual message.
579 struct ClientMessageQueueEntry
582 * This is a doubly-linked list.
584 struct ClientMessageQueueEntry *next;
587 * This is a doubly-linked list.
589 struct ClientMessageQueueEntry *prev;
594 * Client connected to the transport service.
596 struct TransportClient
600 * This is a linked list.
602 struct TransportClient *next;
605 * Handle to the client.
607 struct GNUNET_SERVER_Client *client;
610 * Linked list of messages yet to be transmitted to
613 struct ClientMessageQueueEntry *message_queue_head;
616 * Tail of linked list of messages yet to be transmitted to the
619 struct ClientMessageQueueEntry *message_queue_tail;
622 * Current transmit request handle.
624 struct GNUNET_CONNECTION_TransmitHandle *th;
627 * Is a call to "transmit_send_continuation" pending? If so, we
628 * must not free this struct (even if the corresponding client
629 * disconnects) and instead only remove it from the linked list and
630 * set the "client" field to NULL.
635 * Length of the list of messages pending for this client.
637 unsigned int message_count;
643 * Entry in map of all HELLOs awaiting validation.
645 struct ValidationEntry
649 * The address, actually a pointer to the end
650 * of this struct. Do not free!
655 * Name of the transport.
657 char *transport_name;
660 * The public key of the peer.
662 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
665 * ID of task that will clean up this entry if we don't succeed
666 * with the validation first.
668 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
671 * At what time did we send this validation?
673 struct GNUNET_TIME_Absolute send_time;
681 * Challenge number we used.
689 * Context of currently active requests to peerinfo
690 * for validation of HELLOs.
692 struct CheckHelloValidatedContext
696 * This is a doubly-linked list.
698 struct CheckHelloValidatedContext *next;
701 * This is a doubly-linked list.
703 struct CheckHelloValidatedContext *prev;
706 * Hello that we are validating.
708 const struct GNUNET_HELLO_Message *hello;
711 * Context for peerinfo iteration.
712 * NULL after we are done processing peerinfo's information.
714 struct GNUNET_PEERINFO_IteratorContext *piter;
717 * Was a HELLO known for this peer to peerinfo?
724 * Struct for keeping information about addresses to validate
725 * so that we can re-use for sending around ping's and receiving
726 * pongs periodically to keep connections alive and also better
727 * estimate latency of connections.
730 struct PeriodicValidationContext
734 * The address we are keeping alive
736 struct ForeignAddressList *foreign_address;
739 * The name of the transport
744 * Public Key of the peer to re-validate
746 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
753 static struct GNUNET_HELLO_Message *our_hello;
756 * "version" of "our_hello". Used to see if a given neighbour has
757 * already been sent the latest version of our HELLO message.
759 static unsigned int our_hello_version;
764 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
769 static struct GNUNET_PeerIdentity my_identity;
774 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
779 struct GNUNET_SCHEDULER_Handle *sched;
784 const struct GNUNET_CONFIGURATION_Handle *cfg;
787 * Linked list of all clients to this service.
789 static struct TransportClient *clients;
792 * All loaded plugins.
794 static struct TransportPlugin *plugins;
799 static struct GNUNET_SERVER_Handle *server;
802 * All known neighbours and their HELLOs.
804 static struct NeighbourList *neighbours;
807 * Number of neighbours we'd like to have.
809 static uint32_t max_connect_per_transport;
812 * Head of linked list.
814 static struct CheckHelloValidatedContext *chvc_head;
817 * Tail of linked list.
819 static struct CheckHelloValidatedContext *chvc_tail;
823 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
824 * of the given peer that we are currently validating).
826 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
830 * The peer specified by the given neighbour has timed-out or a plugin
831 * has disconnected. We may either need to do nothing (other plugins
832 * still up), or trigger a full disconnect and clean up. This
833 * function updates our state and do the necessary notifications.
834 * Also notifies our clients that the neighbour is now officially
837 * @param n the neighbour list entry for the peer
838 * @param check should we just check if all plugins
839 * disconnected or must we ask all plugins to
842 static void disconnect_neighbour (struct NeighbourList *n, int check);
845 * Check the ready list for the given neighbour and if a plugin is
846 * ready for transmission (and if we have a message), do so!
848 * @param neighbour target peer for which to transmit
850 static void try_transmission_to_peer (struct NeighbourList *neighbour);
854 * Find an entry in the neighbour list for a particular peer.
855 * if sender_address is not specified (NULL) then return the
856 * first matching entry. If sender_address is specified, then
857 * make sure that the address and address_len also matches.
859 * FIXME: This description does not fit the function.
861 * @return NULL if not found.
863 static struct NeighbourList *
864 find_neighbour (const struct GNUNET_PeerIdentity *key)
866 struct NeighbourList *head = neighbours;
868 while ((head != NULL) &&
869 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
876 * Find an entry in the transport list for a particular transport.
878 * @return NULL if not found.
880 static struct TransportPlugin *
881 find_transport (const char *short_name)
883 struct TransportPlugin *head = plugins;
884 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
891 * Function called to notify a client about the socket being ready to
892 * queue more data. "buf" will be NULL and "size" zero if the socket
893 * was closed for writing in the meantime.
896 * @param size number of bytes available in buf
897 * @param buf where the callee should write the message
898 * @return number of bytes written to buf
901 transmit_to_client_callback (void *cls, size_t size, void *buf)
903 struct TransportClient *client = cls;
904 struct ClientMessageQueueEntry *q;
907 const struct GNUNET_MessageHeader *msg;
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Transmission to client failed, closing connection.\n");
915 /* fatal error with client, free message queue! */
916 while (NULL != (q = client->message_queue_head))
918 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
919 client->message_queue_tail,
923 client->message_count = 0;
928 while (NULL != (q = client->message_queue_head))
930 msg = (const struct GNUNET_MessageHeader *) &q[1];
931 msize = ntohs (msg->size);
932 if (msize + tsize > size)
935 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
936 "Transmitting message of type %u to client.\n",
939 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
940 client->message_queue_tail,
942 memcpy (&cbuf[tsize], msg, msize);
945 client->message_count--;
949 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
950 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
952 GNUNET_TIME_UNIT_FOREVER_REL,
953 &transmit_to_client_callback,
955 GNUNET_assert (client->th != NULL);
962 * Send the specified message to the specified client. Since multiple
963 * messages may be pending for the same client at a time, this code
964 * makes sure that no message is lost.
966 * @param client client to transmit the message to
967 * @param msg the message to send
968 * @param may_drop can this message be dropped if the
969 * message queue for this client is getting far too large?
972 transmit_to_client (struct TransportClient *client,
973 const struct GNUNET_MessageHeader *msg, int may_drop)
975 struct ClientMessageQueueEntry *q;
978 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
980 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
982 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
983 client->message_count, MAX_PENDING);
984 /* TODO: call to statistics... */
987 msize = ntohs (msg->size);
988 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
989 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
990 memcpy (&q[1], msg, msize);
991 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
992 client->message_queue_tail,
993 client->message_queue_tail,
995 client->message_count++;
996 if (client->th == NULL)
998 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1000 GNUNET_TIME_UNIT_FOREVER_REL,
1001 &transmit_to_client_callback,
1003 GNUNET_assert (client->th != NULL);
1009 * Transmit a 'SEND_OK' notification to the given client for the
1012 * @param client who to notify
1013 * @param n neighbour to notify about
1014 * @param result status code for the transmission request
1017 transmit_send_ok (struct TransportClient *client,
1018 struct NeighbourList *n,
1021 struct SendOkMessage send_ok_msg;
1023 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1024 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1025 send_ok_msg.success = htonl (result);
1026 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1027 send_ok_msg.peer = n->id;
1028 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1033 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1034 * upon "completion" of a send request. This tells the API
1035 * that it is now legal to send another message to the given
1038 * @param cls closure, identifies the entry on the
1039 * message queue that was transmitted and the
1040 * client responsible for queueing the message
1041 * @param target the peer receiving the message
1042 * @param result GNUNET_OK on success, if the transmission
1043 * failed, we should not tell the client to transmit
1047 transmit_send_continuation (void *cls,
1048 const struct GNUNET_PeerIdentity *target,
1051 struct MessageQueue *mq = cls;
1052 struct NeighbourList *n;
1054 n = find_neighbour(&mq->neighbour_id);
1055 GNUNET_assert (n != NULL);
1056 if (mq->specific_address != NULL)
1058 if (result == GNUNET_OK)
1060 mq->specific_address->timeout =
1061 GNUNET_TIME_relative_to_absolute
1062 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1063 mq->specific_address->connected = GNUNET_YES;
1067 mq->specific_address->connected = GNUNET_NO;
1069 if (! mq->internal_msg)
1070 mq->specific_address->in_transmit = GNUNET_NO;
1072 if (mq->client != NULL)
1073 transmit_send_ok (mq->client, n, result);
1075 try_transmission_to_peer (n);
1076 /** Never disconnect a neighbor here...
1077 if (result != GNUNET_OK)
1078 disconnect_neighbour (n, GNUNET_YES);
1084 * Find an address in any of the available transports for
1085 * the given neighbour that would be good for message
1086 * transmission. This is essentially the transport selection
1089 * @param neighbour for whom to select an address
1090 * @return selected address, NULL if we have none
1092 struct ForeignAddressList *
1093 find_ready_address(struct NeighbourList *neighbour)
1095 struct ReadyList *head = neighbour->plugins;
1096 struct ForeignAddressList *addresses;
1097 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1098 struct ForeignAddressList *best_address;
1100 best_address = NULL;
1101 while (head != NULL)
1103 addresses = head->addresses;
1104 while (addresses != NULL)
1106 if ( (addresses->timeout.value < now.value) &&
1107 (addresses->connected == GNUNET_YES) )
1110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1111 "Marking long-time inactive connection to `%4s' as down.\n",
1112 GNUNET_i2s (&neighbour->id));
1114 addresses->connected = GNUNET_NO;
1116 addresses = addresses->next;
1119 addresses = head->addresses;
1120 while (addresses != NULL)
1122 if ( ( (best_address == NULL) ||
1123 (addresses->connected == GNUNET_YES) ||
1124 (best_address->connected == GNUNET_NO) ) &&
1125 (addresses->in_transmit == GNUNET_NO) &&
1126 ( (best_address == NULL) ||
1127 (addresses->latency.value < best_address->latency.value)) )
1128 best_address = addresses;
1129 /* FIXME: also give lower-latency addresses that are not
1130 connected a chance some times... */
1131 addresses = addresses->next;
1136 if (best_address != NULL)
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139 "Best address found has latency of %llu ms.\n",
1140 best_address->latency.value);
1143 return best_address;
1149 * We should re-try transmitting to the given peer,
1150 * hopefully we've learned something in the meantime.
1153 retry_transmission_task (void *cls,
1154 const struct GNUNET_SCHEDULER_TaskContext *tc)
1156 struct NeighbourList *n = cls;
1158 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1159 try_transmission_to_peer (n);
1164 * Check the ready list for the given neighbour and if a plugin is
1165 * ready for transmission (and if we have a message), do so!
1167 * @param neighbour target peer for which to transmit
1170 try_transmission_to_peer (struct NeighbourList *neighbour)
1172 struct ReadyList *rl;
1173 struct MessageQueue *mq;
1174 struct GNUNET_TIME_Relative timeout;
1176 if (neighbour->messages_head == NULL)
1177 return; /* nothing to do */
1179 mq = neighbour->messages_head;
1180 /* FIXME: support bi-directional use of TCP */
1181 if (mq->specific_address == NULL)
1182 mq->specific_address = find_ready_address(neighbour);
1183 if (mq->specific_address == NULL)
1185 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1186 if (timeout.value == 0)
1189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190 "No destination address available to transmit message of size %u to peer `%4s'\n",
1191 mq->message_buf_size,
1192 GNUNET_i2s (&mq->neighbour_id));
1194 if (mq->client != NULL)
1195 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1196 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1197 neighbour->messages_tail,
1200 return; /* nobody ready */
1202 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1203 GNUNET_SCHEDULER_cancel (sched,
1204 neighbour->retry_task);
1205 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1207 &retry_transmission_task,
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1212 mq->message_buf_size,
1213 GNUNET_i2s (&mq->neighbour_id),
1216 /* FIXME: might want to trigger peerinfo lookup here
1217 (unless that's already pending...) */
1220 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1221 neighbour->messages_tail,
1223 if (mq->specific_address->connected == GNUNET_NO)
1224 mq->specific_address->connect_attempts++;
1225 rl = mq->specific_address->ready_list;
1226 mq->plugin = rl->plugin;
1227 if (!mq->internal_msg)
1228 mq->specific_address->in_transmit = GNUNET_YES;
1230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1231 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1232 mq->message_buf_size,
1233 GNUNET_i2s (&neighbour->id),
1234 GNUNET_a2s (mq->specific_address->addr,
1235 mq->specific_address->addrlen),
1236 rl->plugin->short_name);
1238 rl->plugin->api->send (rl->plugin->api->cls,
1241 mq->message_buf_size,
1243 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1244 mq->specific_address->addr,
1245 mq->specific_address->addrlen,
1246 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1247 &transmit_send_continuation, mq);
1252 * Send the specified message to the specified peer.
1254 * @param client source of the transmission request (can be NULL)
1255 * @param peer_address ForeignAddressList where we should send this message
1256 * @param priority how important is the message
1257 * @param timeout how long do we have to transmit?
1258 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1259 * @param message_buf_size total size of all messages in message_buf
1260 * @param is_internal is this an internal message; these are pre-pended and
1261 * also do not count for plugins being "ready" to transmit
1262 * @param neighbour handle to the neighbour for transmission
1265 transmit_to_peer (struct TransportClient *client,
1266 struct ForeignAddressList *peer_address,
1267 unsigned int priority,
1268 struct GNUNET_TIME_Relative timeout,
1269 const char *message_buf,
1270 size_t message_buf_size,
1271 int is_internal, struct NeighbourList *neighbour)
1273 struct MessageQueue *mq;
1278 /* check for duplicate submission */
1279 mq = neighbour->messages_head;
1282 if (mq->client == client)
1284 /* client transmitted to same peer twice
1285 before getting SendOk! */
1293 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1294 mq->specific_address = peer_address;
1295 mq->client = client;
1296 memcpy (&mq[1], message_buf, message_buf_size);
1297 mq->message_buf = (const char*) &mq[1];
1298 mq->message_buf_size = message_buf_size;
1299 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1300 mq->internal_msg = is_internal;
1301 mq->priority = priority;
1302 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1304 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1305 neighbour->messages_tail,
1308 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1309 neighbour->messages_tail,
1310 neighbour->messages_tail,
1312 try_transmission_to_peer (neighbour);
1319 struct GeneratorContext
1321 struct TransportPlugin *plug_pos;
1322 struct OwnAddressList *addr_pos;
1323 struct GNUNET_TIME_Absolute expiration;
1331 address_generator (void *cls, size_t max, void *buf)
1333 struct GeneratorContext *gc = cls;
1336 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1338 gc->plug_pos = gc->plug_pos->next;
1339 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1341 if (NULL == gc->plug_pos)
1346 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1349 gc->addr_pos->addrlen, buf, max);
1350 gc->addr_pos = gc->addr_pos->next;
1356 * Construct our HELLO message from all of the addresses of
1357 * all of the transports.
1362 struct GNUNET_HELLO_Message *hello;
1363 struct TransportClient *cpos;
1364 struct NeighbourList *npos;
1365 struct GeneratorContext gc;
1367 gc.plug_pos = plugins;
1368 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1369 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1370 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1373 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1376 while (cpos != NULL)
1378 transmit_to_client (cpos,
1379 (const struct GNUNET_MessageHeader *) hello,
1384 GNUNET_free_non_null (our_hello);
1386 our_hello_version++;
1387 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1389 while (npos != NULL)
1392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1393 "Transmitting updated `%s' to neighbour `%4s'\n",
1394 "HELLO", GNUNET_i2s (&npos->id));
1396 transmit_to_peer (NULL, NULL, 0,
1397 HELLO_ADDRESS_EXPIRATION,
1398 (const char *) our_hello,
1399 GNUNET_HELLO_size(our_hello),
1407 * Task used to clean up expired addresses for a plugin.
1409 * @param cls closure
1413 expire_address_task (void *cls,
1414 const struct GNUNET_SCHEDULER_TaskContext *tc);
1418 * Update the list of addresses for this plugin,
1419 * expiring those that are past their expiration date.
1421 * @param plugin addresses of which plugin should be recomputed?
1422 * @param fresh set to GNUNET_YES if a new address was added
1423 * and we need to regenerate the HELLO even if nobody
1427 update_addresses (struct TransportPlugin *plugin, int fresh)
1429 struct GNUNET_TIME_Relative min_remaining;
1430 struct GNUNET_TIME_Relative remaining;
1431 struct GNUNET_TIME_Absolute now;
1432 struct OwnAddressList *pos;
1433 struct OwnAddressList *prev;
1434 struct OwnAddressList *next;
1437 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1438 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1439 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1440 now = GNUNET_TIME_absolute_get ();
1441 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1442 expired = GNUNET_NO;
1444 pos = plugin->addresses;
1448 if (pos->expires.value < now.value)
1450 expired = GNUNET_YES;
1452 plugin->addresses = pos->next;
1454 prev->next = pos->next;
1459 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1460 if (remaining.value < min_remaining.value)
1461 min_remaining = remaining;
1467 if (expired || fresh)
1469 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1470 plugin->address_update_task
1471 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1473 &expire_address_task, plugin);
1479 * Task used to clean up expired addresses for a plugin.
1481 * @param cls closure
1485 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1487 struct TransportPlugin *plugin = cls;
1488 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1489 update_addresses (plugin, GNUNET_NO);
1494 * Function that must be called by each plugin to notify the
1495 * transport service about the addresses under which the transport
1496 * provided by the plugin can be reached.
1498 * @param cls closure
1499 * @param name name of the transport that generated the address
1500 * @param addr one of the addresses of the host, NULL for the last address
1501 * the specific address format depends on the transport
1502 * @param addrlen length of the address
1503 * @param expires when should this address automatically expire?
1506 plugin_env_notify_address (void *cls,
1510 struct GNUNET_TIME_Relative expires)
1512 struct TransportPlugin *p = cls;
1513 struct OwnAddressList *al;
1514 struct GNUNET_TIME_Absolute abex;
1516 abex = GNUNET_TIME_relative_to_absolute (expires);
1517 GNUNET_assert (p == find_transport (name));
1522 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1524 if (al->expires.value < abex.value)
1531 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1533 al->next = p->addresses;
1536 al->addrlen = addrlen;
1537 memcpy (&al[1], addr, addrlen);
1538 update_addresses (p, GNUNET_YES);
1543 * Notify all of our clients about a peer connecting.
1546 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1547 struct GNUNET_TIME_Relative latency,
1550 struct ConnectInfoMessage cim;
1551 struct TransportClient *cpos;
1554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1555 "Notifying clients about connection from `%s'\n",
1558 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1559 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1560 cim.distance = htonl (distance);
1561 cim.latency = GNUNET_TIME_relative_hton (latency);
1562 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1564 while (cpos != NULL)
1566 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1573 * Notify all of our clients about a peer disconnecting.
1576 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1578 struct DisconnectInfoMessage dim;
1579 struct TransportClient *cpos;
1582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583 "Notifying clients about lost connection to `%s'\n",
1586 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1587 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1588 dim.reserved = htonl (0);
1589 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1591 while (cpos != NULL)
1593 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1600 * Find a ForeignAddressList entry for the given neighbour
1601 * that matches the given address and transport.
1603 * @param neighbour which peer we care about
1604 * @param tname name of the transport plugin
1605 * @param addr binary address
1606 * @param addrlen length of addr
1607 * @return NULL if no such entry exists
1609 static struct ForeignAddressList *
1610 find_peer_address(struct NeighbourList *neighbour,
1615 struct ReadyList *head;
1616 struct ForeignAddressList *address_head;
1618 head = neighbour->plugins;
1619 while (head != NULL)
1621 if (0 == strcmp (tname, head->plugin->short_name))
1628 address_head = head->addresses;
1629 while ( (address_head != NULL) &&
1630 ( (address_head->addrlen != addrlen) ||
1631 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1632 address_head = address_head->next;
1633 return address_head;
1638 * Get the peer address struct for the given neighbour and
1639 * address. If it doesn't yet exist, create it.
1641 * @param neighbour which peer we care about
1642 * @param tname name of the transport plugin
1643 * @param addr binary address
1644 * @param addrlen length of addr
1645 * @return NULL if we do not have a transport plugin for 'tname'
1647 static struct ForeignAddressList *
1648 add_peer_address(struct NeighbourList *neighbour,
1653 struct ReadyList *head;
1654 struct ForeignAddressList *ret;
1656 ret = find_peer_address (neighbour, tname, addr, addrlen);
1659 head = neighbour->plugins;
1660 while (head != NULL)
1662 if (0 == strcmp (tname, head->plugin->short_name))
1668 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1669 ret->addr = (const char*) &ret[1];
1670 memcpy (&ret[1], addr, addrlen);
1671 ret->addrlen = addrlen;
1672 ret->expires = GNUNET_TIME_relative_to_absolute
1673 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1674 ret->latency = GNUNET_TIME_relative_get_forever();
1676 ret->timeout = GNUNET_TIME_relative_to_absolute
1677 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1678 ret->ready_list = head;
1679 ret->next = head->addresses;
1680 head->addresses = ret;
1686 * Closure for 'add_validated_address'.
1688 struct AddValidatedAddressContext
1691 * Entry that has been validated.
1693 const struct ValidationEntry *ve;
1696 * Flag set after we have added the address so
1697 * that we terminate the iteration next time.
1704 * Callback function used to fill a buffer of max bytes with a list of
1705 * addresses in the format used by HELLOs. Should use
1706 * "GNUNET_HELLO_add_address" as a helper function.
1708 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1709 * @param max maximum number of bytes that can be written to buf
1710 * @param buf where to write the address information
1711 * @return number of bytes written, 0 to signal the
1712 * end of the iteration.
1715 add_validated_address (void *cls,
1716 size_t max, void *buf)
1718 struct AddValidatedAddressContext *avac = cls;
1719 const struct ValidationEntry *ve = avac->ve;
1721 if (GNUNET_YES == avac->done)
1723 avac->done = GNUNET_YES;
1724 return GNUNET_HELLO_add_address (ve->transport_name,
1725 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1733 static void send_periodic_ping(void *cls,
1734 const struct GNUNET_SCHEDULER_TaskContext *tc);
1738 * Iterator over hash map entries. Checks if the given validation
1739 * entry is for the same challenge as what is given in the PONG.
1741 * @param cls the 'struct TransportPongMessage*'
1742 * @param key peer identity
1743 * @param value value in the hash map ('struct ValidationEntry')
1744 * @return GNUNET_YES if we should continue to
1745 * iterate (mismatch), GNUNET_NO if not (entry matched)
1748 check_pending_validation (void *cls,
1749 const GNUNET_HashCode * key,
1752 const struct TransportPongMessage *pong = cls;
1753 struct ValidationEntry *ve = value;
1754 struct AddValidatedAddressContext avac;
1755 unsigned int challenge = ntohl(pong->challenge);
1756 struct GNUNET_HELLO_Message *hello;
1757 struct GNUNET_PeerIdentity target;
1758 struct NeighbourList *n;
1759 struct ForeignAddressList *fal;
1760 struct PeriodicValidationContext *periodic_validation_context;
1762 if (ve->challenge != challenge)
1766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1767 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1769 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1771 ve->transport_name);
1773 /* create the updated HELLO */
1774 GNUNET_CRYPTO_hash (&ve->publicKey,
1775 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1776 &target.hashPubKey);
1777 avac.done = GNUNET_NO;
1779 hello = GNUNET_HELLO_create (&ve->publicKey,
1780 &add_validated_address,
1782 GNUNET_PEERINFO_add_peer (cfg, sched,
1785 GNUNET_free (hello);
1786 n = find_neighbour (&target);
1789 fal = add_peer_address (n,
1793 GNUNET_assert (fal != NULL);
1794 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1795 fal->validated = GNUNET_YES;
1796 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1797 periodic_validation_context = GNUNET_malloc(sizeof(struct PeriodicValidationContext));
1798 periodic_validation_context->foreign_address = fal;
1799 periodic_validation_context->transport = strdup(ve->transport_name);
1800 memcpy(&periodic_validation_context->publicKey,
1802 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1803 /* FIXME: this causes all of the revalidation PINGs for the same HELLO
1804 to be transmitted in bulk, which is not nice; also,
1805 triggering these HERE means that revalidations do NOT happen AT ALL
1806 for HELLOs a previous instance of this process validated (since
1807 there is no "initial" validation PING => no revalidation => BUG! */
1808 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
1809 TRANSPORT_DEFAULT_REVALIDATION,
1810 &send_periodic_ping,
1811 periodic_validation_context);
1812 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1813 n->latency = fal->latency;
1815 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1816 n->distance = fal->distance;
1817 if (GNUNET_NO == n->received_pong)
1819 notify_clients_connect (&target, n->latency, n->distance);
1820 n->received_pong = GNUNET_YES;
1822 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1824 GNUNET_SCHEDULER_cancel (sched,
1826 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1827 try_transmission_to_peer (n);
1831 /* clean up validation entry */
1832 GNUNET_assert (GNUNET_YES ==
1833 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1836 GNUNET_SCHEDULER_cancel (sched,
1838 GNUNET_free (ve->transport_name);
1845 * Function that will be called if we receive a validation
1846 * of an address challenge that we transmitted to another
1847 * peer. Note that the validation should only be considered
1848 * acceptable if the challenge matches AND if the sender
1849 * address is at least a plausible address for this peer
1850 * (otherwise we may be seeing a MiM attack).
1852 * @param cls closure
1853 * @param message the pong message
1854 * @param peer who responded to our challenge
1855 * @param sender_address string describing our sender address (as observed
1856 * by the other peer in binary format)
1857 * @param sender_address_len number of bytes in 'sender_address'
1860 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1861 const struct GNUNET_PeerIdentity *peer,
1862 const char *sender_address,
1863 size_t sender_address_len)
1865 #if DEBUG_TRANSPORT > 1
1866 /* we get tons of these that just get discarded, only log
1867 if we are quite verbose */
1868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1869 "Receiving `%s' message from `%4s'.\n", "PONG",
1872 if (GNUNET_SYSERR !=
1873 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1875 &check_pending_validation,
1878 /* This is *expected* to happen a lot since we send
1879 PONGs to *all* known addresses of the sender of
1880 the PING, so most likely we get multiple PONGs
1881 per PING, and all but the first PONG will end up
1882 here. So really we should not print anything here
1883 unless we want to be very, very verbose... */
1884 #if DEBUG_TRANSPORT > 2
1885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1886 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1895 /* FIXME: add given address to potential pool of our addresses
1897 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1898 _("Another peer saw us using the address `%s' via `%s'.\n"),
1899 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1900 ntohs(pong->addrlen)),
1901 va->transport_name);
1907 neighbour_timeout_task (void *cls,
1908 const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 struct NeighbourList *n = cls;
1913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1914 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1916 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1917 disconnect_neighbour (n, GNUNET_NO);
1922 * Create a fresh entry in our neighbour list for the given peer.
1923 * Will try to transmit our current HELLO to the new neighbour. Also
1924 * notifies our clients about the new "connection".
1926 * @param peer the peer for which we create the entry
1927 * @return the new neighbour list entry
1929 static struct NeighbourList *
1930 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1932 struct NeighbourList *n;
1933 struct TransportPlugin *tp;
1934 struct ReadyList *rl;
1936 GNUNET_assert (our_hello != NULL);
1937 n = GNUNET_malloc (sizeof (struct NeighbourList));
1938 n->next = neighbours;
1942 GNUNET_TIME_relative_to_absolute
1943 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1944 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1945 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1946 MAX_BANDWIDTH_CARRY_S);
1950 if (tp->api->send != NULL)
1952 rl = GNUNET_malloc (sizeof (struct ReadyList));
1953 rl->next = n->plugins;
1956 rl->addresses = NULL;
1960 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1962 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1963 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1964 &neighbour_timeout_task, n);
1965 transmit_to_peer (NULL, NULL, 0,
1966 HELLO_ADDRESS_EXPIRATION,
1967 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1974 * Closure for 'check_address_exists'.
1976 struct CheckAddressExistsClosure
1979 * Address to check for.
1984 * Name of the transport.
1994 * Set to GNUNET_YES if the address exists.
2001 * Iterator over hash map entries. Checks if the given
2002 * validation entry is for the same address as what is given
2005 * @param cls the 'struct CheckAddressExistsClosure*'
2006 * @param key current key code (ignored)
2007 * @param value value in the hash map ('struct ValidationEntry')
2008 * @return GNUNET_YES if we should continue to
2009 * iterate (mismatch), GNUNET_NO if not (entry matched)
2012 check_address_exists (void *cls,
2013 const GNUNET_HashCode * key,
2016 struct CheckAddressExistsClosure *caec = cls;
2017 struct ValidationEntry *ve = value;
2018 if ( (0 == strcmp (caec->tname,
2019 ve->transport_name)) &&
2020 (caec->addrlen == ve->addrlen) &&
2021 (0 == memcmp (caec->addr,
2025 caec->exists = GNUNET_YES;
2033 * HELLO validation cleanup task (validation failed).
2035 * @param cls the 'struct ValidationEntry' that failed
2036 * @param tc scheduler context (unused)
2039 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2041 struct ValidationEntry *va = cls;
2042 struct GNUNET_PeerIdentity pid;
2044 GNUNET_CRYPTO_hash (&va->publicKey,
2046 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2048 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2051 GNUNET_free (va->transport_name);
2057 * Check if the given address is already being validated; if not,
2058 * append the given address to the list of entries that are being be
2059 * validated and initiate validation.
2061 * @param cls closure ('struct PeriodicValidationContext *')
2062 * @param tname name of the transport
2063 * @param expiration expiration time
2064 * @param addr the address
2065 * @param addrlen length of the address
2066 * @return GNUNET_OK (always)
2069 rerun_validation (void *cls,
2071 struct GNUNET_TIME_Absolute expiration,
2072 const void *addr, size_t addrlen)
2074 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey = cls;
2075 struct GNUNET_PeerIdentity id;
2076 struct TransportPlugin *tp;
2077 struct ValidationEntry *va;
2078 struct NeighbourList *neighbour;
2079 struct ForeignAddressList *peer_address;
2080 struct TransportPingMessage ping;
2081 /*struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;*/
2082 struct CheckAddressExistsClosure caec;
2084 uint16_t hello_size;
2087 tp = find_transport (tname);
2090 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2091 GNUNET_ERROR_TYPE_BULK,
2093 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2098 GNUNET_CRYPTO_hash (publicKey,
2100 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2103 caec.addrlen = addrlen;
2105 caec.exists = GNUNET_NO;
2106 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2107 &check_address_exists,
2109 if (caec.exists == GNUNET_YES)
2111 /* During validation attempts we will likely trigger the other
2112 peer trying to validate our address which in turn will cause
2113 it to send us its HELLO, so we expect to hit this case rather
2114 frequently. Only print something if we are very verbose. */
2115 #if DEBUG_TRANSPORT > 1
2116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2117 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2118 GNUNET_a2s (addr, addrlen),
2124 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2125 va->transport_name = GNUNET_strdup (tname);
2126 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2128 va->send_time = GNUNET_TIME_absolute_get();
2129 va->addr = (const void*) &va[1];
2130 memcpy (&va[1], addr, addrlen);
2131 va->addrlen = addrlen;
2132 memcpy(&va->publicKey, publicKey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2133 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2134 HELLO_VERIFICATION_TIMEOUT,
2135 &timeout_hello_validation,
2137 GNUNET_CONTAINER_multihashmap_put (validation_map,
2140 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2141 neighbour = find_neighbour(&id);
2142 if (neighbour == NULL)
2143 neighbour = setup_new_neighbour(&id);
2144 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2145 GNUNET_assert(peer_address != NULL);
2146 hello_size = GNUNET_HELLO_size(our_hello);
2147 tsize = sizeof(struct TransportPingMessage) + hello_size;
2148 message_buf = GNUNET_malloc(tsize);
2149 ping.challenge = htonl(va->challenge);
2150 ping.header.size = htons(sizeof(struct TransportPingMessage));
2151 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2152 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2153 memcpy(message_buf, our_hello, hello_size);
2154 memcpy(&message_buf[hello_size],
2156 sizeof(struct TransportPingMessage));
2157 #if DEBUG_TRANSPORT_REVALIDATION
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2160 GNUNET_a2s (addr, addrlen),
2163 "HELLO", hello_size,
2164 "PING", sizeof (struct TransportPingMessage));
2166 transmit_to_peer (NULL, peer_address,
2167 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2168 HELLO_VERIFICATION_TIMEOUT,
2170 GNUNET_YES, neighbour);
2171 GNUNET_free(message_buf);
2177 * Send periodic ping messages to a give foreign address.
2179 * cls closure, can be safely cast to ForeignAddressList
2182 * FIXME: Since a _billion_ pongs are sent for every ping,
2183 * maybe this should be a special message type or something
2184 * that gets discarded on the other side instead of initiating
2188 send_periodic_ping (void *cls,
2189 const struct GNUNET_SCHEDULER_TaskContext *tc)
2191 struct PeriodicValidationContext *periodic_validation_context = cls;
2193 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2195 GNUNET_free(periodic_validation_context->transport);
2196 GNUNET_free(periodic_validation_context);
2197 return; /* We have been shutdown, don't do anything! */
2199 rerun_validation(&periodic_validation_context->publicKey,
2200 periodic_validation_context->transport,
2201 periodic_validation_context->foreign_address->expires,
2202 periodic_validation_context->foreign_address->addr,
2203 periodic_validation_context->foreign_address->addrlen);
2204 GNUNET_free(periodic_validation_context->transport);
2205 GNUNET_free(periodic_validation_context);
2210 * Check if the given address is already being validated; if not,
2211 * append the given address to the list of entries that are being be
2212 * validated and initiate validation.
2214 * @param cls closure ('struct CheckHelloValidatedContext *')
2215 * @param tname name of the transport
2216 * @param expiration expiration time
2217 * @param addr the address
2218 * @param addrlen length of the address
2219 * @return GNUNET_OK (always)
2222 run_validation (void *cls,
2224 struct GNUNET_TIME_Absolute expiration,
2225 const void *addr, size_t addrlen)
2227 struct CheckHelloValidatedContext *chvc = cls;
2228 struct GNUNET_PeerIdentity id;
2229 struct TransportPlugin *tp;
2230 struct ValidationEntry *va;
2231 struct NeighbourList *neighbour;
2232 struct ForeignAddressList *peer_address;
2233 struct TransportPingMessage ping;
2234 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2235 struct CheckAddressExistsClosure caec;
2237 uint16_t hello_size;
2240 tp = find_transport (tname);
2243 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2244 GNUNET_ERROR_TYPE_BULK,
2246 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2250 GNUNET_HELLO_get_key (chvc->hello, &pk);
2251 GNUNET_CRYPTO_hash (&pk,
2253 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2256 caec.addrlen = addrlen;
2258 caec.exists = GNUNET_NO;
2259 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2260 &check_address_exists,
2262 if (caec.exists == GNUNET_YES)
2264 /* During validation attempts we will likely trigger the other
2265 peer trying to validate our address which in turn will cause
2266 it to send us its HELLO, so we expect to hit this case rather
2267 frequently. Only print something if we are very verbose. */
2268 #if DEBUG_TRANSPORT > 1
2269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2271 GNUNET_a2s (addr, addrlen),
2277 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2278 va->transport_name = GNUNET_strdup (tname);
2279 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2281 va->send_time = GNUNET_TIME_absolute_get();
2282 va->addr = (const void*) &va[1];
2283 memcpy (&va[1], addr, addrlen);
2284 va->addrlen = addrlen;
2285 GNUNET_HELLO_get_key (chvc->hello,
2287 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2288 HELLO_VERIFICATION_TIMEOUT,
2289 &timeout_hello_validation,
2291 GNUNET_CONTAINER_multihashmap_put (validation_map,
2294 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2295 neighbour = find_neighbour(&id);
2296 if (neighbour == NULL)
2297 neighbour = setup_new_neighbour(&id);
2298 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2299 GNUNET_assert(peer_address != NULL);
2300 hello_size = GNUNET_HELLO_size(our_hello);
2301 tsize = sizeof(struct TransportPingMessage) + hello_size;
2302 message_buf = GNUNET_malloc(tsize);
2303 ping.challenge = htonl(va->challenge);
2304 ping.header.size = htons(sizeof(struct TransportPingMessage));
2305 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2306 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2307 memcpy(message_buf, our_hello, hello_size);
2308 memcpy(&message_buf[hello_size],
2310 sizeof(struct TransportPingMessage));
2312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2313 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2314 GNUNET_a2s (addr, addrlen),
2317 "HELLO", hello_size,
2318 "PING", sizeof (struct TransportPingMessage));
2320 transmit_to_peer (NULL, peer_address,
2321 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2322 HELLO_VERIFICATION_TIMEOUT,
2324 GNUNET_YES, neighbour);
2325 GNUNET_free(message_buf);
2331 * Add the given address to the list of foreign addresses
2332 * available for the given peer (check for duplicates).
2334 * @param cls the respective 'struct NeighbourList' to update
2335 * @param tname name of the transport
2336 * @param expiration expiration time
2337 * @param addr the address
2338 * @param addrlen length of the address
2339 * @return GNUNET_OK (always)
2342 add_to_foreign_address_list (void *cls,
2344 struct GNUNET_TIME_Absolute expiration,
2345 const void *addr, size_t addrlen)
2347 struct NeighbourList *n = cls;
2348 struct ForeignAddressList *fal;
2352 fal = find_peer_address (n, tname, addr, addrlen);
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2358 GNUNET_a2s (addr, addrlen),
2360 GNUNET_i2s (&n->id),
2363 fal = add_peer_address (n, tname, addr, addrlen);
2368 fal->expires = GNUNET_TIME_absolute_max (expiration,
2370 fal->validated = GNUNET_YES;
2371 if (try == GNUNET_YES)
2372 try_transmission_to_peer (n);
2378 * Check if addresses in validated hello "h" overlap with
2379 * those in "chvc->hello" and validate the rest.
2381 * @param cls closure
2382 * @param peer id of the peer, NULL for last call
2383 * @param h hello message for the peer (can be NULL)
2384 * @param trust amount of trust we have in the peer (not used)
2387 check_hello_validated (void *cls,
2388 const struct GNUNET_PeerIdentity *peer,
2389 const struct GNUNET_HELLO_Message *h,
2392 struct CheckHelloValidatedContext *chvc = cls;
2393 struct GNUNET_HELLO_Message *plain_hello;
2394 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2395 struct GNUNET_PeerIdentity target;
2396 struct NeighbourList *n;
2401 GNUNET_CONTAINER_DLL_remove (chvc_head,
2404 if (GNUNET_NO == chvc->hello_known)
2406 /* notify PEERINFO about the peer now, so that we at least
2407 have the public key if some other component needs it */
2408 GNUNET_HELLO_get_key (chvc->hello, &pk);
2409 GNUNET_CRYPTO_hash (&pk,
2410 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2411 &target.hashPubKey);
2412 plain_hello = GNUNET_HELLO_create (&pk,
2415 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2416 GNUNET_free (plain_hello);
2418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2421 GNUNET_i2s (&target));
2423 GNUNET_HELLO_iterate_addresses (chvc->hello,
2433 chvc->hello_known = GNUNET_YES;
2434 n = find_neighbour (peer);
2437 GNUNET_HELLO_iterate_addresses (h,
2439 &add_to_foreign_address_list,
2441 try_transmission_to_peer (n);
2443 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2445 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2451 * Process HELLO-message.
2453 * @param plugin transport involved, may be NULL
2454 * @param message the actual message
2455 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2458 process_hello (struct TransportPlugin *plugin,
2459 const struct GNUNET_MessageHeader *message)
2462 struct GNUNET_PeerIdentity target;
2463 const struct GNUNET_HELLO_Message *hello;
2464 struct CheckHelloValidatedContext *chvc;
2465 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2467 hsize = ntohs (message->size);
2468 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2469 (hsize < sizeof (struct GNUNET_MessageHeader)))
2472 return GNUNET_SYSERR;
2474 /* first, check if load is too high */
2475 if (GNUNET_SCHEDULER_get_load (sched,
2476 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2478 /* TODO: call to stats? */
2481 hello = (const struct GNUNET_HELLO_Message *) message;
2482 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2484 GNUNET_break_op (0);
2485 return GNUNET_SYSERR;
2487 GNUNET_CRYPTO_hash (&publicKey,
2488 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2489 &target.hashPubKey);
2490 #if DEBUG_TRANSPORT > 1
2491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2492 "Processing `%s' message for `%4s' of size %u\n",
2494 GNUNET_i2s (&target),
2495 GNUNET_HELLO_size(hello));
2497 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2498 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2499 memcpy (&chvc[1], hello, hsize);
2500 GNUNET_CONTAINER_DLL_insert (chvc_head,
2503 /* finally, check if HELLO was previously validated
2504 (continuation will then schedule actual validation) */
2505 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2509 HELLO_VERIFICATION_TIMEOUT,
2510 &check_hello_validated, chvc);
2516 * The peer specified by the given neighbour has timed-out or a plugin
2517 * has disconnected. We may either need to do nothing (other plugins
2518 * still up), or trigger a full disconnect and clean up. This
2519 * function updates our state and does the necessary notifications.
2520 * Also notifies our clients that the neighbour is now officially
2523 * @param n the neighbour list entry for the peer
2524 * @param check should we just check if all plugins
2525 * disconnected or must we ask all plugins to
2529 disconnect_neighbour (struct NeighbourList *n, int check)
2531 struct ReadyList *rpos;
2532 struct NeighbourList *npos;
2533 struct NeighbourList *nprev;
2534 struct MessageQueue *mq;
2535 struct ForeignAddressList *peer_addresses;
2536 struct ForeignAddressList *peer_pos;
2538 if (GNUNET_YES == check)
2541 while (NULL != rpos)
2543 peer_addresses = rpos->addresses;
2544 while (peer_addresses != NULL)
2546 if (GNUNET_YES == peer_addresses->connected)
2547 return; /* still connected */
2548 peer_addresses = peer_addresses->next;
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2555 "Disconnecting from `%4s'\n",
2556 GNUNET_i2s (&n->id));
2558 /* remove n from neighbours list */
2561 while ((npos != NULL) && (npos != n))
2566 GNUNET_assert (npos != NULL);
2568 neighbours = n->next;
2570 nprev->next = n->next;
2572 /* notify all clients about disconnect */
2573 if (GNUNET_YES == n->received_pong)
2574 notify_clients_disconnect (&n->id);
2576 /* clean up all plugins, cancel connections and pending transmissions */
2577 while (NULL != (rpos = n->plugins))
2579 n->plugins = rpos->next;
2580 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2582 while (rpos->addresses != NULL)
2584 peer_pos = rpos->addresses;
2585 rpos->addresses = peer_pos->next;
2586 GNUNET_free(peer_pos);
2591 /* free all messages on the queue */
2592 while (NULL != (mq = n->messages_head))
2594 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2597 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2599 sizeof(struct GNUNET_PeerIdentity)));
2602 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2604 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2605 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2607 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2609 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2610 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2612 /* finally, free n itself */
2618 * We have received a PING message from someone. Need to send a PONG message
2619 * in response to the peer by any means necessary.
2621 * FIXME: With something like TCP where a connection exists, we may
2622 * want to send it that way. But the current API does not seem to
2623 * allow us to do so (can't tell this to the transport!)
2626 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2627 const struct GNUNET_PeerIdentity *peer,
2628 const char *sender_address,
2629 size_t sender_address_len)
2631 struct TransportPlugin *plugin = cls;
2632 struct TransportPingMessage *ping;
2633 struct TransportPongMessage *pong;
2634 struct NeighbourList *n;
2635 struct ReadyList *rl;
2636 struct ForeignAddressList *fal;
2638 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2640 GNUNET_break_op (0);
2641 return GNUNET_SYSERR;
2643 ping = (struct TransportPingMessage *) message;
2644 if (0 != memcmp (&ping->target,
2645 plugin->env.my_identity,
2646 sizeof (struct GNUNET_PeerIdentity)))
2648 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2649 _("Received `%s' message not destined for me!\n"),
2651 return GNUNET_SYSERR;
2654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2655 "Processing `%s' from `%s'\n",
2657 GNUNET_a2s ((const struct sockaddr *)sender_address,
2658 sender_address_len));
2660 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2661 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2662 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2663 pong->purpose.size =
2664 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2666 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2667 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2668 pong->challenge = ping->challenge;
2669 pong->addrlen = htons(sender_address_len);
2670 memcpy(&pong->signer,
2672 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2673 memcpy (&pong[1], sender_address, sender_address_len);
2674 GNUNET_assert (GNUNET_OK ==
2675 GNUNET_CRYPTO_rsa_sign (my_private_key,
2676 &pong->purpose, &pong->signature));
2678 n = find_neighbour(peer);
2680 n = setup_new_neighbour(peer);
2681 /* broadcast 'PONG' to all available addresses */
2685 fal = rl->addresses;
2688 transmit_to_peer(NULL, fal,
2689 TRANSPORT_PONG_PRIORITY,
2690 HELLO_VERIFICATION_TIMEOUT,
2692 ntohs(pong->header.size),
2705 * Function called by the plugin for each received message.
2706 * Update data volumes, possibly notify plugins about
2707 * reducing the rate at which they read from the socket
2708 * and generally forward to our receive callback.
2710 * @param cls the "struct TransportPlugin *" we gave to the plugin
2711 * @param peer (claimed) identity of the other peer
2712 * @param message the message, NULL if we only care about
2713 * learning about the delay until we should receive again
2714 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2715 * @param sender_address binary address of the sender (if observed)
2716 * @param sender_address_len number of bytes in sender_address
2717 * @return how long the plugin should wait until receiving more data
2718 * (plugins that do not support this, can ignore the return value)
2720 static struct GNUNET_TIME_Relative
2721 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2722 const struct GNUNET_MessageHeader *message,
2723 unsigned int distance, const char *sender_address,
2724 size_t sender_address_len)
2726 struct ReadyList *service_context;
2727 struct TransportPlugin *plugin = cls;
2728 struct TransportClient *cpos;
2729 struct InboundMessage *im;
2730 struct ForeignAddressList *peer_address;
2732 struct NeighbourList *n;
2733 struct GNUNET_TIME_Relative ret;
2735 n = find_neighbour (peer);
2737 n = setup_new_neighbour (peer);
2738 service_context = n->plugins;
2739 while ((service_context != NULL) && (plugin != service_context->plugin))
2740 service_context = service_context->next;
2741 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2742 if (message != NULL)
2744 peer_address = add_peer_address(n,
2747 sender_address_len);
2748 if (peer_address != NULL)
2750 peer_address->distance = distance;
2751 if (peer_address->connected == GNUNET_NO)
2753 peer_address->connected = GNUNET_YES;
2754 peer_address->connect_attempts++;
2756 peer_address->timeout
2758 GNUNET_TIME_relative_to_absolute
2759 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2761 /* update traffic received amount ... */
2762 msize = ntohs (message->size);
2763 n->distance = distance;
2765 GNUNET_TIME_relative_to_absolute
2766 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2767 GNUNET_SCHEDULER_cancel (sched,
2770 GNUNET_SCHEDULER_add_delayed (sched,
2771 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2772 &neighbour_timeout_task, n);
2773 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2775 /* dropping message due to frequent inbound volume violations! */
2776 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2777 GNUNET_ERROR_TYPE_BULK,
2779 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
2780 n->in_tracker.available_bytes_per_s__,
2781 n->quota_violation_count);
2782 return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2784 switch (ntohs (message->type))
2786 case GNUNET_MESSAGE_TYPE_HELLO:
2787 process_hello (plugin, message);
2789 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2790 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2792 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2793 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2798 "Received message of type %u from `%4s', sending to all clients.\n",
2799 ntohs (message->type), GNUNET_i2s (peer));
2801 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2803 n->quota_violation_count++;
2805 n->quota_violation_count = 0; /* back within limits */
2806 /* transmit message to all clients */
2807 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2808 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2809 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2810 im->latency = GNUNET_TIME_relative_hton (n->latency);
2812 memcpy (&im[1], message, msize);
2814 while (cpos != NULL)
2816 transmit_to_client (cpos, &im->header, GNUNET_YES);
2822 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
2824 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2825 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
2826 (unsigned long long) n->in_tracker.consumption_since_last_update__,
2827 (unsigned int) n->in_tracker.available_bytes_per_s__,
2828 (unsigned long long) ret.value);
2834 * Handle START-message. This is the first message sent to us
2835 * by any client which causes us to add it to our list.
2837 * @param cls closure (always NULL)
2838 * @param client identification of the client
2839 * @param message the actual message
2842 handle_start (void *cls,
2843 struct GNUNET_SERVER_Client *client,
2844 const struct GNUNET_MessageHeader *message)
2846 struct TransportClient *c;
2847 struct ConnectInfoMessage cim;
2848 struct NeighbourList *n;
2851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2852 "Received `%s' request from client\n", "START");
2857 if (c->client == client)
2859 /* client already on our list! */
2861 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2866 c = GNUNET_malloc (sizeof (struct TransportClient));
2870 if (our_hello != NULL)
2873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2874 "Sending our own `%s' to new client\n", "HELLO");
2876 transmit_to_client (c,
2877 (const struct GNUNET_MessageHeader *) our_hello,
2879 /* tell new client about all existing connections */
2880 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2881 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2885 if (GNUNET_YES == n->received_pong)
2888 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2889 cim.distance = htonl (n->distance);
2890 transmit_to_client (c, &cim.header, GNUNET_NO);
2895 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2900 * Handle HELLO-message.
2902 * @param cls closure (always NULL)
2903 * @param client identification of the client
2904 * @param message the actual message
2907 handle_hello (void *cls,
2908 struct GNUNET_SERVER_Client *client,
2909 const struct GNUNET_MessageHeader *message)
2913 ret = process_hello (NULL, message);
2914 GNUNET_SERVER_receive_done (client, ret);
2919 * Handle SEND-message.
2921 * @param cls closure (always NULL)
2922 * @param client identification of the client
2923 * @param message the actual message
2926 handle_send (void *cls,
2927 struct GNUNET_SERVER_Client *client,
2928 const struct GNUNET_MessageHeader *message)
2930 struct TransportClient *tc;
2931 struct NeighbourList *n;
2932 const struct OutboundMessage *obm;
2933 const struct GNUNET_MessageHeader *obmm;
2937 size = ntohs (message->size);
2939 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2942 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2945 obm = (const struct OutboundMessage *) message;
2947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2948 "Received `%s' request from client with target `%4s'\n",
2949 "SEND", GNUNET_i2s (&obm->peer));
2951 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2952 msize = ntohs (obmm->size);
2953 if (size != msize + sizeof (struct OutboundMessage))
2956 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2959 n = find_neighbour (&obm->peer);
2961 n = setup_new_neighbour (&obm->peer);
2963 while ((tc != NULL) && (tc->client != client))
2967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2970 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2972 transmit_to_peer (tc, NULL, ntohl (obm->priority),
2973 GNUNET_TIME_relative_ntoh (obm->timeout),
2975 ntohs (obmm->size), GNUNET_NO, n);
2976 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2981 * Handle SET_QUOTA-message.
2983 * @param cls closure (always NULL)
2984 * @param client identification of the client
2985 * @param message the actual message
2988 handle_set_quota (void *cls,
2989 struct GNUNET_SERVER_Client *client,
2990 const struct GNUNET_MessageHeader *message)
2992 const struct QuotaSetMessage *qsm =
2993 (const struct QuotaSetMessage *) message;
2994 struct NeighbourList *n;
2996 n = find_neighbour (&qsm->peer);
2999 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3006 (unsigned int) ntohl (qsm->quota.value__),
3007 (unsigned int) n->in_tracker.available_bytes_per_s__,
3008 GNUNET_i2s (&qsm->peer));
3010 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3012 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3017 transmit_address_to_client (void *cls, const char *address)
3019 struct GNUNET_SERVER_TransmitContext *tc = cls;
3022 if (NULL == address)
3025 slen = strlen (address) + 1;
3026 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3027 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3028 if (NULL == address)
3029 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3034 * Handle AddressLookup-message.
3036 * @param cls closure (always NULL)
3037 * @param client identification of the client
3038 * @param message the actual message
3041 handle_address_lookup (void *cls,
3042 struct GNUNET_SERVER_Client *client,
3043 const struct GNUNET_MessageHeader *message)
3045 const struct AddressLookupMessage *alum;
3046 struct TransportPlugin *lsPlugin;
3047 const char *nameTransport;
3048 const char *address;
3050 struct GNUNET_SERVER_TransmitContext *tc;
3052 size = ntohs (message->size);
3053 if (size < sizeof (struct AddressLookupMessage))
3055 GNUNET_break_op (0);
3056 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3059 alum = (const struct AddressLookupMessage *) message;
3060 uint32_t addressLen = ntohl (alum->addrlen);
3061 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3063 GNUNET_break_op (0);
3064 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3067 address = (const char *) &alum[1];
3068 nameTransport = (const char *) &address[addressLen];
3070 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3072 GNUNET_break_op (0);
3073 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3076 struct GNUNET_TIME_Absolute timeout =
3077 GNUNET_TIME_absolute_ntoh (alum->timeout);
3078 struct GNUNET_TIME_Relative rtimeout =
3079 GNUNET_TIME_absolute_get_remaining (timeout);
3080 lsPlugin = find_transport (nameTransport);
3081 if (NULL == lsPlugin)
3083 tc = GNUNET_SERVER_transmit_context_create (client);
3084 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3085 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3086 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3089 tc = GNUNET_SERVER_transmit_context_create (client);
3090 lsPlugin->api->address_pretty_printer (cls, nameTransport,
3091 address, addressLen, GNUNET_YES,
3093 &transmit_address_to_client, tc);
3097 * List of handlers for the messages understood by this
3100 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3101 {&handle_start, NULL,
3102 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3103 {&handle_hello, NULL,
3104 GNUNET_MESSAGE_TYPE_HELLO, 0},
3105 {&handle_send, NULL,
3106 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3107 {&handle_set_quota, NULL,
3108 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3109 {&handle_address_lookup, NULL,
3110 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3117 * Setup the environment for this plugin.
3120 create_environment (struct TransportPlugin *plug)
3122 plug->env.cfg = cfg;
3123 plug->env.sched = sched;
3124 plug->env.my_identity = &my_identity;
3125 plug->env.cls = plug;
3126 plug->env.receive = &plugin_env_receive;
3127 plug->env.notify_address = &plugin_env_notify_address;
3128 plug->env.max_connections = max_connect_per_transport;
3133 * Start the specified transport (load the plugin).
3136 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3138 struct TransportPlugin *plug;
3141 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3142 _("Loading `%s' transport plugin\n"), name);
3143 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3144 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3145 create_environment (plug);
3146 plug->short_name = GNUNET_strdup (name);
3147 plug->lib_name = libname;
3148 plug->next = plugins;
3150 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3151 if (plug->api == NULL)
3153 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3154 _("Failed to load transport plugin for `%s'\n"), name);
3155 GNUNET_free (plug->short_name);
3156 plugins = plug->next;
3157 GNUNET_free (libname);
3164 * Called whenever a client is disconnected. Frees our
3165 * resources associated with that client.
3167 * @param cls closure
3168 * @param client identification of the client
3171 client_disconnect_notification (void *cls,
3172 struct GNUNET_SERVER_Client *client)
3174 struct TransportClient *pos;
3175 struct TransportClient *prev;
3176 struct ClientMessageQueueEntry *mqe;
3181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3182 "Client disconnected, cleaning up.\n");
3186 while ((pos != NULL) && (pos->client != client))
3193 while (NULL != (mqe = pos->message_queue_head))
3195 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3196 pos->message_queue_tail,
3198 pos->message_count--;
3202 clients = pos->next;
3204 prev->next = pos->next;
3205 if (GNUNET_YES == pos->tcs_pending)
3210 if (pos->th != NULL)
3212 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3215 GNUNET_break (0 == pos->message_count);
3221 * Iterator to free entries in the validation_map.
3223 * @param cls closure (unused)
3224 * @param key current key code
3225 * @param value value in the hash map (validation to abort)
3226 * @return GNUNET_YES (always)
3229 abort_validation (void *cls,
3230 const GNUNET_HashCode * key,
3233 struct ValidationEntry *va = value;
3235 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3236 GNUNET_free (va->transport_name);
3243 * Function called when the service shuts down. Unloads our plugins
3244 * and cancels pending validations.
3246 * @param cls closure, unused
3247 * @param tc task context (unused)
3250 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3252 struct TransportPlugin *plug;
3253 struct OwnAddressList *al;
3254 struct CheckHelloValidatedContext *chvc;
3256 while (neighbours != NULL)
3257 disconnect_neighbour (neighbours, GNUNET_NO);
3259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3260 "Transport service is unloading plugins...\n");
3262 while (NULL != (plug = plugins))
3264 plugins = plug->next;
3265 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3266 GNUNET_free (plug->lib_name);
3267 GNUNET_free (plug->short_name);
3268 while (NULL != (al = plug->addresses))
3270 plug->addresses = al->next;
3275 if (my_private_key != NULL)
3276 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3277 GNUNET_free_non_null (our_hello);
3279 /* free 'chvc' data structure */
3280 while (NULL != (chvc = chvc_head))
3282 chvc_head = chvc->next;
3283 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3288 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3291 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3296 * Initiate transport service.
3298 * @param cls closure
3299 * @param s scheduler to use
3300 * @param serv the initialized server
3301 * @param c configuration to use
3305 struct GNUNET_SCHEDULER_Handle *s,
3306 struct GNUNET_SERVER_Handle *serv,
3307 const struct GNUNET_CONFIGURATION_Handle *c)
3312 unsigned long long tneigh;
3317 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3318 /* parse configuration */
3320 GNUNET_CONFIGURATION_get_value_number (c,
3325 GNUNET_CONFIGURATION_get_value_filename (c,
3327 "HOSTKEY", &keyfile)))
3329 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3331 ("Transport service is lacking key configuration settings. Exiting.\n"));
3332 GNUNET_SCHEDULER_shutdown (s);
3335 max_connect_per_transport = (uint32_t) tneigh;
3336 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3337 GNUNET_free (keyfile);
3338 if (my_private_key == NULL)
3340 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3342 ("Transport service could not access hostkey. Exiting.\n"));
3343 GNUNET_SCHEDULER_shutdown (s);
3346 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3347 GNUNET_CRYPTO_hash (&my_public_key,
3348 sizeof (my_public_key), &my_identity.hashPubKey);
3349 /* setup notification */
3351 GNUNET_SERVER_disconnect_notify (server,
3352 &client_disconnect_notification, NULL);
3353 /* load plugins... */
3356 GNUNET_CONFIGURATION_get_value_string (c,
3357 "TRANSPORT", "PLUGINS", &plugs))
3359 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3360 _("Starting transport plugins `%s'\n"), plugs);
3361 pos = strtok (plugs, " ");
3364 start_transport (server, pos);
3366 pos = strtok (NULL, " ");
3368 GNUNET_free (plugs);
3370 GNUNET_SCHEDULER_add_delayed (sched,
3371 GNUNET_TIME_UNIT_FOREVER_REL,
3372 &shutdown_task, NULL);
3377 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3379 /* process client requests */
3380 GNUNET_SERVER_add_handlers (server, handlers);
3385 * The main function for the transport service.
3387 * @param argc number of arguments from the command line
3388 * @param argv command line arguments
3389 * @return 0 ok, 1 on error
3392 main (int argc, char *const *argv)
3394 return (GNUNET_OK ==
3395 GNUNET_SERVICE_run (argc,
3398 GNUNET_SERVICE_OPTION_NONE,
3399 &run, NULL)) ? 0 : 1;
3402 /* end of gnunet-service-transport.c */