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;
822 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
823 * of the given peer that we are currently validating).
825 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
828 * Handle for reporting statistics.
830 static struct GNUNET_STATISTICS_Handle *stats;
834 * The peer specified by the given neighbour has timed-out or a plugin
835 * has disconnected. We may either need to do nothing (other plugins
836 * still up), or trigger a full disconnect and clean up. This
837 * function updates our state and do the necessary notifications.
838 * Also notifies our clients that the neighbour is now officially
841 * @param n the neighbour list entry for the peer
842 * @param check should we just check if all plugins
843 * disconnected or must we ask all plugins to
846 static void disconnect_neighbour (struct NeighbourList *n, int check);
849 * Check the ready list for the given neighbour and if a plugin is
850 * ready for transmission (and if we have a message), do so!
852 * @param neighbour target peer for which to transmit
854 static void try_transmission_to_peer (struct NeighbourList *neighbour);
858 * Find an entry in the neighbour list for a particular peer.
859 * if sender_address is not specified (NULL) then return the
860 * first matching entry. If sender_address is specified, then
861 * make sure that the address and address_len also matches.
863 * FIXME: This description does not fit the function.
865 * @return NULL if not found.
867 static struct NeighbourList *
868 find_neighbour (const struct GNUNET_PeerIdentity *key)
870 struct NeighbourList *head = neighbours;
872 while ((head != NULL) &&
873 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
880 * Find an entry in the transport list for a particular transport.
882 * @return NULL if not found.
884 static struct TransportPlugin *
885 find_transport (const char *short_name)
887 struct TransportPlugin *head = plugins;
888 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
895 * Function called to notify a client about the socket being ready to
896 * queue more data. "buf" will be NULL and "size" zero if the socket
897 * was closed for writing in the meantime.
900 * @param size number of bytes available in buf
901 * @param buf where the callee should write the message
902 * @return number of bytes written to buf
905 transmit_to_client_callback (void *cls, size_t size, void *buf)
907 struct TransportClient *client = cls;
908 struct ClientMessageQueueEntry *q;
911 const struct GNUNET_MessageHeader *msg;
917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
918 "Transmission to client failed, closing connection.\n");
919 /* fatal error with client, free message queue! */
920 while (NULL != (q = client->message_queue_head))
922 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
923 client->message_queue_tail,
927 client->message_count = 0;
932 while (NULL != (q = client->message_queue_head))
934 msg = (const struct GNUNET_MessageHeader *) &q[1];
935 msize = ntohs (msg->size);
936 if (msize + tsize > size)
939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
940 "Transmitting message of type %u to client.\n",
943 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
944 client->message_queue_tail,
946 memcpy (&cbuf[tsize], msg, msize);
949 client->message_count--;
953 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
954 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
956 GNUNET_TIME_UNIT_FOREVER_REL,
957 &transmit_to_client_callback,
959 GNUNET_assert (client->th != NULL);
966 * Send the specified message to the specified client. Since multiple
967 * messages may be pending for the same client at a time, this code
968 * makes sure that no message is lost.
970 * @param client client to transmit the message to
971 * @param msg the message to send
972 * @param may_drop can this message be dropped if the
973 * message queue for this client is getting far too large?
976 transmit_to_client (struct TransportClient *client,
977 const struct GNUNET_MessageHeader *msg, int may_drop)
979 struct ClientMessageQueueEntry *q;
982 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
984 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
986 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
987 client->message_count, MAX_PENDING);
988 /* TODO: call to statistics... */
991 msize = ntohs (msg->size);
992 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
993 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
994 memcpy (&q[1], msg, msize);
995 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
996 client->message_queue_tail,
997 client->message_queue_tail,
999 client->message_count++;
1000 if (client->th == NULL)
1002 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1004 GNUNET_TIME_UNIT_FOREVER_REL,
1005 &transmit_to_client_callback,
1007 GNUNET_assert (client->th != NULL);
1013 * Transmit a 'SEND_OK' notification to the given client for the
1016 * @param client who to notify
1017 * @param n neighbour to notify about
1018 * @param result status code for the transmission request
1021 transmit_send_ok (struct TransportClient *client,
1022 struct NeighbourList *n,
1025 struct SendOkMessage send_ok_msg;
1027 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1028 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1029 send_ok_msg.success = htonl (result);
1030 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1031 send_ok_msg.peer = n->id;
1032 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1037 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1038 * upon "completion" of a send request. This tells the API
1039 * that it is now legal to send another message to the given
1042 * @param cls closure, identifies the entry on the
1043 * message queue that was transmitted and the
1044 * client responsible for queueing the message
1045 * @param target the peer receiving the message
1046 * @param result GNUNET_OK on success, if the transmission
1047 * failed, we should not tell the client to transmit
1051 transmit_send_continuation (void *cls,
1052 const struct GNUNET_PeerIdentity *target,
1055 struct MessageQueue *mq = cls;
1056 struct NeighbourList *n;
1058 n = find_neighbour(&mq->neighbour_id);
1059 GNUNET_assert (n != NULL);
1060 if (mq->specific_address != NULL)
1062 if (result == GNUNET_OK)
1064 mq->specific_address->timeout =
1065 GNUNET_TIME_relative_to_absolute
1066 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1067 mq->specific_address->connected = GNUNET_YES;
1071 mq->specific_address->connected = GNUNET_NO;
1073 if (! mq->internal_msg)
1074 mq->specific_address->in_transmit = GNUNET_NO;
1076 if (mq->client != NULL)
1077 transmit_send_ok (mq->client, n, result);
1079 try_transmission_to_peer (n);
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 GNUNET_STATISTICS_update (stats,
1239 gettext_noop ("# bytes transmitted to other peers"),
1240 mq->message_buf_size,
1242 rl->plugin->api->send (rl->plugin->api->cls,
1245 mq->message_buf_size,
1247 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1248 mq->specific_address->addr,
1249 mq->specific_address->addrlen,
1250 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1251 &transmit_send_continuation, mq);
1256 * Send the specified message to the specified peer.
1258 * @param client source of the transmission request (can be NULL)
1259 * @param peer_address ForeignAddressList where we should send this message
1260 * @param priority how important is the message
1261 * @param timeout how long do we have to transmit?
1262 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1263 * @param message_buf_size total size of all messages in message_buf
1264 * @param is_internal is this an internal message; these are pre-pended and
1265 * also do not count for plugins being "ready" to transmit
1266 * @param neighbour handle to the neighbour for transmission
1269 transmit_to_peer (struct TransportClient *client,
1270 struct ForeignAddressList *peer_address,
1271 unsigned int priority,
1272 struct GNUNET_TIME_Relative timeout,
1273 const char *message_buf,
1274 size_t message_buf_size,
1275 int is_internal, struct NeighbourList *neighbour)
1277 struct MessageQueue *mq;
1282 /* check for duplicate submission */
1283 mq = neighbour->messages_head;
1286 if (mq->client == client)
1288 /* client transmitted to same peer twice
1289 before getting SendOk! */
1297 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1298 mq->specific_address = peer_address;
1299 mq->client = client;
1300 memcpy (&mq[1], message_buf, message_buf_size);
1301 mq->message_buf = (const char*) &mq[1];
1302 mq->message_buf_size = message_buf_size;
1303 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1304 mq->internal_msg = is_internal;
1305 mq->priority = priority;
1306 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1308 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1309 neighbour->messages_tail,
1312 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1313 neighbour->messages_tail,
1314 neighbour->messages_tail,
1316 try_transmission_to_peer (neighbour);
1323 struct GeneratorContext
1325 struct TransportPlugin *plug_pos;
1326 struct OwnAddressList *addr_pos;
1327 struct GNUNET_TIME_Absolute expiration;
1335 address_generator (void *cls, size_t max, void *buf)
1337 struct GeneratorContext *gc = cls;
1340 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1342 gc->plug_pos = gc->plug_pos->next;
1343 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1345 if (NULL == gc->plug_pos)
1350 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1353 gc->addr_pos->addrlen, buf, max);
1354 gc->addr_pos = gc->addr_pos->next;
1360 * Construct our HELLO message from all of the addresses of
1361 * all of the transports.
1366 struct GNUNET_HELLO_Message *hello;
1367 struct TransportClient *cpos;
1368 struct NeighbourList *npos;
1369 struct GeneratorContext gc;
1371 gc.plug_pos = plugins;
1372 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1373 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1374 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1377 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1379 GNUNET_STATISTICS_update (stats,
1380 gettext_noop ("# refreshed my HELLO"),
1384 while (cpos != NULL)
1386 transmit_to_client (cpos,
1387 (const struct GNUNET_MessageHeader *) hello,
1392 GNUNET_free_non_null (our_hello);
1394 our_hello_version++;
1395 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1397 while (npos != NULL)
1400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1401 "Transmitting updated `%s' to neighbour `%4s'\n",
1402 "HELLO", GNUNET_i2s (&npos->id));
1404 GNUNET_STATISTICS_update (stats,
1405 gettext_noop ("# transmitted my HELLO to other peers"),
1408 transmit_to_peer (NULL, NULL, 0,
1409 HELLO_ADDRESS_EXPIRATION,
1410 (const char *) our_hello,
1411 GNUNET_HELLO_size(our_hello),
1419 * Task used to clean up expired addresses for a plugin.
1421 * @param cls closure
1425 expire_address_task (void *cls,
1426 const struct GNUNET_SCHEDULER_TaskContext *tc);
1430 * Update the list of addresses for this plugin,
1431 * expiring those that are past their expiration date.
1433 * @param plugin addresses of which plugin should be recomputed?
1434 * @param fresh set to GNUNET_YES if a new address was added
1435 * and we need to regenerate the HELLO even if nobody
1439 update_addresses (struct TransportPlugin *plugin, int fresh)
1441 struct GNUNET_TIME_Relative min_remaining;
1442 struct GNUNET_TIME_Relative remaining;
1443 struct GNUNET_TIME_Absolute now;
1444 struct OwnAddressList *pos;
1445 struct OwnAddressList *prev;
1446 struct OwnAddressList *next;
1449 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1450 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1451 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1452 now = GNUNET_TIME_absolute_get ();
1453 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1454 expired = GNUNET_NO;
1456 pos = plugin->addresses;
1460 if (pos->expires.value < now.value)
1462 expired = GNUNET_YES;
1464 plugin->addresses = pos->next;
1466 prev->next = pos->next;
1471 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1472 if (remaining.value < min_remaining.value)
1473 min_remaining = remaining;
1479 if (expired || fresh)
1481 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1482 plugin->address_update_task
1483 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1485 &expire_address_task, plugin);
1491 * Task used to clean up expired addresses for a plugin.
1493 * @param cls closure
1497 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1499 struct TransportPlugin *plugin = cls;
1500 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1501 update_addresses (plugin, GNUNET_NO);
1506 * Function that must be called by each plugin to notify the
1507 * transport service about the addresses under which the transport
1508 * provided by the plugin can be reached.
1510 * @param cls closure
1511 * @param name name of the transport that generated the address
1512 * @param addr one of the addresses of the host, NULL for the last address
1513 * the specific address format depends on the transport
1514 * @param addrlen length of the address
1515 * @param expires when should this address automatically expire?
1518 plugin_env_notify_address (void *cls,
1522 struct GNUNET_TIME_Relative expires)
1524 struct TransportPlugin *p = cls;
1525 struct OwnAddressList *al;
1526 struct GNUNET_TIME_Absolute abex;
1528 abex = GNUNET_TIME_relative_to_absolute (expires);
1529 GNUNET_assert (p == find_transport (name));
1534 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1536 if (al->expires.value < abex.value)
1543 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1545 al->next = p->addresses;
1548 al->addrlen = addrlen;
1549 memcpy (&al[1], addr, addrlen);
1550 update_addresses (p, GNUNET_YES);
1555 * Notify all of our clients about a peer connecting.
1558 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1559 struct GNUNET_TIME_Relative latency,
1562 struct ConnectInfoMessage cim;
1563 struct TransportClient *cpos;
1566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567 "Notifying clients about connection from `%s'\n",
1570 GNUNET_STATISTICS_update (stats,
1571 gettext_noop ("# peers connected"),
1574 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1575 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1576 cim.distance = htonl (distance);
1577 cim.latency = GNUNET_TIME_relative_hton (latency);
1578 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1580 while (cpos != NULL)
1582 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1589 * Notify all of our clients about a peer disconnecting.
1592 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1594 struct DisconnectInfoMessage dim;
1595 struct TransportClient *cpos;
1598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599 "Notifying clients about lost connection to `%s'\n",
1602 GNUNET_STATISTICS_update (stats,
1603 gettext_noop ("# peers connected"),
1606 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1607 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1608 dim.reserved = htonl (0);
1609 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1611 while (cpos != NULL)
1613 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1620 * Find a ForeignAddressList entry for the given neighbour
1621 * that matches the given address and transport.
1623 * @param neighbour which peer we care about
1624 * @param tname name of the transport plugin
1625 * @param addr binary address
1626 * @param addrlen length of addr
1627 * @return NULL if no such entry exists
1629 static struct ForeignAddressList *
1630 find_peer_address(struct NeighbourList *neighbour,
1635 struct ReadyList *head;
1636 struct ForeignAddressList *address_head;
1638 head = neighbour->plugins;
1639 while (head != NULL)
1641 if (0 == strcmp (tname, head->plugin->short_name))
1648 address_head = head->addresses;
1649 while ( (address_head != NULL) &&
1650 ( (address_head->addrlen != addrlen) ||
1651 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1652 address_head = address_head->next;
1653 return address_head;
1658 * Get the peer address struct for the given neighbour and
1659 * address. If it doesn't yet exist, create it.
1661 * @param neighbour which peer we care about
1662 * @param tname name of the transport plugin
1663 * @param addr binary address
1664 * @param addrlen length of addr
1665 * @return NULL if we do not have a transport plugin for 'tname'
1667 static struct ForeignAddressList *
1668 add_peer_address(struct NeighbourList *neighbour,
1673 struct ReadyList *head;
1674 struct ForeignAddressList *ret;
1676 ret = find_peer_address (neighbour, tname, addr, addrlen);
1679 head = neighbour->plugins;
1680 while (head != NULL)
1682 if (0 == strcmp (tname, head->plugin->short_name))
1688 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1689 ret->addr = (const char*) &ret[1];
1690 memcpy (&ret[1], addr, addrlen);
1691 ret->addrlen = addrlen;
1692 ret->expires = GNUNET_TIME_relative_to_absolute
1693 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1694 ret->latency = GNUNET_TIME_relative_get_forever();
1696 ret->timeout = GNUNET_TIME_relative_to_absolute
1697 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1698 ret->ready_list = head;
1699 ret->next = head->addresses;
1700 head->addresses = ret;
1706 * Closure for 'add_validated_address'.
1708 struct AddValidatedAddressContext
1711 * Entry that has been validated.
1713 const struct ValidationEntry *ve;
1716 * Flag set after we have added the address so
1717 * that we terminate the iteration next time.
1724 * Callback function used to fill a buffer of max bytes with a list of
1725 * addresses in the format used by HELLOs. Should use
1726 * "GNUNET_HELLO_add_address" as a helper function.
1728 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1729 * @param max maximum number of bytes that can be written to buf
1730 * @param buf where to write the address information
1731 * @return number of bytes written, 0 to signal the
1732 * end of the iteration.
1735 add_validated_address (void *cls,
1736 size_t max, void *buf)
1738 struct AddValidatedAddressContext *avac = cls;
1739 const struct ValidationEntry *ve = avac->ve;
1741 if (GNUNET_YES == avac->done)
1743 avac->done = GNUNET_YES;
1744 return GNUNET_HELLO_add_address (ve->transport_name,
1745 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1753 static void send_periodic_ping(void *cls,
1754 const struct GNUNET_SCHEDULER_TaskContext *tc);
1758 * Iterator over hash map entries. Checks if the given validation
1759 * entry is for the same challenge as what is given in the PONG.
1761 * @param cls the 'struct TransportPongMessage*'
1762 * @param key peer identity
1763 * @param value value in the hash map ('struct ValidationEntry')
1764 * @return GNUNET_YES if we should continue to
1765 * iterate (mismatch), GNUNET_NO if not (entry matched)
1768 check_pending_validation (void *cls,
1769 const GNUNET_HashCode * key,
1772 const struct TransportPongMessage *pong = cls;
1773 struct ValidationEntry *ve = value;
1774 struct AddValidatedAddressContext avac;
1775 unsigned int challenge = ntohl(pong->challenge);
1776 struct GNUNET_HELLO_Message *hello;
1777 struct GNUNET_PeerIdentity target;
1778 struct NeighbourList *n;
1779 struct ForeignAddressList *fal;
1780 struct PeriodicValidationContext *periodic_validation_context;
1782 if (ve->challenge != challenge)
1786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1787 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1789 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1791 ve->transport_name);
1793 GNUNET_STATISTICS_update (stats,
1794 gettext_noop ("# address validation successes"),
1797 /* create the updated HELLO */
1798 GNUNET_CRYPTO_hash (&ve->publicKey,
1799 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1800 &target.hashPubKey);
1801 avac.done = GNUNET_NO;
1803 hello = GNUNET_HELLO_create (&ve->publicKey,
1804 &add_validated_address,
1806 GNUNET_PEERINFO_add_peer (cfg, sched,
1809 GNUNET_free (hello);
1810 n = find_neighbour (&target);
1813 fal = add_peer_address (n,
1817 GNUNET_assert (fal != NULL);
1818 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1819 fal->validated = GNUNET_YES;
1820 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1821 periodic_validation_context = GNUNET_malloc(sizeof(struct PeriodicValidationContext));
1822 periodic_validation_context->foreign_address = fal;
1823 periodic_validation_context->transport = strdup(ve->transport_name);
1824 memcpy(&periodic_validation_context->publicKey,
1826 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1827 /* FIXME: this causes all of the revalidation PINGs for the same HELLO
1828 to be transmitted in bulk, which is not nice; also,
1829 triggering these HERE means that revalidations do NOT happen AT ALL
1830 for HELLOs a previous instance of this process validated (since
1831 there is no "initial" validation PING => no revalidation => BUG! */
1832 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
1833 TRANSPORT_DEFAULT_REVALIDATION,
1834 &send_periodic_ping,
1835 periodic_validation_context);
1836 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1837 n->latency = fal->latency;
1839 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1840 n->distance = fal->distance;
1841 if (GNUNET_NO == n->received_pong)
1843 notify_clients_connect (&target, n->latency, n->distance);
1844 n->received_pong = GNUNET_YES;
1846 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1848 GNUNET_SCHEDULER_cancel (sched,
1850 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1851 try_transmission_to_peer (n);
1855 /* clean up validation entry */
1856 GNUNET_assert (GNUNET_YES ==
1857 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1860 GNUNET_SCHEDULER_cancel (sched,
1862 GNUNET_free (ve->transport_name);
1869 * Function that will be called if we receive a validation
1870 * of an address challenge that we transmitted to another
1871 * peer. Note that the validation should only be considered
1872 * acceptable if the challenge matches AND if the sender
1873 * address is at least a plausible address for this peer
1874 * (otherwise we may be seeing a MiM attack).
1876 * @param cls closure
1877 * @param message the pong message
1878 * @param peer who responded to our challenge
1879 * @param sender_address string describing our sender address (as observed
1880 * by the other peer in binary format)
1881 * @param sender_address_len number of bytes in 'sender_address'
1884 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1885 const struct GNUNET_PeerIdentity *peer,
1886 const char *sender_address,
1887 size_t sender_address_len)
1889 #if DEBUG_TRANSPORT > 1
1890 /* we get tons of these that just get discarded, only log
1891 if we are quite verbose */
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893 "Receiving `%s' message from `%4s'.\n", "PONG",
1896 GNUNET_STATISTICS_update (stats,
1897 gettext_noop ("# PONG messages received"),
1900 if (GNUNET_SYSERR !=
1901 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1903 &check_pending_validation,
1906 /* This is *expected* to happen a lot since we send
1907 PONGs to *all* known addresses of the sender of
1908 the PING, so most likely we get multiple PONGs
1909 per PING, and all but the first PONG will end up
1910 here. So really we should not print anything here
1911 unless we want to be very, very verbose... */
1912 #if DEBUG_TRANSPORT > 2
1913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1914 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1923 /* FIXME: add given address to potential pool of our addresses
1925 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1926 _("Another peer saw us using the address `%s' via `%s'.\n"),
1927 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1928 ntohs(pong->addrlen)),
1929 va->transport_name);
1935 neighbour_timeout_task (void *cls,
1936 const struct GNUNET_SCHEDULER_TaskContext *tc)
1938 struct NeighbourList *n = cls;
1941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1942 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1944 GNUNET_STATISTICS_update (stats,
1945 gettext_noop ("# disconnects due to timeout"),
1948 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1949 disconnect_neighbour (n, GNUNET_NO);
1954 * Create a fresh entry in our neighbour list for the given peer.
1955 * Will try to transmit our current HELLO to the new neighbour. Also
1956 * notifies our clients about the new "connection".
1958 * @param peer the peer for which we create the entry
1959 * @return the new neighbour list entry
1961 static struct NeighbourList *
1962 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1964 struct NeighbourList *n;
1965 struct TransportPlugin *tp;
1966 struct ReadyList *rl;
1968 GNUNET_assert (our_hello != NULL);
1969 n = GNUNET_malloc (sizeof (struct NeighbourList));
1970 n->next = neighbours;
1974 GNUNET_TIME_relative_to_absolute
1975 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1976 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1977 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1978 MAX_BANDWIDTH_CARRY_S);
1982 if (tp->api->send != NULL)
1984 rl = GNUNET_malloc (sizeof (struct ReadyList));
1985 rl->next = n->plugins;
1988 rl->addresses = NULL;
1992 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1994 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1995 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1996 &neighbour_timeout_task, n);
1997 transmit_to_peer (NULL, NULL, 0,
1998 HELLO_ADDRESS_EXPIRATION,
1999 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2006 * Closure for 'check_address_exists'.
2008 struct CheckAddressExistsClosure
2011 * Address to check for.
2016 * Name of the transport.
2026 * Set to GNUNET_YES if the address exists.
2033 * Iterator over hash map entries. Checks if the given
2034 * validation entry is for the same address as what is given
2037 * @param cls the 'struct CheckAddressExistsClosure*'
2038 * @param key current key code (ignored)
2039 * @param value value in the hash map ('struct ValidationEntry')
2040 * @return GNUNET_YES if we should continue to
2041 * iterate (mismatch), GNUNET_NO if not (entry matched)
2044 check_address_exists (void *cls,
2045 const GNUNET_HashCode * key,
2048 struct CheckAddressExistsClosure *caec = cls;
2049 struct ValidationEntry *ve = value;
2050 if ( (0 == strcmp (caec->tname,
2051 ve->transport_name)) &&
2052 (caec->addrlen == ve->addrlen) &&
2053 (0 == memcmp (caec->addr,
2057 caec->exists = GNUNET_YES;
2065 * HELLO validation cleanup task (validation failed).
2067 * @param cls the 'struct ValidationEntry' that failed
2068 * @param tc scheduler context (unused)
2071 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2073 struct ValidationEntry *va = cls;
2074 struct GNUNET_PeerIdentity pid;
2076 GNUNET_STATISTICS_update (stats,
2077 gettext_noop ("# address validation timeouts"),
2080 GNUNET_CRYPTO_hash (&va->publicKey,
2082 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2084 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2087 GNUNET_free (va->transport_name);
2093 * Check if the given address is already being validated; if not,
2094 * append the given address to the list of entries that are being be
2095 * validated and initiate validation.
2097 * @param cls closure ('struct PeriodicValidationContext *')
2098 * @param tname name of the transport
2099 * @param expiration expiration time
2100 * @param addr the address
2101 * @param addrlen length of the address
2102 * @return GNUNET_OK (always)
2105 rerun_validation (void *cls,
2107 struct GNUNET_TIME_Absolute expiration,
2108 const void *addr, size_t addrlen)
2110 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey = cls;
2111 struct GNUNET_PeerIdentity id;
2112 struct TransportPlugin *tp;
2113 struct ValidationEntry *va;
2114 struct NeighbourList *neighbour;
2115 struct ForeignAddressList *peer_address;
2116 struct TransportPingMessage ping;
2117 /*struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;*/
2118 struct CheckAddressExistsClosure caec;
2120 uint16_t hello_size;
2123 tp = find_transport (tname);
2126 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2127 GNUNET_ERROR_TYPE_BULK,
2129 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2134 GNUNET_CRYPTO_hash (publicKey,
2136 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2139 caec.addrlen = addrlen;
2141 caec.exists = GNUNET_NO;
2142 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2143 &check_address_exists,
2145 if (caec.exists == GNUNET_YES)
2147 /* During validation attempts we will likely trigger the other
2148 peer trying to validate our address which in turn will cause
2149 it to send us its HELLO, so we expect to hit this case rather
2150 frequently. Only print something if we are very verbose. */
2151 #if DEBUG_TRANSPORT > 1
2152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2153 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2154 GNUNET_a2s (addr, addrlen),
2160 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2161 va->transport_name = GNUNET_strdup (tname);
2162 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2164 va->send_time = GNUNET_TIME_absolute_get();
2165 va->addr = (const void*) &va[1];
2166 memcpy (&va[1], addr, addrlen);
2167 va->addrlen = addrlen;
2168 memcpy(&va->publicKey, publicKey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2169 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2170 HELLO_VERIFICATION_TIMEOUT,
2171 &timeout_hello_validation,
2173 GNUNET_CONTAINER_multihashmap_put (validation_map,
2176 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2177 neighbour = find_neighbour(&id);
2178 if (neighbour == NULL)
2179 neighbour = setup_new_neighbour(&id);
2180 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2181 GNUNET_assert(peer_address != NULL);
2182 hello_size = GNUNET_HELLO_size(our_hello);
2183 tsize = sizeof(struct TransportPingMessage) + hello_size;
2184 message_buf = GNUNET_malloc(tsize);
2185 ping.challenge = htonl(va->challenge);
2186 ping.header.size = htons(sizeof(struct TransportPingMessage));
2187 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2188 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2189 memcpy(message_buf, our_hello, hello_size);
2190 memcpy(&message_buf[hello_size],
2192 sizeof(struct TransportPingMessage));
2193 #if DEBUG_TRANSPORT_REVALIDATION
2194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2195 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2196 GNUNET_a2s (addr, addrlen),
2199 "HELLO", hello_size,
2200 "PING", sizeof (struct TransportPingMessage));
2202 GNUNET_STATISTICS_update (stats,
2203 gettext_noop ("# PING messages sent"),
2206 transmit_to_peer (NULL, peer_address,
2207 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2208 HELLO_VERIFICATION_TIMEOUT,
2210 GNUNET_YES, neighbour);
2211 GNUNET_free(message_buf);
2217 * Send periodic ping messages to a give foreign address.
2219 * cls closure, can be safely cast to ForeignAddressList
2222 * FIXME: Since a _billion_ pongs are sent for every ping,
2223 * maybe this should be a special message type or something
2224 * that gets discarded on the other side instead of initiating
2228 send_periodic_ping (void *cls,
2229 const struct GNUNET_SCHEDULER_TaskContext *tc)
2231 struct PeriodicValidationContext *periodic_validation_context = cls;
2233 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2235 GNUNET_free(periodic_validation_context->transport);
2236 GNUNET_free(periodic_validation_context);
2237 return; /* We have been shutdown, don't do anything! */
2239 rerun_validation(&periodic_validation_context->publicKey,
2240 periodic_validation_context->transport,
2241 periodic_validation_context->foreign_address->expires,
2242 periodic_validation_context->foreign_address->addr,
2243 periodic_validation_context->foreign_address->addrlen);
2244 GNUNET_free(periodic_validation_context->transport);
2245 GNUNET_free(periodic_validation_context);
2250 * Check if the given address is already being validated; if not,
2251 * append the given address to the list of entries that are being be
2252 * validated and initiate validation.
2254 * @param cls closure ('struct CheckHelloValidatedContext *')
2255 * @param tname name of the transport
2256 * @param expiration expiration time
2257 * @param addr the address
2258 * @param addrlen length of the address
2259 * @return GNUNET_OK (always)
2262 run_validation (void *cls,
2264 struct GNUNET_TIME_Absolute expiration,
2265 const void *addr, size_t addrlen)
2267 struct CheckHelloValidatedContext *chvc = cls;
2268 struct GNUNET_PeerIdentity id;
2269 struct TransportPlugin *tp;
2270 struct ValidationEntry *va;
2271 struct NeighbourList *neighbour;
2272 struct ForeignAddressList *peer_address;
2273 struct TransportPingMessage ping;
2274 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2275 struct CheckAddressExistsClosure caec;
2277 uint16_t hello_size;
2280 tp = find_transport (tname);
2283 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2284 GNUNET_ERROR_TYPE_BULK,
2286 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2290 GNUNET_HELLO_get_key (chvc->hello, &pk);
2291 GNUNET_CRYPTO_hash (&pk,
2293 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2296 caec.addrlen = addrlen;
2298 caec.exists = GNUNET_NO;
2299 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2300 &check_address_exists,
2302 if (caec.exists == GNUNET_YES)
2304 /* During validation attempts we will likely trigger the other
2305 peer trying to validate our address which in turn will cause
2306 it to send us its HELLO, so we expect to hit this case rather
2307 frequently. Only print something if we are very verbose. */
2308 #if DEBUG_TRANSPORT > 1
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2311 GNUNET_a2s (addr, addrlen),
2317 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2318 va->transport_name = GNUNET_strdup (tname);
2319 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2321 va->send_time = GNUNET_TIME_absolute_get();
2322 va->addr = (const void*) &va[1];
2323 memcpy (&va[1], addr, addrlen);
2324 va->addrlen = addrlen;
2325 GNUNET_HELLO_get_key (chvc->hello,
2327 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2328 HELLO_VERIFICATION_TIMEOUT,
2329 &timeout_hello_validation,
2331 GNUNET_CONTAINER_multihashmap_put (validation_map,
2334 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2335 neighbour = find_neighbour(&id);
2336 if (neighbour == NULL)
2337 neighbour = setup_new_neighbour(&id);
2338 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2339 GNUNET_assert(peer_address != NULL);
2340 hello_size = GNUNET_HELLO_size(our_hello);
2341 tsize = sizeof(struct TransportPingMessage) + hello_size;
2342 message_buf = GNUNET_malloc(tsize);
2343 ping.challenge = htonl(va->challenge);
2344 ping.header.size = htons(sizeof(struct TransportPingMessage));
2345 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2346 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2347 memcpy(message_buf, our_hello, hello_size);
2348 memcpy(&message_buf[hello_size],
2350 sizeof(struct TransportPingMessage));
2352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2353 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2354 GNUNET_a2s (addr, addrlen),
2357 "HELLO", hello_size,
2358 "PING", sizeof (struct TransportPingMessage));
2360 transmit_to_peer (NULL, peer_address,
2361 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2362 HELLO_VERIFICATION_TIMEOUT,
2364 GNUNET_YES, neighbour);
2365 GNUNET_free(message_buf);
2371 * Add the given address to the list of foreign addresses
2372 * available for the given peer (check for duplicates).
2374 * @param cls the respective 'struct NeighbourList' to update
2375 * @param tname name of the transport
2376 * @param expiration expiration time
2377 * @param addr the address
2378 * @param addrlen length of the address
2379 * @return GNUNET_OK (always)
2382 add_to_foreign_address_list (void *cls,
2384 struct GNUNET_TIME_Absolute expiration,
2385 const void *addr, size_t addrlen)
2387 struct NeighbourList *n = cls;
2388 struct ForeignAddressList *fal;
2392 fal = find_peer_address (n, tname, addr, addrlen);
2396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2398 GNUNET_a2s (addr, addrlen),
2400 GNUNET_i2s (&n->id),
2403 fal = add_peer_address (n, tname, addr, addrlen);
2408 fal->expires = GNUNET_TIME_absolute_max (expiration,
2410 fal->validated = GNUNET_YES;
2411 if (try == GNUNET_YES)
2412 try_transmission_to_peer (n);
2418 * Check if addresses in validated hello "h" overlap with
2419 * those in "chvc->hello" and validate the rest.
2421 * @param cls closure
2422 * @param peer id of the peer, NULL for last call
2423 * @param h hello message for the peer (can be NULL)
2424 * @param trust amount of trust we have in the peer (not used)
2427 check_hello_validated (void *cls,
2428 const struct GNUNET_PeerIdentity *peer,
2429 const struct GNUNET_HELLO_Message *h,
2432 struct CheckHelloValidatedContext *chvc = cls;
2433 struct GNUNET_HELLO_Message *plain_hello;
2434 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2435 struct GNUNET_PeerIdentity target;
2436 struct NeighbourList *n;
2441 GNUNET_CONTAINER_DLL_remove (chvc_head,
2444 if (GNUNET_NO == chvc->hello_known)
2446 /* notify PEERINFO about the peer now, so that we at least
2447 have the public key if some other component needs it */
2448 GNUNET_HELLO_get_key (chvc->hello, &pk);
2449 GNUNET_CRYPTO_hash (&pk,
2450 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2451 &target.hashPubKey);
2452 plain_hello = GNUNET_HELLO_create (&pk,
2455 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2456 GNUNET_free (plain_hello);
2458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2461 GNUNET_i2s (&target));
2463 GNUNET_HELLO_iterate_addresses (chvc->hello,
2473 chvc->hello_known = GNUNET_YES;
2474 n = find_neighbour (peer);
2477 GNUNET_HELLO_iterate_addresses (h,
2479 &add_to_foreign_address_list,
2481 try_transmission_to_peer (n);
2483 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2485 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2491 * Process HELLO-message.
2493 * @param plugin transport involved, may be NULL
2494 * @param message the actual message
2495 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2498 process_hello (struct TransportPlugin *plugin,
2499 const struct GNUNET_MessageHeader *message)
2502 struct GNUNET_PeerIdentity target;
2503 const struct GNUNET_HELLO_Message *hello;
2504 struct CheckHelloValidatedContext *chvc;
2505 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2507 hsize = ntohs (message->size);
2508 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2509 (hsize < sizeof (struct GNUNET_MessageHeader)))
2512 return GNUNET_SYSERR;
2514 /* first, check if load is too high */
2515 if (GNUNET_SCHEDULER_get_load (sched,
2516 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2518 /* TODO: call to stats? */
2521 hello = (const struct GNUNET_HELLO_Message *) message;
2522 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2524 GNUNET_break_op (0);
2525 return GNUNET_SYSERR;
2527 GNUNET_CRYPTO_hash (&publicKey,
2528 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2529 &target.hashPubKey);
2530 #if DEBUG_TRANSPORT > 1
2531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532 "Processing `%s' message for `%4s' of size %u\n",
2534 GNUNET_i2s (&target),
2535 GNUNET_HELLO_size(hello));
2537 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2538 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2539 memcpy (&chvc[1], hello, hsize);
2540 GNUNET_CONTAINER_DLL_insert (chvc_head,
2543 /* finally, check if HELLO was previously validated
2544 (continuation will then schedule actual validation) */
2545 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2549 HELLO_VERIFICATION_TIMEOUT,
2550 &check_hello_validated, chvc);
2556 * The peer specified by the given neighbour has timed-out or a plugin
2557 * has disconnected. We may either need to do nothing (other plugins
2558 * still up), or trigger a full disconnect and clean up. This
2559 * function updates our state and does the necessary notifications.
2560 * Also notifies our clients that the neighbour is now officially
2563 * @param n the neighbour list entry for the peer
2564 * @param check should we just check if all plugins
2565 * disconnected or must we ask all plugins to
2569 disconnect_neighbour (struct NeighbourList *n, int check)
2571 struct ReadyList *rpos;
2572 struct NeighbourList *npos;
2573 struct NeighbourList *nprev;
2574 struct MessageQueue *mq;
2575 struct ForeignAddressList *peer_addresses;
2576 struct ForeignAddressList *peer_pos;
2578 if (GNUNET_YES == check)
2581 while (NULL != rpos)
2583 peer_addresses = rpos->addresses;
2584 while (peer_addresses != NULL)
2586 if (GNUNET_YES == peer_addresses->connected)
2587 return; /* still connected */
2588 peer_addresses = peer_addresses->next;
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2595 "Disconnecting from `%4s'\n",
2596 GNUNET_i2s (&n->id));
2598 /* remove n from neighbours list */
2601 while ((npos != NULL) && (npos != n))
2606 GNUNET_assert (npos != NULL);
2608 neighbours = n->next;
2610 nprev->next = n->next;
2612 /* notify all clients about disconnect */
2613 if (GNUNET_YES == n->received_pong)
2614 notify_clients_disconnect (&n->id);
2616 /* clean up all plugins, cancel connections and pending transmissions */
2617 while (NULL != (rpos = n->plugins))
2619 n->plugins = rpos->next;
2620 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2622 while (rpos->addresses != NULL)
2624 peer_pos = rpos->addresses;
2625 rpos->addresses = peer_pos->next;
2626 GNUNET_free(peer_pos);
2631 /* free all messages on the queue */
2632 while (NULL != (mq = n->messages_head))
2634 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2637 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2639 sizeof(struct GNUNET_PeerIdentity)));
2642 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2644 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2645 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2647 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2649 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2650 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2652 /* finally, free n itself */
2658 * We have received a PING message from someone. Need to send a PONG message
2659 * in response to the peer by any means necessary.
2661 * FIXME: With something like TCP where a connection exists, we may
2662 * want to send it that way. But the current API does not seem to
2663 * allow us to do so (can't tell this to the transport!)
2666 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2667 const struct GNUNET_PeerIdentity *peer,
2668 const char *sender_address,
2669 size_t sender_address_len)
2671 struct TransportPlugin *plugin = cls;
2672 struct TransportPingMessage *ping;
2673 struct TransportPongMessage *pong;
2674 struct NeighbourList *n;
2675 struct ReadyList *rl;
2676 struct ForeignAddressList *fal;
2678 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2680 GNUNET_break_op (0);
2681 return GNUNET_SYSERR;
2683 ping = (struct TransportPingMessage *) message;
2684 if (0 != memcmp (&ping->target,
2685 plugin->env.my_identity,
2686 sizeof (struct GNUNET_PeerIdentity)))
2688 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2689 _("Received `%s' message not destined for me!\n"),
2691 return GNUNET_SYSERR;
2694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2695 "Processing `%s' from `%s'\n",
2697 GNUNET_a2s ((const struct sockaddr *)sender_address,
2698 sender_address_len));
2700 GNUNET_STATISTICS_update (stats,
2701 gettext_noop ("# PING messages received"),
2704 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2705 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2706 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2707 pong->purpose.size =
2708 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2710 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2711 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2712 pong->challenge = ping->challenge;
2713 pong->addrlen = htons(sender_address_len);
2714 memcpy(&pong->signer,
2716 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2717 memcpy (&pong[1], sender_address, sender_address_len);
2718 GNUNET_assert (GNUNET_OK ==
2719 GNUNET_CRYPTO_rsa_sign (my_private_key,
2720 &pong->purpose, &pong->signature));
2722 n = find_neighbour(peer);
2724 n = setup_new_neighbour(peer);
2725 /* broadcast 'PONG' to all available addresses */
2729 fal = rl->addresses;
2732 transmit_to_peer(NULL, fal,
2733 TRANSPORT_PONG_PRIORITY,
2734 HELLO_VERIFICATION_TIMEOUT,
2736 ntohs(pong->header.size),
2749 * Function called by the plugin for each received message.
2750 * Update data volumes, possibly notify plugins about
2751 * reducing the rate at which they read from the socket
2752 * and generally forward to our receive callback.
2754 * @param cls the "struct TransportPlugin *" we gave to the plugin
2755 * @param peer (claimed) identity of the other peer
2756 * @param message the message, NULL if we only care about
2757 * learning about the delay until we should receive again
2758 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2759 * @param sender_address binary address of the sender (if observed)
2760 * @param sender_address_len number of bytes in sender_address
2761 * @return how long the plugin should wait until receiving more data
2762 * (plugins that do not support this, can ignore the return value)
2764 static struct GNUNET_TIME_Relative
2765 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2766 const struct GNUNET_MessageHeader *message,
2767 unsigned int distance, const char *sender_address,
2768 size_t sender_address_len)
2770 struct ReadyList *service_context;
2771 struct TransportPlugin *plugin = cls;
2772 struct TransportClient *cpos;
2773 struct InboundMessage *im;
2774 struct ForeignAddressList *peer_address;
2776 struct NeighbourList *n;
2777 struct GNUNET_TIME_Relative ret;
2779 n = find_neighbour (peer);
2781 n = setup_new_neighbour (peer);
2782 service_context = n->plugins;
2783 while ((service_context != NULL) && (plugin != service_context->plugin))
2784 service_context = service_context->next;
2785 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2786 if (message != NULL)
2788 peer_address = add_peer_address(n,
2791 sender_address_len);
2792 if (peer_address != NULL)
2794 peer_address->distance = distance;
2795 if (peer_address->connected == GNUNET_NO)
2797 peer_address->connected = GNUNET_YES;
2798 peer_address->connect_attempts++;
2800 peer_address->timeout
2802 GNUNET_TIME_relative_to_absolute
2803 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2805 /* update traffic received amount ... */
2806 msize = ntohs (message->size);
2807 GNUNET_STATISTICS_update (stats,
2808 gettext_noop ("# bytes received from other peers"),
2811 n->distance = distance;
2813 GNUNET_TIME_relative_to_absolute
2814 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2815 GNUNET_SCHEDULER_cancel (sched,
2818 GNUNET_SCHEDULER_add_delayed (sched,
2819 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2820 &neighbour_timeout_task, n);
2821 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2823 /* dropping message due to frequent inbound volume violations! */
2824 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2825 GNUNET_ERROR_TYPE_BULK,
2827 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
2828 n->in_tracker.available_bytes_per_s__,
2829 n->quota_violation_count);
2830 GNUNET_STATISTICS_update (stats,
2831 gettext_noop ("# bandwidth quota violations by other peers"),
2834 return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2836 switch (ntohs (message->type))
2838 case GNUNET_MESSAGE_TYPE_HELLO:
2839 GNUNET_STATISTICS_update (stats,
2840 gettext_noop ("# HELLO messages received from other peers"),
2843 process_hello (plugin, message);
2845 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2846 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2848 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2849 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854 "Received message of type %u from `%4s', sending to all clients.\n",
2855 ntohs (message->type), GNUNET_i2s (peer));
2857 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2859 n->quota_violation_count++;
2861 n->quota_violation_count = 0; /* back within limits */
2862 GNUNET_STATISTICS_update (stats,
2863 gettext_noop ("# payload received from other peers"),
2866 /* transmit message to all clients */
2867 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2868 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2869 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2870 im->latency = GNUNET_TIME_relative_hton (n->latency);
2872 memcpy (&im[1], message, msize);
2874 while (cpos != NULL)
2876 transmit_to_client (cpos, &im->header, GNUNET_YES);
2882 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
2885 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2886 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
2887 (unsigned long long) n->in_tracker.consumption_since_last_update__,
2888 (unsigned int) n->in_tracker.available_bytes_per_s__,
2889 (unsigned long long) ret.value);
2890 GNUNET_STATISTICS_update (stats,
2891 gettext_noop ("# ms throttling suggested"),
2892 (int64_t) ret.value,
2900 * Handle START-message. This is the first message sent to us
2901 * by any client which causes us to add it to our list.
2903 * @param cls closure (always NULL)
2904 * @param client identification of the client
2905 * @param message the actual message
2908 handle_start (void *cls,
2909 struct GNUNET_SERVER_Client *client,
2910 const struct GNUNET_MessageHeader *message)
2912 struct TransportClient *c;
2913 struct ConnectInfoMessage cim;
2914 struct NeighbourList *n;
2917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2918 "Received `%s' request from client\n", "START");
2923 if (c->client == client)
2925 /* client already on our list! */
2927 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2932 c = GNUNET_malloc (sizeof (struct TransportClient));
2936 if (our_hello != NULL)
2939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2940 "Sending our own `%s' to new client\n", "HELLO");
2942 transmit_to_client (c,
2943 (const struct GNUNET_MessageHeader *) our_hello,
2945 /* tell new client about all existing connections */
2946 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2947 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2951 if (GNUNET_YES == n->received_pong)
2954 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2955 cim.distance = htonl (n->distance);
2956 transmit_to_client (c, &cim.header, GNUNET_NO);
2961 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2966 * Handle HELLO-message.
2968 * @param cls closure (always NULL)
2969 * @param client identification of the client
2970 * @param message the actual message
2973 handle_hello (void *cls,
2974 struct GNUNET_SERVER_Client *client,
2975 const struct GNUNET_MessageHeader *message)
2979 ret = process_hello (NULL, message);
2980 GNUNET_SERVER_receive_done (client, ret);
2985 * Handle SEND-message.
2987 * @param cls closure (always NULL)
2988 * @param client identification of the client
2989 * @param message the actual message
2992 handle_send (void *cls,
2993 struct GNUNET_SERVER_Client *client,
2994 const struct GNUNET_MessageHeader *message)
2996 struct TransportClient *tc;
2997 struct NeighbourList *n;
2998 const struct OutboundMessage *obm;
2999 const struct GNUNET_MessageHeader *obmm;
3003 size = ntohs (message->size);
3005 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3008 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3011 GNUNET_STATISTICS_update (stats,
3012 gettext_noop ("# payload received for other peers"),
3015 obm = (const struct OutboundMessage *) message;
3017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3018 "Received `%s' request from client with target `%4s'\n",
3019 "SEND", GNUNET_i2s (&obm->peer));
3021 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3022 msize = ntohs (obmm->size);
3023 if (size != msize + sizeof (struct OutboundMessage))
3026 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3029 n = find_neighbour (&obm->peer);
3031 n = setup_new_neighbour (&obm->peer);
3033 while ((tc != NULL) && (tc->client != client))
3037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3040 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3042 transmit_to_peer (tc, NULL, ntohl (obm->priority),
3043 GNUNET_TIME_relative_ntoh (obm->timeout),
3045 ntohs (obmm->size), GNUNET_NO, n);
3046 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3051 * Handle SET_QUOTA-message.
3053 * @param cls closure (always NULL)
3054 * @param client identification of the client
3055 * @param message the actual message
3058 handle_set_quota (void *cls,
3059 struct GNUNET_SERVER_Client *client,
3060 const struct GNUNET_MessageHeader *message)
3062 const struct QuotaSetMessage *qsm =
3063 (const struct QuotaSetMessage *) message;
3064 struct NeighbourList *n;
3066 GNUNET_STATISTICS_update (stats,
3067 gettext_noop ("# SET QUOTA messages received"),
3070 n = find_neighbour (&qsm->peer);
3073 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3074 GNUNET_STATISTICS_update (stats,
3075 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3084 (unsigned int) ntohl (qsm->quota.value__),
3085 (unsigned int) n->in_tracker.available_bytes_per_s__,
3086 GNUNET_i2s (&qsm->peer));
3088 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3090 if (0 == ntohl (qsm->quota.value__))
3091 disconnect_neighbour (n, GNUNET_NO);
3092 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3097 transmit_address_to_client (void *cls, const char *address)
3099 struct GNUNET_SERVER_TransmitContext *tc = cls;
3102 if (NULL == address)
3105 slen = strlen (address) + 1;
3106 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3107 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3108 if (NULL == address)
3109 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3114 * Handle AddressLookup-message.
3116 * @param cls closure (always NULL)
3117 * @param client identification of the client
3118 * @param message the actual message
3121 handle_address_lookup (void *cls,
3122 struct GNUNET_SERVER_Client *client,
3123 const struct GNUNET_MessageHeader *message)
3125 const struct AddressLookupMessage *alum;
3126 struct TransportPlugin *lsPlugin;
3127 const char *nameTransport;
3128 const char *address;
3130 struct GNUNET_SERVER_TransmitContext *tc;
3132 size = ntohs (message->size);
3133 if (size < sizeof (struct AddressLookupMessage))
3135 GNUNET_break_op (0);
3136 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3139 alum = (const struct AddressLookupMessage *) message;
3140 uint32_t addressLen = ntohl (alum->addrlen);
3141 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3143 GNUNET_break_op (0);
3144 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3147 address = (const char *) &alum[1];
3148 nameTransport = (const char *) &address[addressLen];
3150 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3152 GNUNET_break_op (0);
3153 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3156 struct GNUNET_TIME_Absolute timeout =
3157 GNUNET_TIME_absolute_ntoh (alum->timeout);
3158 struct GNUNET_TIME_Relative rtimeout =
3159 GNUNET_TIME_absolute_get_remaining (timeout);
3160 lsPlugin = find_transport (nameTransport);
3161 if (NULL == lsPlugin)
3163 tc = GNUNET_SERVER_transmit_context_create (client);
3164 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3165 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3166 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3169 tc = GNUNET_SERVER_transmit_context_create (client);
3170 lsPlugin->api->address_pretty_printer (cls, nameTransport,
3171 address, addressLen, GNUNET_YES,
3173 &transmit_address_to_client, tc);
3177 * List of handlers for the messages understood by this
3180 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3181 {&handle_start, NULL,
3182 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3183 {&handle_hello, NULL,
3184 GNUNET_MESSAGE_TYPE_HELLO, 0},
3185 {&handle_send, NULL,
3186 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3187 {&handle_set_quota, NULL,
3188 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3189 {&handle_address_lookup, NULL,
3190 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3197 * Setup the environment for this plugin.
3200 create_environment (struct TransportPlugin *plug)
3202 plug->env.cfg = cfg;
3203 plug->env.sched = sched;
3204 plug->env.my_identity = &my_identity;
3205 plug->env.cls = plug;
3206 plug->env.receive = &plugin_env_receive;
3207 plug->env.notify_address = &plugin_env_notify_address;
3208 plug->env.max_connections = max_connect_per_transport;
3209 plug->env.stats = stats;
3214 * Start the specified transport (load the plugin).
3217 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3219 struct TransportPlugin *plug;
3222 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3223 _("Loading `%s' transport plugin\n"), name);
3224 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3225 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3226 create_environment (plug);
3227 plug->short_name = GNUNET_strdup (name);
3228 plug->lib_name = libname;
3229 plug->next = plugins;
3231 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3232 if (plug->api == NULL)
3234 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3235 _("Failed to load transport plugin for `%s'\n"), name);
3236 GNUNET_free (plug->short_name);
3237 plugins = plug->next;
3238 GNUNET_free (libname);
3245 * Called whenever a client is disconnected. Frees our
3246 * resources associated with that client.
3248 * @param cls closure
3249 * @param client identification of the client
3252 client_disconnect_notification (void *cls,
3253 struct GNUNET_SERVER_Client *client)
3255 struct TransportClient *pos;
3256 struct TransportClient *prev;
3257 struct ClientMessageQueueEntry *mqe;
3262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3263 "Client disconnected, cleaning up.\n");
3267 while ((pos != NULL) && (pos->client != client))
3274 while (NULL != (mqe = pos->message_queue_head))
3276 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3277 pos->message_queue_tail,
3279 pos->message_count--;
3283 clients = pos->next;
3285 prev->next = pos->next;
3286 if (GNUNET_YES == pos->tcs_pending)
3291 if (pos->th != NULL)
3293 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3296 GNUNET_break (0 == pos->message_count);
3302 * Iterator to free entries in the validation_map.
3304 * @param cls closure (unused)
3305 * @param key current key code
3306 * @param value value in the hash map (validation to abort)
3307 * @return GNUNET_YES (always)
3310 abort_validation (void *cls,
3311 const GNUNET_HashCode * key,
3314 struct ValidationEntry *va = value;
3316 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3317 GNUNET_free (va->transport_name);
3324 * Function called when the service shuts down. Unloads our plugins
3325 * and cancels pending validations.
3327 * @param cls closure, unused
3328 * @param tc task context (unused)
3331 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3333 struct TransportPlugin *plug;
3334 struct OwnAddressList *al;
3335 struct CheckHelloValidatedContext *chvc;
3337 while (neighbours != NULL)
3338 disconnect_neighbour (neighbours, GNUNET_NO);
3340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3341 "Transport service is unloading plugins...\n");
3343 while (NULL != (plug = plugins))
3345 plugins = plug->next;
3346 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3347 GNUNET_free (plug->lib_name);
3348 GNUNET_free (plug->short_name);
3349 while (NULL != (al = plug->addresses))
3351 plug->addresses = al->next;
3356 if (my_private_key != NULL)
3357 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3358 GNUNET_free_non_null (our_hello);
3360 /* free 'chvc' data structure */
3361 while (NULL != (chvc = chvc_head))
3363 chvc_head = chvc->next;
3364 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3369 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3372 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3373 validation_map = NULL;
3376 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3383 * Initiate transport service.
3385 * @param cls closure
3386 * @param s scheduler to use
3387 * @param serv the initialized server
3388 * @param c configuration to use
3392 struct GNUNET_SCHEDULER_Handle *s,
3393 struct GNUNET_SERVER_Handle *serv,
3394 const struct GNUNET_CONFIGURATION_Handle *c)
3399 unsigned long long tneigh;
3404 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3405 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3406 /* parse configuration */
3408 GNUNET_CONFIGURATION_get_value_number (c,
3413 GNUNET_CONFIGURATION_get_value_filename (c,
3415 "HOSTKEY", &keyfile)))
3417 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3419 ("Transport service is lacking key configuration settings. Exiting.\n"));
3420 GNUNET_SCHEDULER_shutdown (s);
3423 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3426 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3427 validation_map = NULL;
3430 max_connect_per_transport = (uint32_t) tneigh;
3431 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3432 GNUNET_free (keyfile);
3433 if (my_private_key == NULL)
3435 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3437 ("Transport service could not access hostkey. Exiting.\n"));
3438 GNUNET_SCHEDULER_shutdown (s);
3441 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3444 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3445 validation_map = NULL;
3448 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3449 GNUNET_CRYPTO_hash (&my_public_key,
3450 sizeof (my_public_key), &my_identity.hashPubKey);
3451 /* setup notification */
3453 GNUNET_SERVER_disconnect_notify (server,
3454 &client_disconnect_notification, NULL);
3455 /* load plugins... */
3458 GNUNET_CONFIGURATION_get_value_string (c,
3459 "TRANSPORT", "PLUGINS", &plugs))
3461 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3462 _("Starting transport plugins `%s'\n"), plugs);
3463 pos = strtok (plugs, " ");
3466 start_transport (server, pos);
3468 pos = strtok (NULL, " ");
3470 GNUNET_free (plugs);
3472 GNUNET_SCHEDULER_add_delayed (sched,
3473 GNUNET_TIME_UNIT_FOREVER_REL,
3474 &shutdown_task, NULL);
3479 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3481 /* process client requests */
3482 GNUNET_SERVER_add_handlers (server, handlers);
3487 * The main function for the transport service.
3489 * @param argc number of arguments from the command line
3490 * @param argv command line arguments
3491 * @return 0 ok, 1 on error
3494 main (int argc, char *const *argv)
3496 return (GNUNET_OK ==
3497 GNUNET_SERVICE_run (argc,
3500 GNUNET_SERVICE_OPTION_NONE,
3501 &run, NULL)) ? 0 : 1;
3504 /* end of gnunet-service-transport.c */