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 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1794 fal->validated = GNUNET_YES;
1795 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1796 periodic_validation_context = GNUNET_malloc(sizeof(struct PeriodicValidationContext));
1797 periodic_validation_context->foreign_address = fal;
1798 periodic_validation_context->transport = strdup(ve->transport_name);
1799 memcpy(&periodic_validation_context->publicKey,
1801 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1802 /* FIXME: this causes all of the revalidation PINGs for the same HELLO
1803 to be transmitted in bulk, which is not nice; also,
1804 triggering these HERE means that revalidations do NOT happen AT ALL
1805 for HELLOs a previous instance of this process validated (since
1806 there is no "initial" validation PING => no revalidation => BUG! */
1807 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
1808 TRANSPORT_DEFAULT_REVALIDATION,
1809 &send_periodic_ping,
1810 periodic_validation_context);
1811 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1812 n->latency = fal->latency;
1814 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1815 n->distance = fal->distance;
1816 if (GNUNET_NO == n->received_pong)
1818 notify_clients_connect (&target, n->latency, n->distance);
1819 n->received_pong = GNUNET_YES;
1821 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1823 GNUNET_SCHEDULER_cancel (sched,
1825 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1826 try_transmission_to_peer (n);
1830 /* clean up validation entry */
1831 GNUNET_assert (GNUNET_YES ==
1832 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1835 GNUNET_SCHEDULER_cancel (sched,
1837 GNUNET_free (ve->transport_name);
1844 * Function that will be called if we receive a validation
1845 * of an address challenge that we transmitted to another
1846 * peer. Note that the validation should only be considered
1847 * acceptable if the challenge matches AND if the sender
1848 * address is at least a plausible address for this peer
1849 * (otherwise we may be seeing a MiM attack).
1851 * @param cls closure
1852 * @param message the pong message
1853 * @param peer who responded to our challenge
1854 * @param sender_address string describing our sender address (as observed
1855 * by the other peer in binary format)
1856 * @param sender_address_len number of bytes in 'sender_address'
1859 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1860 const struct GNUNET_PeerIdentity *peer,
1861 const char *sender_address,
1862 size_t sender_address_len)
1864 #if DEBUG_TRANSPORT > 1
1865 /* we get tons of these that just get discarded, only log
1866 if we are quite verbose */
1867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1868 "Receiving `%s' message from `%4s'.\n", "PONG",
1871 if (GNUNET_SYSERR !=
1872 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1874 &check_pending_validation,
1877 /* This is *expected* to happen a lot since we send
1878 PONGs to *all* known addresses of the sender of
1879 the PING, so most likely we get multiple PONGs
1880 per PING, and all but the first PONG will end up
1881 here. So really we should not print anything here
1882 unless we want to be very, very verbose... */
1883 #if DEBUG_TRANSPORT > 2
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1894 /* FIXME: add given address to potential pool of our addresses
1896 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1897 _("Another peer saw us using the address `%s' via `%s'.\n"),
1898 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1899 ntohs(pong->addrlen)),
1900 va->transport_name);
1906 neighbour_timeout_task (void *cls,
1907 const struct GNUNET_SCHEDULER_TaskContext *tc)
1909 struct NeighbourList *n = cls;
1912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1913 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1915 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1916 disconnect_neighbour (n, GNUNET_NO);
1921 * Create a fresh entry in our neighbour list for the given peer.
1922 * Will try to transmit our current HELLO to the new neighbour. Also
1923 * notifies our clients about the new "connection".
1925 * @param peer the peer for which we create the entry
1926 * @return the new neighbour list entry
1928 static struct NeighbourList *
1929 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1931 struct NeighbourList *n;
1932 struct TransportPlugin *tp;
1933 struct ReadyList *rl;
1935 GNUNET_assert (our_hello != NULL);
1936 n = GNUNET_malloc (sizeof (struct NeighbourList));
1937 n->next = neighbours;
1941 GNUNET_TIME_relative_to_absolute
1942 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1943 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1944 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1945 MAX_BANDWIDTH_CARRY_S);
1949 if (tp->api->send != NULL)
1951 rl = GNUNET_malloc (sizeof (struct ReadyList));
1952 rl->next = n->plugins;
1955 rl->addresses = NULL;
1959 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1961 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1962 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1963 &neighbour_timeout_task, n);
1964 transmit_to_peer (NULL, NULL, 0,
1965 HELLO_ADDRESS_EXPIRATION,
1966 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1973 * Closure for 'check_address_exists'.
1975 struct CheckAddressExistsClosure
1978 * Address to check for.
1983 * Name of the transport.
1993 * Set to GNUNET_YES if the address exists.
2000 * Iterator over hash map entries. Checks if the given
2001 * validation entry is for the same address as what is given
2004 * @param cls the 'struct CheckAddressExistsClosure*'
2005 * @param key current key code (ignored)
2006 * @param value value in the hash map ('struct ValidationEntry')
2007 * @return GNUNET_YES if we should continue to
2008 * iterate (mismatch), GNUNET_NO if not (entry matched)
2011 check_address_exists (void *cls,
2012 const GNUNET_HashCode * key,
2015 struct CheckAddressExistsClosure *caec = cls;
2016 struct ValidationEntry *ve = value;
2017 if ( (0 == strcmp (caec->tname,
2018 ve->transport_name)) &&
2019 (caec->addrlen == ve->addrlen) &&
2020 (0 == memcmp (caec->addr,
2024 caec->exists = GNUNET_YES;
2032 * HELLO validation cleanup task (validation failed).
2034 * @param cls the 'struct ValidationEntry' that failed
2035 * @param tc scheduler context (unused)
2038 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2040 struct ValidationEntry *va = cls;
2041 struct GNUNET_PeerIdentity pid;
2043 GNUNET_CRYPTO_hash (&va->publicKey,
2045 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2047 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2050 GNUNET_free (va->transport_name);
2056 * Check if the given address is already being validated; if not,
2057 * append the given address to the list of entries that are being be
2058 * validated and initiate validation.
2060 * @param cls closure ('struct PeriodicValidationContext *')
2061 * @param tname name of the transport
2062 * @param expiration expiration time
2063 * @param addr the address
2064 * @param addrlen length of the address
2065 * @return GNUNET_OK (always)
2068 rerun_validation (void *cls,
2070 struct GNUNET_TIME_Absolute expiration,
2071 const void *addr, size_t addrlen)
2073 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey = cls;
2074 struct GNUNET_PeerIdentity id;
2075 struct TransportPlugin *tp;
2076 struct ValidationEntry *va;
2077 struct NeighbourList *neighbour;
2078 struct ForeignAddressList *peer_address;
2079 struct TransportPingMessage ping;
2080 /*struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;*/
2081 struct CheckAddressExistsClosure caec;
2083 uint16_t hello_size;
2086 tp = find_transport (tname);
2089 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2090 GNUNET_ERROR_TYPE_BULK,
2092 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2097 GNUNET_CRYPTO_hash (publicKey,
2099 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2102 caec.addrlen = addrlen;
2104 caec.exists = GNUNET_NO;
2105 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2106 &check_address_exists,
2108 if (caec.exists == GNUNET_YES)
2110 /* During validation attempts we will likely trigger the other
2111 peer trying to validate our address which in turn will cause
2112 it to send us its HELLO, so we expect to hit this case rather
2113 frequently. Only print something if we are very verbose. */
2114 #if DEBUG_TRANSPORT > 1
2115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2116 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2117 GNUNET_a2s (addr, addrlen),
2123 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2124 va->transport_name = GNUNET_strdup (tname);
2125 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2127 va->send_time = GNUNET_TIME_absolute_get();
2128 va->addr = (const void*) &va[1];
2129 memcpy (&va[1], addr, addrlen);
2130 va->addrlen = addrlen;
2131 memcpy(&va->publicKey, publicKey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2132 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2133 HELLO_VERIFICATION_TIMEOUT,
2134 &timeout_hello_validation,
2136 GNUNET_CONTAINER_multihashmap_put (validation_map,
2139 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2140 neighbour = find_neighbour(&id);
2141 if (neighbour == NULL)
2142 neighbour = setup_new_neighbour(&id);
2143 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2144 GNUNET_assert(peer_address != NULL);
2145 hello_size = GNUNET_HELLO_size(our_hello);
2146 tsize = sizeof(struct TransportPingMessage) + hello_size;
2147 message_buf = GNUNET_malloc(tsize);
2148 ping.challenge = htonl(va->challenge);
2149 ping.header.size = htons(sizeof(struct TransportPingMessage));
2150 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2151 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2152 memcpy(message_buf, our_hello, hello_size);
2153 memcpy(&message_buf[hello_size],
2155 sizeof(struct TransportPingMessage));
2156 #if DEBUG_TRANSPORT_REVALIDATION
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2159 GNUNET_a2s (addr, addrlen),
2162 "HELLO", hello_size,
2163 "PING", sizeof (struct TransportPingMessage));
2165 transmit_to_peer (NULL, peer_address,
2166 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2167 HELLO_VERIFICATION_TIMEOUT,
2169 GNUNET_YES, neighbour);
2170 GNUNET_free(message_buf);
2176 * Send periodic ping messages to a give foreign address.
2178 * cls closure, can be safely cast to ForeignAddressList
2181 * FIXME: Since a _billion_ pongs are sent for every ping,
2182 * maybe this should be a special message type or something
2183 * that gets discarded on the other side instead of initiating
2187 send_periodic_ping (void *cls,
2188 const struct GNUNET_SCHEDULER_TaskContext *tc)
2190 struct PeriodicValidationContext *periodic_validation_context = cls;
2192 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2194 GNUNET_free(periodic_validation_context->transport);
2195 GNUNET_free(periodic_validation_context);
2196 return; /* We have been shutdown, don't do anything! */
2198 rerun_validation(&periodic_validation_context->publicKey,
2199 periodic_validation_context->transport,
2200 periodic_validation_context->foreign_address->expires,
2201 periodic_validation_context->foreign_address->addr,
2202 periodic_validation_context->foreign_address->addrlen);
2203 GNUNET_free(periodic_validation_context->transport);
2204 GNUNET_free(periodic_validation_context);
2209 * Check if the given address is already being validated; if not,
2210 * append the given address to the list of entries that are being be
2211 * validated and initiate validation.
2213 * @param cls closure ('struct CheckHelloValidatedContext *')
2214 * @param tname name of the transport
2215 * @param expiration expiration time
2216 * @param addr the address
2217 * @param addrlen length of the address
2218 * @return GNUNET_OK (always)
2221 run_validation (void *cls,
2223 struct GNUNET_TIME_Absolute expiration,
2224 const void *addr, size_t addrlen)
2226 struct CheckHelloValidatedContext *chvc = cls;
2227 struct GNUNET_PeerIdentity id;
2228 struct TransportPlugin *tp;
2229 struct ValidationEntry *va;
2230 struct NeighbourList *neighbour;
2231 struct ForeignAddressList *peer_address;
2232 struct TransportPingMessage ping;
2233 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2234 struct CheckAddressExistsClosure caec;
2236 uint16_t hello_size;
2239 tp = find_transport (tname);
2242 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2243 GNUNET_ERROR_TYPE_BULK,
2245 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2249 GNUNET_HELLO_get_key (chvc->hello, &pk);
2250 GNUNET_CRYPTO_hash (&pk,
2252 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2255 caec.addrlen = addrlen;
2257 caec.exists = GNUNET_NO;
2258 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2259 &check_address_exists,
2261 if (caec.exists == GNUNET_YES)
2263 /* During validation attempts we will likely trigger the other
2264 peer trying to validate our address which in turn will cause
2265 it to send us its HELLO, so we expect to hit this case rather
2266 frequently. Only print something if we are very verbose. */
2267 #if DEBUG_TRANSPORT > 1
2268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2269 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2270 GNUNET_a2s (addr, addrlen),
2276 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2277 va->transport_name = GNUNET_strdup (tname);
2278 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2280 va->send_time = GNUNET_TIME_absolute_get();
2281 va->addr = (const void*) &va[1];
2282 memcpy (&va[1], addr, addrlen);
2283 va->addrlen = addrlen;
2284 GNUNET_HELLO_get_key (chvc->hello,
2286 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2287 HELLO_VERIFICATION_TIMEOUT,
2288 &timeout_hello_validation,
2290 GNUNET_CONTAINER_multihashmap_put (validation_map,
2293 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2294 neighbour = find_neighbour(&id);
2295 if (neighbour == NULL)
2296 neighbour = setup_new_neighbour(&id);
2297 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2298 GNUNET_assert(peer_address != NULL);
2299 hello_size = GNUNET_HELLO_size(our_hello);
2300 tsize = sizeof(struct TransportPingMessage) + hello_size;
2301 message_buf = GNUNET_malloc(tsize);
2302 ping.challenge = htonl(va->challenge);
2303 ping.header.size = htons(sizeof(struct TransportPingMessage));
2304 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2305 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2306 memcpy(message_buf, our_hello, hello_size);
2307 memcpy(&message_buf[hello_size],
2309 sizeof(struct TransportPingMessage));
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2313 GNUNET_a2s (addr, addrlen),
2316 "HELLO", hello_size,
2317 "PING", sizeof (struct TransportPingMessage));
2319 transmit_to_peer (NULL, peer_address,
2320 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2321 HELLO_VERIFICATION_TIMEOUT,
2323 GNUNET_YES, neighbour);
2324 GNUNET_free(message_buf);
2330 * Add the given address to the list of foreign addresses
2331 * available for the given peer (check for duplicates).
2333 * @param cls the respective 'struct NeighbourList' to update
2334 * @param tname name of the transport
2335 * @param expiration expiration time
2336 * @param addr the address
2337 * @param addrlen length of the address
2338 * @return GNUNET_OK (always)
2341 add_to_foreign_address_list (void *cls,
2343 struct GNUNET_TIME_Absolute expiration,
2344 const void *addr, size_t addrlen)
2346 struct NeighbourList *n = cls;
2347 struct ForeignAddressList *fal;
2351 fal = find_peer_address (n, tname, addr, addrlen);
2355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2356 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2357 GNUNET_a2s (addr, addrlen),
2359 GNUNET_i2s (&n->id),
2362 fal = add_peer_address (n, tname, addr, addrlen);
2367 fal->expires = GNUNET_TIME_absolute_max (expiration,
2369 fal->validated = GNUNET_YES;
2370 if (try == GNUNET_YES)
2371 try_transmission_to_peer (n);
2377 * Check if addresses in validated hello "h" overlap with
2378 * those in "chvc->hello" and validate the rest.
2380 * @param cls closure
2381 * @param peer id of the peer, NULL for last call
2382 * @param h hello message for the peer (can be NULL)
2383 * @param trust amount of trust we have in the peer (not used)
2386 check_hello_validated (void *cls,
2387 const struct GNUNET_PeerIdentity *peer,
2388 const struct GNUNET_HELLO_Message *h,
2391 struct CheckHelloValidatedContext *chvc = cls;
2392 struct GNUNET_HELLO_Message *plain_hello;
2393 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2394 struct GNUNET_PeerIdentity target;
2395 struct NeighbourList *n;
2400 GNUNET_CONTAINER_DLL_remove (chvc_head,
2403 if (GNUNET_NO == chvc->hello_known)
2405 /* notify PEERINFO about the peer now, so that we at least
2406 have the public key if some other component needs it */
2407 GNUNET_HELLO_get_key (chvc->hello, &pk);
2408 GNUNET_CRYPTO_hash (&pk,
2409 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2410 &target.hashPubKey);
2411 plain_hello = GNUNET_HELLO_create (&pk,
2414 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2415 GNUNET_free (plain_hello);
2417 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2420 GNUNET_i2s (&target));
2422 GNUNET_HELLO_iterate_addresses (chvc->hello,
2432 chvc->hello_known = GNUNET_YES;
2433 n = find_neighbour (peer);
2436 GNUNET_HELLO_iterate_addresses (h,
2438 &add_to_foreign_address_list,
2440 try_transmission_to_peer (n);
2442 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2444 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2450 * Process HELLO-message.
2452 * @param plugin transport involved, may be NULL
2453 * @param message the actual message
2454 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2457 process_hello (struct TransportPlugin *plugin,
2458 const struct GNUNET_MessageHeader *message)
2461 struct GNUNET_PeerIdentity target;
2462 const struct GNUNET_HELLO_Message *hello;
2463 struct CheckHelloValidatedContext *chvc;
2464 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2466 hsize = ntohs (message->size);
2467 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2468 (hsize < sizeof (struct GNUNET_MessageHeader)))
2471 return GNUNET_SYSERR;
2473 /* first, check if load is too high */
2474 if (GNUNET_SCHEDULER_get_load (sched,
2475 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2477 /* TODO: call to stats? */
2480 hello = (const struct GNUNET_HELLO_Message *) message;
2481 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2483 GNUNET_break_op (0);
2484 return GNUNET_SYSERR;
2486 GNUNET_CRYPTO_hash (&publicKey,
2487 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2488 &target.hashPubKey);
2489 #if DEBUG_TRANSPORT > 1
2490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2491 "Processing `%s' message for `%4s' of size %u\n",
2493 GNUNET_i2s (&target),
2494 GNUNET_HELLO_size(hello));
2496 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2497 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2498 memcpy (&chvc[1], hello, hsize);
2499 GNUNET_CONTAINER_DLL_insert (chvc_head,
2502 /* finally, check if HELLO was previously validated
2503 (continuation will then schedule actual validation) */
2504 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2508 HELLO_VERIFICATION_TIMEOUT,
2509 &check_hello_validated, chvc);
2515 * The peer specified by the given neighbour has timed-out or a plugin
2516 * has disconnected. We may either need to do nothing (other plugins
2517 * still up), or trigger a full disconnect and clean up. This
2518 * function updates our state and does the necessary notifications.
2519 * Also notifies our clients that the neighbour is now officially
2522 * @param n the neighbour list entry for the peer
2523 * @param check should we just check if all plugins
2524 * disconnected or must we ask all plugins to
2528 disconnect_neighbour (struct NeighbourList *n, int check)
2530 struct ReadyList *rpos;
2531 struct NeighbourList *npos;
2532 struct NeighbourList *nprev;
2533 struct MessageQueue *mq;
2534 struct ForeignAddressList *peer_addresses;
2535 struct ForeignAddressList *peer_pos;
2537 if (GNUNET_YES == check)
2540 while (NULL != rpos)
2542 peer_addresses = rpos->addresses;
2543 while (peer_addresses != NULL)
2545 if (GNUNET_YES == peer_addresses->connected)
2546 return; /* still connected */
2547 peer_addresses = peer_addresses->next;
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2554 "Disconnecting from `%4s'\n",
2555 GNUNET_i2s (&n->id));
2557 /* remove n from neighbours list */
2560 while ((npos != NULL) && (npos != n))
2565 GNUNET_assert (npos != NULL);
2567 neighbours = n->next;
2569 nprev->next = n->next;
2571 /* notify all clients about disconnect */
2572 if (GNUNET_YES == n->received_pong)
2573 notify_clients_disconnect (&n->id);
2575 /* clean up all plugins, cancel connections and pending transmissions */
2576 while (NULL != (rpos = n->plugins))
2578 n->plugins = rpos->next;
2579 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2581 while (rpos->addresses != NULL)
2583 peer_pos = rpos->addresses;
2584 rpos->addresses = peer_pos->next;
2585 GNUNET_free(peer_pos);
2590 /* free all messages on the queue */
2591 while (NULL != (mq = n->messages_head))
2593 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2596 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2598 sizeof(struct GNUNET_PeerIdentity)));
2601 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2603 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2604 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2606 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2608 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2609 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2611 /* finally, free n itself */
2617 * We have received a PING message from someone. Need to send a PONG message
2618 * in response to the peer by any means necessary.
2620 * FIXME: With something like TCP where a connection exists, we may
2621 * want to send it that way. But the current API does not seem to
2622 * allow us to do so (can't tell this to the transport!)
2625 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2626 const struct GNUNET_PeerIdentity *peer,
2627 const char *sender_address,
2628 size_t sender_address_len)
2630 struct TransportPlugin *plugin = cls;
2631 struct TransportPingMessage *ping;
2632 struct TransportPongMessage *pong;
2633 struct NeighbourList *n;
2634 struct ReadyList *rl;
2635 struct ForeignAddressList *fal;
2637 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2639 GNUNET_break_op (0);
2640 return GNUNET_SYSERR;
2642 ping = (struct TransportPingMessage *) message;
2643 if (0 != memcmp (&ping->target,
2644 plugin->env.my_identity,
2645 sizeof (struct GNUNET_PeerIdentity)))
2647 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2648 _("Received `%s' message not destined for me!\n"),
2650 return GNUNET_SYSERR;
2653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2654 "Processing `%s' from `%s'\n",
2656 GNUNET_a2s ((const struct sockaddr *)sender_address,
2657 sender_address_len));
2659 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2660 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2661 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2662 pong->purpose.size =
2663 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2665 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2666 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2667 pong->challenge = ping->challenge;
2668 pong->addrlen = htons(sender_address_len);
2669 memcpy(&pong->signer,
2671 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2672 memcpy (&pong[1], sender_address, sender_address_len);
2673 GNUNET_assert (GNUNET_OK ==
2674 GNUNET_CRYPTO_rsa_sign (my_private_key,
2675 &pong->purpose, &pong->signature));
2677 n = find_neighbour(peer);
2679 n = setup_new_neighbour(peer);
2680 /* broadcast 'PONG' to all available addresses */
2684 fal = rl->addresses;
2687 transmit_to_peer(NULL, fal,
2688 TRANSPORT_PONG_PRIORITY,
2689 HELLO_VERIFICATION_TIMEOUT,
2691 ntohs(pong->header.size),
2704 * Function called by the plugin for each received message.
2705 * Update data volumes, possibly notify plugins about
2706 * reducing the rate at which they read from the socket
2707 * and generally forward to our receive callback.
2709 * @param cls the "struct TransportPlugin *" we gave to the plugin
2710 * @param peer (claimed) identity of the other peer
2711 * @param message the message, NULL if we only care about
2712 * learning about the delay until we should receive again
2713 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2714 * @param sender_address binary address of the sender (if observed)
2715 * @param sender_address_len number of bytes in sender_address
2716 * @return how long the plugin should wait until receiving more data
2717 * (plugins that do not support this, can ignore the return value)
2719 static struct GNUNET_TIME_Relative
2720 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2721 const struct GNUNET_MessageHeader *message,
2722 unsigned int distance, const char *sender_address,
2723 size_t sender_address_len)
2725 struct ReadyList *service_context;
2726 struct TransportPlugin *plugin = cls;
2727 struct TransportClient *cpos;
2728 struct InboundMessage *im;
2729 struct ForeignAddressList *peer_address;
2731 struct NeighbourList *n;
2732 struct GNUNET_TIME_Relative ret;
2734 n = find_neighbour (peer);
2736 n = setup_new_neighbour (peer);
2737 service_context = n->plugins;
2738 while ((service_context != NULL) && (plugin != service_context->plugin))
2739 service_context = service_context->next;
2740 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2741 if (message != NULL)
2743 peer_address = add_peer_address(n,
2746 sender_address_len);
2747 if (peer_address != NULL)
2749 peer_address->distance = distance;
2750 if (peer_address->connected == GNUNET_NO)
2752 peer_address->connected = GNUNET_YES;
2753 peer_address->connect_attempts++;
2755 peer_address->timeout
2757 GNUNET_TIME_relative_to_absolute
2758 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2760 /* update traffic received amount ... */
2761 msize = ntohs (message->size);
2762 n->distance = distance;
2764 GNUNET_TIME_relative_to_absolute
2765 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2766 GNUNET_SCHEDULER_cancel (sched,
2769 GNUNET_SCHEDULER_add_delayed (sched,
2770 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2771 &neighbour_timeout_task, n);
2772 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2774 /* dropping message due to frequent inbound volume violations! */
2775 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2776 GNUNET_ERROR_TYPE_BULK,
2778 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
2779 n->in_tracker.available_bytes_per_s__,
2780 n->quota_violation_count);
2781 return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2783 switch (ntohs (message->type))
2785 case GNUNET_MESSAGE_TYPE_HELLO:
2786 process_hello (plugin, message);
2788 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2789 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2791 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2792 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797 "Received message of type %u from `%4s', sending to all clients.\n",
2798 ntohs (message->type), GNUNET_i2s (peer));
2800 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2802 n->quota_violation_count++;
2804 n->quota_violation_count = 0; /* back within limits */
2805 /* transmit message to all clients */
2806 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2807 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2808 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2809 im->latency = GNUNET_TIME_relative_hton (n->latency);
2811 memcpy (&im[1], message, msize);
2813 while (cpos != NULL)
2815 transmit_to_client (cpos, &im->header, GNUNET_YES);
2821 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
2823 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2824 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
2825 (unsigned long long) n->in_tracker.consumption_since_last_update__,
2826 (unsigned int) n->in_tracker.available_bytes_per_s__,
2827 (unsigned long long) ret.value);
2833 * Handle START-message. This is the first message sent to us
2834 * by any client which causes us to add it to our list.
2836 * @param cls closure (always NULL)
2837 * @param client identification of the client
2838 * @param message the actual message
2841 handle_start (void *cls,
2842 struct GNUNET_SERVER_Client *client,
2843 const struct GNUNET_MessageHeader *message)
2845 struct TransportClient *c;
2846 struct ConnectInfoMessage cim;
2847 struct NeighbourList *n;
2850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851 "Received `%s' request from client\n", "START");
2856 if (c->client == client)
2858 /* client already on our list! */
2860 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2865 c = GNUNET_malloc (sizeof (struct TransportClient));
2869 if (our_hello != NULL)
2872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2873 "Sending our own `%s' to new client\n", "HELLO");
2875 transmit_to_client (c,
2876 (const struct GNUNET_MessageHeader *) our_hello,
2878 /* tell new client about all existing connections */
2879 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2880 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2884 if (GNUNET_YES == n->received_pong)
2887 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2888 cim.distance = htonl (n->distance);
2889 transmit_to_client (c, &cim.header, GNUNET_NO);
2894 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2899 * Handle HELLO-message.
2901 * @param cls closure (always NULL)
2902 * @param client identification of the client
2903 * @param message the actual message
2906 handle_hello (void *cls,
2907 struct GNUNET_SERVER_Client *client,
2908 const struct GNUNET_MessageHeader *message)
2912 ret = process_hello (NULL, message);
2913 GNUNET_SERVER_receive_done (client, ret);
2918 * Handle SEND-message.
2920 * @param cls closure (always NULL)
2921 * @param client identification of the client
2922 * @param message the actual message
2925 handle_send (void *cls,
2926 struct GNUNET_SERVER_Client *client,
2927 const struct GNUNET_MessageHeader *message)
2929 struct TransportClient *tc;
2930 struct NeighbourList *n;
2931 const struct OutboundMessage *obm;
2932 const struct GNUNET_MessageHeader *obmm;
2936 size = ntohs (message->size);
2938 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2941 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2944 obm = (const struct OutboundMessage *) message;
2946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2947 "Received `%s' request from client with target `%4s'\n",
2948 "SEND", GNUNET_i2s (&obm->peer));
2950 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2951 msize = ntohs (obmm->size);
2952 if (size != msize + sizeof (struct OutboundMessage))
2955 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2958 n = find_neighbour (&obm->peer);
2960 n = setup_new_neighbour (&obm->peer);
2962 while ((tc != NULL) && (tc->client != client))
2966 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2967 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2969 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2971 transmit_to_peer (tc, NULL, ntohl (obm->priority),
2972 GNUNET_TIME_relative_ntoh (obm->timeout),
2974 ntohs (obmm->size), GNUNET_NO, n);
2975 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2980 * Handle SET_QUOTA-message.
2982 * @param cls closure (always NULL)
2983 * @param client identification of the client
2984 * @param message the actual message
2987 handle_set_quota (void *cls,
2988 struct GNUNET_SERVER_Client *client,
2989 const struct GNUNET_MessageHeader *message)
2991 const struct QuotaSetMessage *qsm =
2992 (const struct QuotaSetMessage *) message;
2993 struct NeighbourList *n;
2995 n = find_neighbour (&qsm->peer);
2998 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3003 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3005 (unsigned int) ntohl (qsm->quota.value__),
3006 (unsigned int) n->in_tracker.available_bytes_per_s__,
3007 GNUNET_i2s (&qsm->peer));
3009 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3011 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3016 transmit_address_to_client (void *cls, const char *address)
3018 struct GNUNET_SERVER_TransmitContext *tc = cls;
3021 if (NULL == address)
3024 slen = strlen (address) + 1;
3025 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3026 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3027 if (NULL == address)
3028 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3033 * Handle AddressLookup-message.
3035 * @param cls closure (always NULL)
3036 * @param client identification of the client
3037 * @param message the actual message
3040 handle_address_lookup (void *cls,
3041 struct GNUNET_SERVER_Client *client,
3042 const struct GNUNET_MessageHeader *message)
3044 const struct AddressLookupMessage *alum;
3045 struct TransportPlugin *lsPlugin;
3046 const char *nameTransport;
3047 const char *address;
3049 struct GNUNET_SERVER_TransmitContext *tc;
3051 size = ntohs (message->size);
3052 if (size < sizeof (struct AddressLookupMessage))
3054 GNUNET_break_op (0);
3055 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3058 alum = (const struct AddressLookupMessage *) message;
3059 uint32_t addressLen = ntohl (alum->addrlen);
3060 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3062 GNUNET_break_op (0);
3063 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3066 address = (const char *) &alum[1];
3067 nameTransport = (const char *) &address[addressLen];
3069 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3071 GNUNET_break_op (0);
3072 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3075 struct GNUNET_TIME_Absolute timeout =
3076 GNUNET_TIME_absolute_ntoh (alum->timeout);
3077 struct GNUNET_TIME_Relative rtimeout =
3078 GNUNET_TIME_absolute_get_remaining (timeout);
3079 lsPlugin = find_transport (nameTransport);
3080 if (NULL == lsPlugin)
3082 tc = GNUNET_SERVER_transmit_context_create (client);
3083 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3084 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3085 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3088 tc = GNUNET_SERVER_transmit_context_create (client);
3089 lsPlugin->api->address_pretty_printer (cls, nameTransport,
3090 address, addressLen, GNUNET_YES,
3092 &transmit_address_to_client, tc);
3096 * List of handlers for the messages understood by this
3099 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3100 {&handle_start, NULL,
3101 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3102 {&handle_hello, NULL,
3103 GNUNET_MESSAGE_TYPE_HELLO, 0},
3104 {&handle_send, NULL,
3105 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3106 {&handle_set_quota, NULL,
3107 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3108 {&handle_address_lookup, NULL,
3109 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3116 * Setup the environment for this plugin.
3119 create_environment (struct TransportPlugin *plug)
3121 plug->env.cfg = cfg;
3122 plug->env.sched = sched;
3123 plug->env.my_identity = &my_identity;
3124 plug->env.cls = plug;
3125 plug->env.receive = &plugin_env_receive;
3126 plug->env.notify_address = &plugin_env_notify_address;
3127 plug->env.max_connections = max_connect_per_transport;
3132 * Start the specified transport (load the plugin).
3135 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3137 struct TransportPlugin *plug;
3140 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3141 _("Loading `%s' transport plugin\n"), name);
3142 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3143 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3144 create_environment (plug);
3145 plug->short_name = GNUNET_strdup (name);
3146 plug->lib_name = libname;
3147 plug->next = plugins;
3149 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3150 if (plug->api == NULL)
3152 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3153 _("Failed to load transport plugin for `%s'\n"), name);
3154 GNUNET_free (plug->short_name);
3155 plugins = plug->next;
3156 GNUNET_free (libname);
3163 * Called whenever a client is disconnected. Frees our
3164 * resources associated with that client.
3166 * @param cls closure
3167 * @param client identification of the client
3170 client_disconnect_notification (void *cls,
3171 struct GNUNET_SERVER_Client *client)
3173 struct TransportClient *pos;
3174 struct TransportClient *prev;
3175 struct ClientMessageQueueEntry *mqe;
3180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3181 "Client disconnected, cleaning up.\n");
3185 while ((pos != NULL) && (pos->client != client))
3192 while (NULL != (mqe = pos->message_queue_head))
3194 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3195 pos->message_queue_tail,
3197 pos->message_count--;
3201 clients = pos->next;
3203 prev->next = pos->next;
3204 if (GNUNET_YES == pos->tcs_pending)
3209 if (pos->th != NULL)
3211 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3214 GNUNET_break (0 == pos->message_count);
3220 * Iterator to free entries in the validation_map.
3222 * @param cls closure (unused)
3223 * @param key current key code
3224 * @param value value in the hash map (validation to abort)
3225 * @return GNUNET_YES (always)
3228 abort_validation (void *cls,
3229 const GNUNET_HashCode * key,
3232 struct ValidationEntry *va = value;
3234 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3235 GNUNET_free (va->transport_name);
3242 * Function called when the service shuts down. Unloads our plugins
3243 * and cancels pending validations.
3245 * @param cls closure, unused
3246 * @param tc task context (unused)
3249 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3251 struct TransportPlugin *plug;
3252 struct OwnAddressList *al;
3253 struct CheckHelloValidatedContext *chvc;
3255 while (neighbours != NULL)
3256 disconnect_neighbour (neighbours, GNUNET_NO);
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3259 "Transport service is unloading plugins...\n");
3261 while (NULL != (plug = plugins))
3263 plugins = plug->next;
3264 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3265 GNUNET_free (plug->lib_name);
3266 GNUNET_free (plug->short_name);
3267 while (NULL != (al = plug->addresses))
3269 plug->addresses = al->next;
3274 if (my_private_key != NULL)
3275 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3276 GNUNET_free_non_null (our_hello);
3278 /* free 'chvc' data structure */
3279 while (NULL != (chvc = chvc_head))
3281 chvc_head = chvc->next;
3282 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3287 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3290 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3295 * Initiate transport service.
3297 * @param cls closure
3298 * @param s scheduler to use
3299 * @param serv the initialized server
3300 * @param c configuration to use
3304 struct GNUNET_SCHEDULER_Handle *s,
3305 struct GNUNET_SERVER_Handle *serv,
3306 const struct GNUNET_CONFIGURATION_Handle *c)
3311 unsigned long long tneigh;
3316 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3317 /* parse configuration */
3319 GNUNET_CONFIGURATION_get_value_number (c,
3324 GNUNET_CONFIGURATION_get_value_filename (c,
3326 "HOSTKEY", &keyfile)))
3328 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3330 ("Transport service is lacking key configuration settings. Exiting.\n"));
3331 GNUNET_SCHEDULER_shutdown (s);
3334 max_connect_per_transport = (uint32_t) tneigh;
3335 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3336 GNUNET_free (keyfile);
3337 if (my_private_key == NULL)
3339 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3341 ("Transport service could not access hostkey. Exiting.\n"));
3342 GNUNET_SCHEDULER_shutdown (s);
3345 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3346 GNUNET_CRYPTO_hash (&my_public_key,
3347 sizeof (my_public_key), &my_identity.hashPubKey);
3348 /* setup notification */
3350 GNUNET_SERVER_disconnect_notify (server,
3351 &client_disconnect_notification, NULL);
3352 /* load plugins... */
3355 GNUNET_CONFIGURATION_get_value_string (c,
3356 "TRANSPORT", "PLUGINS", &plugs))
3358 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3359 _("Starting transport plugins `%s'\n"), plugs);
3360 pos = strtok (plugs, " ");
3363 start_transport (server, pos);
3365 pos = strtok (NULL, " ");
3367 GNUNET_free (plugs);
3369 GNUNET_SCHEDULER_add_delayed (sched,
3370 GNUNET_TIME_UNIT_FOREVER_REL,
3371 &shutdown_task, NULL);
3376 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3378 /* process client requests */
3379 GNUNET_SERVER_add_handlers (server, handlers);
3384 * The main function for the transport service.
3386 * @param argc number of arguments from the command line
3387 * @param argv command line arguments
3388 * @return 0 ok, 1 on error
3391 main (int argc, char *const *argv)
3393 return (GNUNET_OK ==
3394 GNUNET_SERVICE_run (argc,
3397 GNUNET_SERVICE_OPTION_NONE,
3398 &run, NULL)) ? 0 : 1;
3401 /* end of gnunet-service-transport.c */