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 * Priority to use for PONG messages.
97 #define TRANSPORT_PONG_PRIORITY 4
100 * How often do we re-add (cheaper) plugins to our list of plugins
101 * to try for a given connected peer?
103 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
106 * After how long do we expire an address in a HELLO that we just
107 * validated? This value is also used for our own addresses when we
110 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
114 * How long before an existing address expires should we again try to
115 * validate it? Must be (significantly) smaller than
116 * HELLO_ADDRESS_EXPIRATION.
118 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
121 * Maximum frequency for re-evaluating latencies for all transport addresses.
123 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
126 * Maximum frequency for re-evaluating latencies for connected addresses.
128 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 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 * Session (or NULL if no valid session currently exists or if the
170 * plugin does not use sessions).
172 struct Session *session;
175 * What was the last latency observed for this address, plugin and peer?
177 struct GNUNET_TIME_Relative latency;
180 * If we did not successfully transmit a message to the given peer
181 * via this connection during the specified time, we should consider
182 * the connection to be dead. This is used in the case that a TCP
183 * transport simply stalls writing to the stream but does not
184 * formerly get a signal that the other peer died.
186 struct GNUNET_TIME_Absolute timeout;
189 * How often have we tried to connect using this plugin? Used to
190 * discriminate against addresses that do not work well.
191 * FIXME: not yet used, but should be!
193 unsigned int connect_attempts;
196 * DV distance to this peer (1 if no DV is used).
197 * FIXME: need to set this from transport plugins!
202 * Have we ever estimated the latency of this address? Used to
203 * ensure that the first time we add an address, we immediately
209 * Are we currently connected via this address? The first time we
210 * successfully transmit or receive data to a peer via a particular
211 * address, we set this to GNUNET_YES. If we later get an error
212 * (disconnect notification, transmission failure, timeout), we set
213 * it back to GNUNET_NO.
218 * Is this plugin currently busy transmitting to the specific target?
219 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
220 * messages do not count as 'in transmit'.
225 * Has this address been validated yet?
233 * Entry in linked list of network addresses for ourselves.
235 struct OwnAddressList
238 * This is a linked list.
240 struct OwnAddressList *next;
243 * The address, actually a pointer to the end
244 * of this struct. Do not free!
249 * How long until we auto-expire this address (unless it is
250 * re-confirmed by the transport)?
252 struct GNUNET_TIME_Absolute expires;
263 * Entry in linked list of all of our plugins.
265 struct TransportPlugin
269 * This is a linked list.
271 struct TransportPlugin *next;
274 * API of the transport as returned by the plugin's
275 * initialization function.
277 struct GNUNET_TRANSPORT_PluginFunctions *api;
280 * Short name for the plugin (i.e. "tcp").
285 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
290 * List of our known addresses for this transport.
292 struct OwnAddressList *addresses;
295 * Environment this transport service is using
298 struct GNUNET_TRANSPORT_PluginEnvironment env;
301 * ID of task that is used to clean up expired addresses.
303 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
306 * Set to GNUNET_YES if we need to scrap the existing list of
307 * "addresses" and start fresh when we receive the next address
308 * update from a transport. Set to GNUNET_NO if we should just add
309 * the new address to the list and wait for the commit call.
315 struct NeighbourList;
318 * For each neighbour we keep a list of messages
319 * that we still want to transmit to the neighbour.
325 * This is a doubly linked list.
327 struct MessageQueue *next;
330 * This is a doubly linked list.
332 struct MessageQueue *prev;
335 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
336 * stuck together in memory. Allocated at the end of this struct.
338 const char *message_buf;
341 * Size of the message buf
343 size_t message_buf_size;
346 * Client responsible for queueing the message;
347 * used to check that a client has no two messages
348 * pending for the same target. Can be NULL.
350 struct TransportClient *client;
353 * Using which specific address should we send this message?
355 struct ForeignAddressList *specific_address;
358 * Peer ID of the Neighbour this entry belongs to.
360 struct GNUNET_PeerIdentity neighbour_id;
363 * Plugin that we used for the transmission.
364 * NULL until we scheduled a transmission.
366 struct TransportPlugin *plugin;
369 * At what time should we fail?
371 struct GNUNET_TIME_Absolute timeout;
374 * Internal message of the transport system that should not be
375 * included in the usual SEND-SEND_OK transmission confirmation
376 * traffic management scheme. Typically, "internal_msg" will
377 * be set whenever "client" is NULL (but it is not strictly
383 * How important is the message?
385 unsigned int priority;
391 * For a given Neighbour, which plugins are available
392 * to talk to this peer and what are their costs?
397 * This is a linked list.
399 struct ReadyList *next;
402 * Which of our transport plugins does this entry
405 struct TransportPlugin *plugin;
408 * Transport addresses, latency, and readiness for
409 * this particular plugin.
411 struct ForeignAddressList *addresses;
414 * To which neighbour does this ready list belong to?
416 struct NeighbourList *neighbour;
422 * Entry in linked list of all of our current neighbours.
428 * This is a linked list.
430 struct NeighbourList *next;
433 * Which of our transports is connected to this peer
434 * and what is their status?
436 struct ReadyList *plugins;
439 * Head of list of messages we would like to send to this peer;
440 * must contain at most one message per client.
442 struct MessageQueue *messages_head;
445 * Tail of list of messages we would like to send to this peer; must
446 * contain at most one message per client.
448 struct MessageQueue *messages_tail;
451 * Buffer for at most one payload message used when we receive
452 * payload data before our PING-PONG has succeeded. We then
453 * store such messages in this intermediary buffer until the
454 * connection is fully up.
456 struct GNUNET_MessageHeader *pre_connect_message_buffer;
459 * Context for peerinfo iteration.
460 * NULL after we are done processing peerinfo's information.
462 struct GNUNET_PEERINFO_IteratorContext *piter;
465 * Public key for this peer. Valid only if the respective flag is set below.
467 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
470 * Identity of this neighbour.
472 struct GNUNET_PeerIdentity id;
475 * ID of task scheduled to run when this peer is about to
476 * time out (will free resources associated with the peer).
478 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
481 * ID of task scheduled to run when we should retry transmitting
482 * the head of the message queue. Actually triggered when the
483 * transmission is timing out (we trigger instantly when we have
484 * a chance of success).
486 GNUNET_SCHEDULER_TaskIdentifier retry_task;
489 * How long until we should consider this peer dead
490 * (if we don't receive another message in the
493 struct GNUNET_TIME_Absolute peer_timeout;
496 * Tracker for inbound bandwidth.
498 struct GNUNET_BANDWIDTH_Tracker in_tracker;
501 * The latency we have seen for this particular address for
502 * this particular peer. This latency may have been calculated
503 * over multiple transports. This value reflects how long it took
504 * us to receive a response when SENDING via this particular
505 * transport/neighbour/address combination!
507 * FIXME: we need to periodically send PINGs to update this
508 * latency (at least more often than the current "huge" (11h?)
511 struct GNUNET_TIME_Relative latency;
514 * How often has the other peer (recently) violated the
515 * inbound traffic limit? Incremented by 10 per violation,
516 * decremented by 1 per non-violation (for each
519 unsigned int quota_violation_count;
522 * DV distance to this peer (1 if no DV is used).
527 * Have we seen an PONG from this neighbour in the past (and
528 * not had a disconnect since)?
533 * Do we have a valid public key for this neighbour?
535 int public_key_valid;
540 * Message used to ask a peer to validate receipt (to check an address
543 struct TransportPingMessage
547 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
549 struct GNUNET_MessageHeader header;
552 * Random challenge number (in network byte order).
554 uint32_t challenge GNUNET_PACKED;
557 * Who is the intended recipient?
559 struct GNUNET_PeerIdentity target;
565 * Message used to validate a HELLO. The challenge is included in the
566 * confirmation to make matching of replies to requests possible. The
567 * signature signs the original challenge number, our public key, the
568 * sender's address (so that the sender can check that the address we
569 * saw is plausible for him and possibly detect a MiM attack) and a
570 * timestamp (to limit replay).<p>
572 * This message is followed by the address of the
573 * client that we are observing (which is part of what
576 struct TransportPongMessage
580 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
582 struct GNUNET_MessageHeader header;
585 * For padding, always zero.
587 uint32_t reserved GNUNET_PACKED;
592 struct GNUNET_CRYPTO_RsaSignature signature;
595 * What are we signing and why?
597 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
600 * Random challenge number (in network byte order).
602 uint32_t challenge GNUNET_PACKED;
605 * Who signed this message?
607 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
610 * Size of address appended to this message
618 * Linked list of messages to be transmitted to the client. Each
619 * entry is followed by the actual message.
621 struct ClientMessageQueueEntry
624 * This is a doubly-linked list.
626 struct ClientMessageQueueEntry *next;
629 * This is a doubly-linked list.
631 struct ClientMessageQueueEntry *prev;
636 * Client connected to the transport service.
638 struct TransportClient
642 * This is a linked list.
644 struct TransportClient *next;
647 * Handle to the client.
649 struct GNUNET_SERVER_Client *client;
652 * Linked list of messages yet to be transmitted to
655 struct ClientMessageQueueEntry *message_queue_head;
658 * Tail of linked list of messages yet to be transmitted to the
661 struct ClientMessageQueueEntry *message_queue_tail;
664 * Current transmit request handle.
666 struct GNUNET_CONNECTION_TransmitHandle *th;
669 * Is a call to "transmit_send_continuation" pending? If so, we
670 * must not free this struct (even if the corresponding client
671 * disconnects) and instead only remove it from the linked list and
672 * set the "client" field to NULL.
677 * Length of the list of messages pending for this client.
679 unsigned int message_count;
685 * Entry in map of all HELLOs awaiting validation.
687 struct ValidationEntry
691 * The address, actually a pointer to the end
692 * of this struct. Do not free!
697 * Name of the transport.
699 char *transport_name;
702 * The public key of the peer.
704 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
707 * ID of task that will clean up this entry if we don't succeed
708 * with the validation first.
710 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
713 * At what time did we send this validation?
715 struct GNUNET_TIME_Absolute send_time;
718 * Session being validated (or NULL for none).
720 struct Session *session;
728 * Challenge number we used.
736 * Context of currently active requests to peerinfo
737 * for validation of HELLOs.
739 struct CheckHelloValidatedContext
743 * This is a doubly-linked list.
745 struct CheckHelloValidatedContext *next;
748 * This is a doubly-linked list.
750 struct CheckHelloValidatedContext *prev;
753 * Hello that we are validating.
755 const struct GNUNET_HELLO_Message *hello;
758 * Context for peerinfo iteration.
759 * NULL after we are done processing peerinfo's information.
761 struct GNUNET_PEERINFO_IteratorContext *piter;
764 * Was a HELLO known for this peer to peerinfo?
774 static struct GNUNET_HELLO_Message *our_hello;
777 * "version" of "our_hello". Used to see if a given neighbour has
778 * already been sent the latest version of our HELLO message.
780 static unsigned int our_hello_version;
785 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
790 static struct GNUNET_PeerIdentity my_identity;
795 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
800 struct GNUNET_SCHEDULER_Handle *sched;
805 const struct GNUNET_CONFIGURATION_Handle *cfg;
808 * Linked list of all clients to this service.
810 static struct TransportClient *clients;
813 * All loaded plugins.
815 static struct TransportPlugin *plugins;
820 static struct GNUNET_SERVER_Handle *server;
823 * All known neighbours and their HELLOs.
825 static struct NeighbourList *neighbours;
828 * Number of neighbours we'd like to have.
830 static uint32_t max_connect_per_transport;
833 * Head of linked list.
835 static struct CheckHelloValidatedContext *chvc_head;
838 * Tail of linked list.
840 static struct CheckHelloValidatedContext *chvc_tail;
843 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
844 * of the given peer that we are currently validating).
846 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
849 * Handle for reporting statistics.
851 static struct GNUNET_STATISTICS_Handle *stats;
855 * The peer specified by the given neighbour has timed-out or a plugin
856 * has disconnected. We may either need to do nothing (other plugins
857 * still up), or trigger a full disconnect and clean up. This
858 * function updates our state and do the necessary notifications.
859 * Also notifies our clients that the neighbour is now officially
862 * @param n the neighbour list entry for the peer
863 * @param check should we just check if all plugins
864 * disconnected or must we ask all plugins to
867 static void disconnect_neighbour (struct NeighbourList *n, int check);
870 * Check the ready list for the given neighbour and if a plugin is
871 * ready for transmission (and if we have a message), do so!
873 * @param neighbour target peer for which to transmit
875 static void try_transmission_to_peer (struct NeighbourList *neighbour);
879 * Find an entry in the neighbour list for a particular peer.
881 * @return NULL if not found.
883 static struct NeighbourList *
884 find_neighbour (const struct GNUNET_PeerIdentity *key)
886 struct NeighbourList *head = neighbours;
888 while ((head != NULL) &&
889 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
896 * Find an entry in the transport list for a particular transport.
898 * @return NULL if not found.
900 static struct TransportPlugin *
901 find_transport (const char *short_name)
903 struct TransportPlugin *head = plugins;
904 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
911 * Function called to notify a client about the socket being ready to
912 * queue more data. "buf" will be NULL and "size" zero if the socket
913 * was closed for writing in the meantime.
916 * @param size number of bytes available in buf
917 * @param buf where the callee should write the message
918 * @return number of bytes written to buf
921 transmit_to_client_callback (void *cls, size_t size, void *buf)
923 struct TransportClient *client = cls;
924 struct ClientMessageQueueEntry *q;
927 const struct GNUNET_MessageHeader *msg;
933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934 "Transmission to client failed, closing connection.\n");
935 /* fatal error with client, free message queue! */
936 while (NULL != (q = client->message_queue_head))
938 GNUNET_STATISTICS_update (stats,
939 gettext_noop ("# bytes discarded (could not transmit to client)"),
940 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
942 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
943 client->message_queue_tail,
947 client->message_count = 0;
952 while (NULL != (q = client->message_queue_head))
954 msg = (const struct GNUNET_MessageHeader *) &q[1];
955 msize = ntohs (msg->size);
956 if (msize + tsize > size)
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960 "Transmitting message of type %u to client.\n",
963 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
964 client->message_queue_tail,
966 memcpy (&cbuf[tsize], msg, msize);
969 client->message_count--;
973 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
974 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
976 GNUNET_TIME_UNIT_FOREVER_REL,
977 &transmit_to_client_callback,
979 GNUNET_assert (client->th != NULL);
986 * Mark the given FAL entry as 'connected' (and hence preferred for
987 * sending); also mark all others for the same peer as 'not connected'
988 * (since only one can be preferred).
990 * @param fal address to set to 'connected'
993 mark_address_connected (struct ForeignAddressList *fal)
995 struct ForeignAddressList *pos;
998 GNUNET_assert (GNUNET_YES == fal->validated);
999 if (fal->connected == GNUNET_YES)
1000 return; /* nothing to do */
1002 pos = fal->ready_list->addresses;
1005 if (GNUNET_YES == pos->connected)
1007 GNUNET_break (cnt == GNUNET_YES);
1009 pos->connected = GNUNET_NO;
1013 fal->connected = GNUNET_YES;
1014 if (GNUNET_YES == cnt)
1016 GNUNET_STATISTICS_update (stats,
1017 gettext_noop ("# connected addresses"),
1025 * Send the specified message to the specified client. Since multiple
1026 * messages may be pending for the same client at a time, this code
1027 * makes sure that no message is lost.
1029 * @param client client to transmit the message to
1030 * @param msg the message to send
1031 * @param may_drop can this message be dropped if the
1032 * message queue for this client is getting far too large?
1035 transmit_to_client (struct TransportClient *client,
1036 const struct GNUNET_MessageHeader *msg, int may_drop)
1038 struct ClientMessageQueueEntry *q;
1041 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1043 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1045 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1046 client->message_count, MAX_PENDING);
1047 /* TODO: call to statistics... */
1050 msize = ntohs (msg->size);
1051 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1052 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1053 memcpy (&q[1], msg, msize);
1054 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1055 client->message_queue_tail,
1056 client->message_queue_tail,
1058 client->message_count++;
1059 if (client->th == NULL)
1061 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1063 GNUNET_TIME_UNIT_FOREVER_REL,
1064 &transmit_to_client_callback,
1066 GNUNET_assert (client->th != NULL);
1072 * Transmit a 'SEND_OK' notification to the given client for the
1075 * @param client who to notify
1076 * @param n neighbour to notify about
1077 * @param result status code for the transmission request
1080 transmit_send_ok (struct TransportClient *client,
1081 struct NeighbourList *n,
1084 struct SendOkMessage send_ok_msg;
1086 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1087 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1088 send_ok_msg.success = htonl (result);
1089 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1090 send_ok_msg.peer = n->id;
1091 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1096 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1097 * upon "completion" of a send request. This tells the API
1098 * that it is now legal to send another message to the given
1101 * @param cls closure, identifies the entry on the
1102 * message queue that was transmitted and the
1103 * client responsible for queueing the message
1104 * @param target the peer receiving the message
1105 * @param result GNUNET_OK on success, if the transmission
1106 * failed, we should not tell the client to transmit
1110 transmit_send_continuation (void *cls,
1111 const struct GNUNET_PeerIdentity *target,
1114 struct MessageQueue *mq = cls;
1115 struct NeighbourList *n;
1117 GNUNET_STATISTICS_update (stats,
1118 gettext_noop ("# bytes pending with plugins"),
1119 - (int64_t) mq->message_buf_size,
1121 if (result == GNUNET_OK)
1123 GNUNET_STATISTICS_update (stats,
1124 gettext_noop ("# bytes successfully transmitted by plugins"),
1125 mq->message_buf_size,
1130 GNUNET_STATISTICS_update (stats,
1131 gettext_noop ("# bytes with transmission failure by plugins"),
1132 mq->message_buf_size,
1135 n = find_neighbour(&mq->neighbour_id);
1136 GNUNET_assert (n != NULL);
1137 if (mq->specific_address != NULL)
1139 if (result == GNUNET_OK)
1141 mq->specific_address->timeout =
1142 GNUNET_TIME_relative_to_absolute
1143 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1144 if (mq->specific_address->validated == GNUNET_YES)
1145 mark_address_connected (mq->specific_address);
1149 if (mq->specific_address->connected != GNUNET_NO)
1151 GNUNET_STATISTICS_update (stats,
1152 gettext_noop ("# connected addresses"),
1155 mq->specific_address->connected = GNUNET_NO;
1158 if (! mq->internal_msg)
1159 mq->specific_address->in_transmit = GNUNET_NO;
1161 if (mq->client != NULL)
1162 transmit_send_ok (mq->client, n, result);
1164 try_transmission_to_peer (n);
1169 * Find an address in any of the available transports for
1170 * the given neighbour that would be good for message
1171 * transmission. This is essentially the transport selection
1174 * @param neighbour for whom to select an address
1175 * @return selected address, NULL if we have none
1177 struct ForeignAddressList *
1178 find_ready_address(struct NeighbourList *neighbour)
1180 struct ReadyList *head = neighbour->plugins;
1181 struct ForeignAddressList *addresses;
1182 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1183 struct ForeignAddressList *best_address;
1185 best_address = NULL;
1186 while (head != NULL)
1188 addresses = head->addresses;
1189 while (addresses != NULL)
1191 if ( (addresses->timeout.value < now.value) &&
1192 (addresses->connected == GNUNET_YES) )
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1196 "Marking long-time inactive connection to `%4s' as down.\n",
1197 GNUNET_i2s (&neighbour->id));
1199 GNUNET_STATISTICS_update (stats,
1200 gettext_noop ("# connected addresses"),
1203 addresses->connected = GNUNET_NO;
1205 addresses = addresses->next;
1208 addresses = head->addresses;
1209 while (addresses != NULL)
1211 #if DEBUG_TRANSPORT > 1
1212 if (addresses->addr != NULL)
1213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1215 GNUNET_a2s (addresses->addr,
1216 addresses->addrlen),
1217 GNUNET_i2s (&neighbour->id),
1218 addresses->connected,
1219 addresses->in_transmit,
1220 addresses->validated,
1221 addresses->connect_attempts,
1222 (unsigned long long) addresses->timeout.value,
1223 (unsigned int) addresses->distance);
1225 if ( ( (best_address == NULL) ||
1226 (addresses->connected == GNUNET_YES) ||
1227 (best_address->connected == GNUNET_NO) ) &&
1228 (addresses->in_transmit == GNUNET_NO) &&
1229 ( (best_address == NULL) ||
1230 (addresses->latency.value < best_address->latency.value)) )
1231 best_address = addresses;
1232 /* FIXME: also give lower-latency addresses that are not
1233 connected a chance some times... */
1234 addresses = addresses->next;
1238 if (best_address != NULL)
1241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242 "Best address found has latency of %llu ms.\n",
1243 best_address->latency.value);
1248 GNUNET_STATISTICS_update (stats,
1249 gettext_noop ("# transmission attempts failed (no address)"),
1253 return best_address;
1259 * We should re-try transmitting to the given peer,
1260 * hopefully we've learned something in the meantime.
1263 retry_transmission_task (void *cls,
1264 const struct GNUNET_SCHEDULER_TaskContext *tc)
1266 struct NeighbourList *n = cls;
1268 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1269 try_transmission_to_peer (n);
1274 * Check the ready list for the given neighbour and if a plugin is
1275 * ready for transmission (and if we have a message), do so!
1277 * @param neighbour target peer for which to transmit
1280 try_transmission_to_peer (struct NeighbourList *neighbour)
1282 struct ReadyList *rl;
1283 struct MessageQueue *mq;
1284 struct GNUNET_TIME_Relative timeout;
1288 if (neighbour->messages_head == NULL)
1291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1292 "Transmission queue for `%4s' is empty\n",
1293 GNUNET_i2s (&neighbour->id));
1295 return; /* nothing to do */
1298 mq = neighbour->messages_head;
1299 force_address = GNUNET_YES;
1300 if (mq->specific_address == NULL)
1302 mq->specific_address = find_ready_address(neighbour);
1303 GNUNET_STATISTICS_update (stats,
1304 gettext_noop ("# transport selected peer address freely"),
1307 force_address = GNUNET_NO;
1309 if (mq->specific_address == NULL)
1311 GNUNET_STATISTICS_update (stats,
1312 gettext_noop ("# transport failed to selected peer address"),
1315 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1316 if (timeout.value == 0)
1319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1320 "No destination address available to transmit message of size %u to peer `%4s'\n",
1321 mq->message_buf_size,
1322 GNUNET_i2s (&mq->neighbour_id));
1324 GNUNET_STATISTICS_update (stats,
1325 gettext_noop ("# bytes in message queue for other peers"),
1326 - (int64_t) mq->message_buf_size,
1328 GNUNET_STATISTICS_update (stats,
1329 gettext_noop ("# bytes discarded (no destination address available)"),
1330 mq->message_buf_size,
1332 if (mq->client != NULL)
1333 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1334 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1335 neighbour->messages_tail,
1338 return; /* nobody ready */
1340 GNUNET_STATISTICS_update (stats,
1341 gettext_noop ("# message delivery deferred (no address)"),
1344 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1345 GNUNET_SCHEDULER_cancel (sched,
1346 neighbour->retry_task);
1347 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1349 &retry_transmission_task,
1352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1354 mq->message_buf_size,
1355 GNUNET_i2s (&mq->neighbour_id),
1358 /* FIXME: might want to trigger peerinfo lookup here
1359 (unless that's already pending...) */
1362 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1363 neighbour->messages_tail,
1365 if (mq->specific_address->connected == GNUNET_NO)
1366 mq->specific_address->connect_attempts++;
1367 rl = mq->specific_address->ready_list;
1368 mq->plugin = rl->plugin;
1369 if (!mq->internal_msg)
1370 mq->specific_address->in_transmit = GNUNET_YES;
1372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1374 mq->message_buf_size,
1375 GNUNET_i2s (&neighbour->id),
1376 (mq->specific_address->addr != NULL)
1377 ? GNUNET_a2s (mq->specific_address->addr,
1378 mq->specific_address->addrlen)
1380 rl->plugin->short_name);
1382 GNUNET_STATISTICS_update (stats,
1383 gettext_noop ("# bytes in message queue for other peers"),
1384 - (int64_t) mq->message_buf_size,
1386 GNUNET_STATISTICS_update (stats,
1387 gettext_noop ("# bytes pending with plugins"),
1388 mq->message_buf_size,
1390 ret = rl->plugin->api->send (rl->plugin->api->cls,
1393 mq->message_buf_size,
1395 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1396 mq->specific_address->session,
1397 mq->specific_address->addr,
1398 mq->specific_address->addrlen,
1400 &transmit_send_continuation, mq);
1403 /* failure, but 'send' would not call continuation in this case,
1404 so we need to do it here! */
1405 transmit_send_continuation (mq,
1413 * Send the specified message to the specified peer.
1415 * @param client source of the transmission request (can be NULL)
1416 * @param peer_address ForeignAddressList where we should send this message
1417 * @param priority how important is the message
1418 * @param timeout how long do we have to transmit?
1419 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1420 * @param message_buf_size total size of all messages in message_buf
1421 * @param is_internal is this an internal message; these are pre-pended and
1422 * also do not count for plugins being "ready" to transmit
1423 * @param neighbour handle to the neighbour for transmission
1426 transmit_to_peer (struct TransportClient *client,
1427 struct ForeignAddressList *peer_address,
1428 unsigned int priority,
1429 struct GNUNET_TIME_Relative timeout,
1430 const char *message_buf,
1431 size_t message_buf_size,
1432 int is_internal, struct NeighbourList *neighbour)
1434 struct MessageQueue *mq;
1439 /* check for duplicate submission */
1440 mq = neighbour->messages_head;
1443 if (mq->client == client)
1445 /* client transmitted to same peer twice
1446 before getting SEND_OK! */
1454 GNUNET_STATISTICS_update (stats,
1455 gettext_noop ("# bytes in message queue for other peers"),
1458 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1459 mq->specific_address = peer_address;
1460 mq->client = client;
1461 memcpy (&mq[1], message_buf, message_buf_size);
1462 mq->message_buf = (const char*) &mq[1];
1463 mq->message_buf_size = message_buf_size;
1464 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1465 mq->internal_msg = is_internal;
1466 mq->priority = priority;
1467 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1469 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1470 neighbour->messages_tail,
1473 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1474 neighbour->messages_tail,
1475 neighbour->messages_tail,
1477 try_transmission_to_peer (neighbour);
1484 struct GeneratorContext
1486 struct TransportPlugin *plug_pos;
1487 struct OwnAddressList *addr_pos;
1488 struct GNUNET_TIME_Absolute expiration;
1496 address_generator (void *cls, size_t max, void *buf)
1498 struct GeneratorContext *gc = cls;
1501 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1503 gc->plug_pos = gc->plug_pos->next;
1504 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1506 if (NULL == gc->plug_pos)
1511 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1514 gc->addr_pos->addrlen, buf, max);
1515 gc->addr_pos = gc->addr_pos->next;
1521 * Construct our HELLO message from all of the addresses of
1522 * all of the transports.
1527 struct GNUNET_HELLO_Message *hello;
1528 struct TransportClient *cpos;
1529 struct NeighbourList *npos;
1530 struct GeneratorContext gc;
1532 gc.plug_pos = plugins;
1533 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1534 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1535 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1538 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1540 GNUNET_STATISTICS_update (stats,
1541 gettext_noop ("# refreshed my HELLO"),
1545 while (cpos != NULL)
1547 transmit_to_client (cpos,
1548 (const struct GNUNET_MessageHeader *) hello,
1553 GNUNET_free_non_null (our_hello);
1555 our_hello_version++;
1556 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1558 while (npos != NULL)
1561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1562 "Transmitting updated `%s' to neighbour `%4s'\n",
1563 "HELLO", GNUNET_i2s (&npos->id));
1565 GNUNET_STATISTICS_update (stats,
1566 gettext_noop ("# transmitted my HELLO to other peers"),
1569 transmit_to_peer (NULL, NULL, 0,
1570 HELLO_ADDRESS_EXPIRATION,
1571 (const char *) our_hello,
1572 GNUNET_HELLO_size(our_hello),
1580 * Task used to clean up expired addresses for a plugin.
1582 * @param cls closure
1586 expire_address_task (void *cls,
1587 const struct GNUNET_SCHEDULER_TaskContext *tc);
1591 * Update the list of addresses for this plugin,
1592 * expiring those that are past their expiration date.
1594 * @param plugin addresses of which plugin should be recomputed?
1595 * @param fresh set to GNUNET_YES if a new address was added
1596 * and we need to regenerate the HELLO even if nobody
1600 update_addresses (struct TransportPlugin *plugin, int fresh)
1602 static struct GNUNET_TIME_Absolute last_update;
1603 struct GNUNET_TIME_Relative min_remaining;
1604 struct GNUNET_TIME_Relative remaining;
1605 struct GNUNET_TIME_Absolute now;
1606 struct OwnAddressList *pos;
1607 struct OwnAddressList *prev;
1608 struct OwnAddressList *next;
1611 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1612 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1613 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1614 now = GNUNET_TIME_absolute_get ();
1615 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1616 expired = (GNUNET_TIME_absolute_get_duration (last_update).value > (HELLO_ADDRESS_EXPIRATION.value / 4));
1618 pos = plugin->addresses;
1622 if (pos->expires.value < now.value)
1624 expired = GNUNET_YES;
1626 plugin->addresses = pos->next;
1628 prev->next = pos->next;
1633 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1634 if (remaining.value < min_remaining.value)
1635 min_remaining = remaining;
1641 if (expired || fresh)
1646 min_remaining = GNUNET_TIME_relative_min (min_remaining,
1647 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1649 plugin->address_update_task
1650 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1652 &expire_address_task, plugin);
1657 * Task used to clean up expired addresses for a plugin.
1659 * @param cls closure
1663 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1665 struct TransportPlugin *plugin = cls;
1667 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1668 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1669 update_addresses (plugin, GNUNET_NO);
1674 * Iterator over hash map entries that NULLs the session of validation
1675 * entries that match the given session.
1677 * @param cls closure (the 'struct Session*' to match against)
1678 * @param key current key code (peer ID, not used)
1679 * @param value value in the hash map ('struct ValidationEntry*')
1680 * @return GNUNET_YES (we should continue to iterate)
1683 remove_session_validations (void *cls,
1684 const GNUNET_HashCode * key,
1687 struct Session *session = cls;
1688 struct ValidationEntry *ve = value;
1690 if (session == ve->session)
1697 * Function that will be called whenever the plugin internally
1698 * cleans up a session pointer and hence the service needs to
1699 * discard all of those sessions as well. Plugins that do not
1700 * use sessions can simply omit calling this function and always
1701 * use NULL wherever a session pointer is needed.
1703 * @param cls closure
1704 * @param peer which peer was the session for
1705 * @param session which session is being destoyed
1708 plugin_env_session_end (void *cls,
1709 const struct GNUNET_PeerIdentity *peer,
1710 struct Session *session)
1712 struct TransportPlugin *p = cls;
1713 struct NeighbourList *nl;
1714 struct ReadyList *rl;
1715 struct ForeignAddressList *pos;
1716 struct ForeignAddressList *prev;
1718 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
1719 &remove_session_validations,
1721 nl = find_neighbour (peer);
1727 if (rl->plugin == p)
1734 pos = rl->addresses;
1735 while ( (pos != NULL) &&
1736 (pos->session != session) )
1743 pos->session = NULL;
1744 if (pos->addrlen != 0)
1747 rl->addresses = pos->next;
1749 prev->next = pos->next;
1750 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
1752 GNUNET_SCHEDULER_cancel (sched,
1753 pos->revalidate_task);
1754 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
1757 if (nl->received_pong == GNUNET_NO)
1758 return; /* nothing to do */
1759 /* check if we have any validated addresses left */
1760 pos = rl->addresses;
1767 /* no valid addresses left, signal disconnect! */
1768 disconnect_neighbour (nl, GNUNET_NO);
1773 * Function that must be called by each plugin to notify the
1774 * transport service about the addresses under which the transport
1775 * provided by the plugin can be reached.
1777 * @param cls closure
1778 * @param name name of the transport that generated the address
1779 * @param addr one of the addresses of the host, NULL for the last address
1780 * the specific address format depends on the transport
1781 * @param addrlen length of the address
1782 * @param expires when should this address automatically expire?
1785 plugin_env_notify_address (void *cls,
1789 struct GNUNET_TIME_Relative expires)
1791 struct TransportPlugin *p = cls;
1792 struct OwnAddressList *al;
1793 struct GNUNET_TIME_Absolute abex;
1795 GNUNET_assert (addr != NULL);
1796 abex = GNUNET_TIME_relative_to_absolute (expires);
1797 GNUNET_assert (p == find_transport (name));
1801 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1803 if (al->expires.value < abex.value)
1810 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1812 al->next = p->addresses;
1815 al->addrlen = addrlen;
1816 memcpy (&al[1], addr, addrlen);
1817 update_addresses (p, GNUNET_YES);
1822 * Notify all of our clients about a peer connecting.
1825 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1826 struct GNUNET_TIME_Relative latency,
1829 struct ConnectInfoMessage cim;
1830 struct TransportClient *cpos;
1833 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1834 "Notifying clients about connection from `%s'\n",
1837 GNUNET_STATISTICS_update (stats,
1838 gettext_noop ("# peers connected"),
1841 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1842 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1843 cim.distance = htonl (distance);
1844 cim.latency = GNUNET_TIME_relative_hton (latency);
1845 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1847 while (cpos != NULL)
1849 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1856 * Notify all of our clients about a peer disconnecting.
1859 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1861 struct DisconnectInfoMessage dim;
1862 struct TransportClient *cpos;
1865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1866 "Notifying clients about lost connection to `%s'\n",
1869 GNUNET_STATISTICS_update (stats,
1870 gettext_noop ("# peers connected"),
1873 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1874 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1875 dim.reserved = htonl (0);
1876 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1878 while (cpos != NULL)
1880 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1887 * Find a ForeignAddressList entry for the given neighbour
1888 * that matches the given address and transport.
1890 * @param neighbour which peer we care about
1891 * @param tname name of the transport plugin
1892 * @param session session to look for, NULL for 'any'; otherwise
1893 * can be used for the service to "learn" this session ID
1895 * @param addr binary address
1896 * @param addrlen length of addr
1897 * @return NULL if no such entry exists
1899 static struct ForeignAddressList *
1900 find_peer_address(struct NeighbourList *neighbour,
1902 struct Session *session,
1906 struct ReadyList *head;
1907 struct ForeignAddressList *pos;
1909 head = neighbour->plugins;
1910 while (head != NULL)
1912 if (0 == strcmp (tname, head->plugin->short_name))
1918 pos = head->addresses;
1919 while ( (pos != NULL) &&
1920 ( (pos->addrlen != addrlen) ||
1921 (memcmp(pos->addr, addr, addrlen) != 0) ) )
1923 if ( (session != NULL) &&
1924 (pos->session == session) )
1928 if ( (session != NULL) && (pos != NULL) )
1929 pos->session = session; /* learn it! */
1935 * Get the peer address struct for the given neighbour and
1936 * address. If it doesn't yet exist, create it.
1938 * @param neighbour which peer we care about
1939 * @param tname name of the transport plugin
1940 * @param session session of the plugin, or NULL for none
1941 * @param addr binary address
1942 * @param addrlen length of addr
1943 * @return NULL if we do not have a transport plugin for 'tname'
1945 static struct ForeignAddressList *
1946 add_peer_address (struct NeighbourList *neighbour,
1948 struct Session *session,
1952 struct ReadyList *head;
1953 struct ForeignAddressList *ret;
1955 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
1958 head = neighbour->plugins;
1959 while (head != NULL)
1961 if (0 == strcmp (tname, head->plugin->short_name))
1967 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1968 ret->session = session;
1971 ret->addr = (const char*) &ret[1];
1972 memcpy (&ret[1], addr, addrlen);
1978 ret->addrlen = addrlen;
1979 ret->expires = GNUNET_TIME_relative_to_absolute
1980 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1981 ret->latency = GNUNET_TIME_relative_get_forever();
1983 ret->timeout = GNUNET_TIME_relative_to_absolute
1984 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1985 ret->ready_list = head;
1986 ret->next = head->addresses;
1987 head->addresses = ret;
1993 * Closure for 'add_validated_address'.
1995 struct AddValidatedAddressContext
1998 * Entry that has been validated.
2000 const struct ValidationEntry *ve;
2003 * Flag set after we have added the address so
2004 * that we terminate the iteration next time.
2011 * Callback function used to fill a buffer of max bytes with a list of
2012 * addresses in the format used by HELLOs. Should use
2013 * "GNUNET_HELLO_add_address" as a helper function.
2015 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2016 * @param max maximum number of bytes that can be written to buf
2017 * @param buf where to write the address information
2018 * @return number of bytes written, 0 to signal the
2019 * end of the iteration.
2022 add_validated_address (void *cls,
2023 size_t max, void *buf)
2025 struct AddValidatedAddressContext *avac = cls;
2026 const struct ValidationEntry *ve = avac->ve;
2028 if (GNUNET_YES == avac->done)
2030 avac->done = GNUNET_YES;
2031 return GNUNET_HELLO_add_address (ve->transport_name,
2032 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2042 * Closure for 'check_address_exists'.
2044 struct CheckAddressExistsClosure
2047 * Address to check for.
2052 * Name of the transport.
2059 struct Session *session;
2067 * Set to GNUNET_YES if the address exists.
2074 * Iterator over hash map entries. Checks if the given
2075 * validation entry is for the same address as what is given
2078 * @param cls the 'struct CheckAddressExistsClosure*'
2079 * @param key current key code (ignored)
2080 * @param value value in the hash map ('struct ValidationEntry')
2081 * @return GNUNET_YES if we should continue to
2082 * iterate (mismatch), GNUNET_NO if not (entry matched)
2085 check_address_exists (void *cls,
2086 const GNUNET_HashCode * key,
2089 struct CheckAddressExistsClosure *caec = cls;
2090 struct ValidationEntry *ve = value;
2092 if ( (0 == strcmp (caec->tname,
2093 ve->transport_name)) &&
2094 (caec->addrlen == ve->addrlen) &&
2095 (0 == memcmp (caec->addr,
2099 caec->exists = GNUNET_YES;
2102 if ( (ve->session != NULL) &&
2103 (caec->session == ve->session) )
2105 caec->exists = GNUNET_YES;
2113 * HELLO validation cleanup task (validation failed).
2115 * @param cls the 'struct ValidationEntry' that failed
2116 * @param tc scheduler context (unused)
2119 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2121 struct ValidationEntry *va = cls;
2122 struct GNUNET_PeerIdentity pid;
2124 GNUNET_STATISTICS_update (stats,
2125 gettext_noop ("# address validation timeouts"),
2128 GNUNET_CRYPTO_hash (&va->publicKey,
2130 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2132 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2135 GNUNET_free (va->transport_name);
2141 neighbour_timeout_task (void *cls,
2142 const struct GNUNET_SCHEDULER_TaskContext *tc)
2144 struct NeighbourList *n = cls;
2147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2148 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2150 GNUNET_STATISTICS_update (stats,
2151 gettext_noop ("# disconnects due to timeout"),
2154 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2155 disconnect_neighbour (n, GNUNET_NO);
2160 * Schedule the job that will cause us to send a PING to the
2161 * foreign address to evaluate its validity and latency.
2163 * @param fal address to PING
2166 schedule_next_ping (struct ForeignAddressList *fal);
2170 * Add the given address to the list of foreign addresses
2171 * available for the given peer (check for duplicates).
2173 * @param cls the respective 'struct NeighbourList' to update
2174 * @param tname name of the transport
2175 * @param expiration expiration time
2176 * @param addr the address
2177 * @param addrlen length of the address
2178 * @return GNUNET_OK (always)
2181 add_to_foreign_address_list (void *cls,
2183 struct GNUNET_TIME_Absolute expiration,
2184 const void *addr, size_t addrlen)
2186 struct NeighbourList *n = cls;
2187 struct ForeignAddressList *fal;
2190 GNUNET_STATISTICS_update (stats,
2191 gettext_noop ("# valid peer addresses returned by peerinfo"),
2195 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2201 GNUNET_a2s (addr, addrlen),
2203 GNUNET_i2s (&n->id),
2206 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2209 GNUNET_STATISTICS_update (stats,
2210 gettext_noop ("# previously validated addresses lacking transport"),
2216 fal->expires = GNUNET_TIME_absolute_max (expiration,
2218 schedule_next_ping (fal);
2224 fal->expires = GNUNET_TIME_absolute_max (expiration,
2229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2230 "Failed to add new address for `%4s'\n",
2231 GNUNET_i2s (&n->id));
2234 if (fal->validated == GNUNET_NO)
2236 fal->validated = GNUNET_YES;
2237 GNUNET_STATISTICS_update (stats,
2238 gettext_noop ("# peer addresses considered valid"),
2242 if (try == GNUNET_YES)
2244 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2245 "Have new addresses, will try to trigger transmissions.\n");
2246 try_transmission_to_peer (n);
2253 * Add addresses in validated HELLO "h" to the set of addresses
2254 * we have for this peer.
2256 * @param cls closure ('struct NeighbourList*')
2257 * @param peer id of the peer, NULL for last call
2258 * @param h hello message for the peer (can be NULL)
2259 * @param trust amount of trust we have in the peer (not used)
2262 add_hello_for_peer (void *cls,
2263 const struct GNUNET_PeerIdentity *peer,
2264 const struct GNUNET_HELLO_Message *h,
2267 struct NeighbourList *n = cls;
2275 return; /* no HELLO available */
2277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2278 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2282 if (GNUNET_YES != n->public_key_valid)
2284 GNUNET_HELLO_get_key (h, &n->publicKey);
2285 n->public_key_valid = GNUNET_YES;
2287 GNUNET_HELLO_iterate_addresses (h,
2289 &add_to_foreign_address_list,
2295 * Create a fresh entry in our neighbour list for the given peer.
2296 * Will try to transmit our current HELLO to the new neighbour.
2298 * @param peer the peer for which we create the entry
2299 * @return the new neighbour list entry
2301 static struct NeighbourList *
2302 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2304 struct NeighbourList *n;
2305 struct TransportPlugin *tp;
2306 struct ReadyList *rl;
2308 GNUNET_assert (our_hello != NULL);
2309 GNUNET_STATISTICS_update (stats,
2310 gettext_noop ("# active neighbours"),
2313 n = GNUNET_malloc (sizeof (struct NeighbourList));
2314 n->next = neighbours;
2318 GNUNET_TIME_relative_to_absolute
2319 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2320 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2321 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2322 MAX_BANDWIDTH_CARRY_S);
2326 if (tp->api->send != NULL)
2328 rl = GNUNET_malloc (sizeof (struct ReadyList));
2330 rl->next = n->plugins;
2333 rl->addresses = NULL;
2337 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2339 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2340 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2341 &neighbour_timeout_task, n);
2342 n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2343 0, GNUNET_TIME_UNIT_FOREVER_REL,
2344 &add_hello_for_peer, n);
2345 transmit_to_peer (NULL, NULL, 0,
2346 HELLO_ADDRESS_EXPIRATION,
2347 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2354 * Send periodic PING messages to a give foreign address.
2356 * @param cls our 'struct PeriodicValidationContext*'
2357 * @param tc task context
2360 send_periodic_ping (void *cls,
2361 const struct GNUNET_SCHEDULER_TaskContext *tc)
2363 struct ForeignAddressList *peer_address = cls;
2364 struct TransportPlugin *tp;
2365 struct ValidationEntry *va;
2366 struct NeighbourList *neighbour;
2367 struct TransportPingMessage ping;
2368 struct CheckAddressExistsClosure caec;
2370 uint16_t hello_size;
2373 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2374 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2376 tp = peer_address->ready_list->plugin;
2377 neighbour = peer_address->ready_list->neighbour;
2378 if (GNUNET_YES != neighbour->public_key_valid)
2380 /* no public key yet, try again later */
2381 schedule_next_ping (peer_address);
2384 caec.addr = peer_address->addr;
2385 caec.addrlen = peer_address->addrlen;
2386 caec.tname = tp->short_name;
2387 caec.session = peer_address->session;
2388 caec.exists = GNUNET_NO;
2389 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2390 &check_address_exists,
2392 if (caec.exists == GNUNET_YES)
2394 /* During validation attempts we will likely trigger the other
2395 peer trying to validate our address which in turn will cause
2396 it to send us its HELLO, so we expect to hit this case rather
2397 frequently. Only print something if we are very verbose. */
2398 #if DEBUG_TRANSPORT > 1
2399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2401 (peer_address->addr != NULL)
2402 ? GNUNET_a2s (peer_address->addr,
2403 peer_address->addrlen)
2406 GNUNET_i2s (&neighbour->id));
2408 schedule_next_ping (peer_address);
2411 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2412 va->transport_name = GNUNET_strdup (tp->short_name);
2413 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2415 va->send_time = GNUNET_TIME_absolute_get();
2416 va->session = peer_address->session;
2417 if (peer_address->addr != NULL)
2419 va->addr = (const void*) &va[1];
2420 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2421 va->addrlen = peer_address->addrlen;
2423 memcpy(&va->publicKey,
2424 &neighbour->publicKey,
2425 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2427 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2428 HELLO_VERIFICATION_TIMEOUT,
2429 &timeout_hello_validation,
2431 GNUNET_CONTAINER_multihashmap_put (validation_map,
2432 &neighbour->id.hashPubKey,
2434 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2435 hello_size = GNUNET_HELLO_size(our_hello);
2436 tsize = sizeof(struct TransportPingMessage) + hello_size;
2437 message_buf = GNUNET_malloc(tsize);
2438 ping.challenge = htonl(va->challenge);
2439 ping.header.size = htons(sizeof(struct TransportPingMessage));
2440 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2441 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2442 memcpy(message_buf, our_hello, hello_size);
2443 memcpy(&message_buf[hello_size],
2445 sizeof(struct TransportPingMessage));
2446 #if DEBUG_TRANSPORT_REVALIDATION
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2449 (peer_address->addr != NULL)
2450 ? GNUNET_a2s (peer_address->addr,
2451 peer_address->addrlen)
2454 GNUNET_i2s (&neighbour->id),
2455 "HELLO", hello_size,
2456 "PING", sizeof (struct TransportPingMessage));
2458 GNUNET_STATISTICS_update (stats,
2459 gettext_noop ("# PING messages sent for re-validation"),
2462 transmit_to_peer (NULL, peer_address,
2463 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2464 HELLO_VERIFICATION_TIMEOUT,
2466 GNUNET_YES, neighbour);
2467 GNUNET_free(message_buf);
2468 schedule_next_ping (peer_address);
2473 * Schedule the job that will cause us to send a PING to the
2474 * foreign address to evaluate its validity and latency.
2476 * @param fal address to PING
2479 schedule_next_ping (struct ForeignAddressList *fal)
2481 struct GNUNET_TIME_Relative delay;
2483 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2485 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2486 delay.value /= 2; /* do before expiration */
2487 delay = GNUNET_TIME_relative_min (delay,
2488 LATENCY_EVALUATION_MAX_DELAY);
2489 if (GNUNET_YES != fal->estimated)
2491 delay = GNUNET_TIME_UNIT_ZERO;
2492 fal->estimated = GNUNET_YES;
2494 if (GNUNET_YES == fal->connected)
2496 delay = GNUNET_TIME_relative_min (delay,
2497 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2499 /* FIXME: also adjust delay based on how close the last
2500 observed latency is to the latency of the best alternative */
2501 /* bound how fast we can go */
2502 delay = GNUNET_TIME_relative_max (delay,
2503 GNUNET_TIME_UNIT_SECONDS);
2504 /* randomize a bit (to avoid doing all at the same time) */
2505 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2506 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
2508 &send_periodic_ping,
2516 * Function that will be called if we receive some payload
2517 * from another peer.
2519 * @param message the payload
2520 * @param n peer who claimed to be the sender
2523 handle_payload_message (const struct GNUNET_MessageHeader *message,
2524 struct NeighbourList *n)
2526 struct InboundMessage *im;
2527 struct TransportClient *cpos;
2530 msize = ntohs (message->size);
2531 if (n->received_pong == GNUNET_NO)
2533 GNUNET_free_non_null (n->pre_connect_message_buffer);
2534 n->pre_connect_message_buffer = GNUNET_malloc (msize);
2535 memcpy (n->pre_connect_message_buffer, message, msize);
2539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540 "Received message of type %u from `%4s', sending to all clients.\n",
2541 ntohs (message->type),
2542 GNUNET_i2s (&n->id));
2544 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2547 n->quota_violation_count++;
2549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
2551 n->in_tracker.available_bytes_per_s__,
2552 n->quota_violation_count);
2554 /* Discount 32k per violation */
2555 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2560 if (n->quota_violation_count > 0)
2562 /* try to add 32k back */
2563 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2565 n->quota_violation_count--;
2568 GNUNET_STATISTICS_update (stats,
2569 gettext_noop ("# payload received from other peers"),
2572 /* transmit message to all clients */
2573 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2574 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2575 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2576 im->latency = GNUNET_TIME_relative_hton (n->latency);
2578 memcpy (&im[1], message, msize);
2580 while (cpos != NULL)
2582 transmit_to_client (cpos, &im->header, GNUNET_YES);
2590 * Iterator over hash map entries. Checks if the given validation
2591 * entry is for the same challenge as what is given in the PONG.
2593 * @param cls the 'struct TransportPongMessage*'
2594 * @param key peer identity
2595 * @param value value in the hash map ('struct ValidationEntry')
2596 * @return GNUNET_YES if we should continue to
2597 * iterate (mismatch), GNUNET_NO if not (entry matched)
2600 check_pending_validation (void *cls,
2601 const GNUNET_HashCode * key,
2604 const struct TransportPongMessage *pong = cls;
2605 struct ValidationEntry *ve = value;
2606 struct AddValidatedAddressContext avac;
2607 unsigned int challenge = ntohl(pong->challenge);
2608 struct GNUNET_HELLO_Message *hello;
2609 struct GNUNET_PeerIdentity target;
2610 struct NeighbourList *n;
2611 struct ForeignAddressList *fal;
2612 struct GNUNET_MessageHeader *prem;
2614 if (ve->challenge != challenge)
2617 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING,
2622 GNUNET_break_op (0);
2627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2631 ? GNUNET_a2s ((const struct sockaddr *) ve->addr,
2634 ve->transport_name);
2636 GNUNET_STATISTICS_update (stats,
2637 gettext_noop ("# address validation successes"),
2640 /* create the updated HELLO */
2641 GNUNET_CRYPTO_hash (&ve->publicKey,
2642 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2643 &target.hashPubKey);
2644 if (ve->addr != NULL)
2646 avac.done = GNUNET_NO;
2648 hello = GNUNET_HELLO_create (&ve->publicKey,
2649 &add_validated_address,
2651 GNUNET_PEERINFO_add_peer (cfg, sched,
2654 GNUNET_free (hello);
2656 n = find_neighbour (&target);
2659 n->publicKey = ve->publicKey;
2660 n->public_key_valid = GNUNET_YES;
2661 fal = add_peer_address (n,
2666 GNUNET_assert (fal != NULL);
2667 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2668 fal->validated = GNUNET_YES;
2669 mark_address_connected (fal);
2670 GNUNET_STATISTICS_update (stats,
2671 gettext_noop ("# peer addresses considered valid"),
2674 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2675 schedule_next_ping (fal);
2676 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2677 n->latency = fal->latency;
2679 n->latency.value = (fal->latency.value + n->latency.value) / 2;
2680 n->distance = fal->distance;
2681 if (GNUNET_NO == n->received_pong)
2683 n->received_pong = GNUNET_YES;
2684 notify_clients_connect (&target, n->latency, n->distance);
2685 if (NULL != (prem = n->pre_connect_message_buffer))
2687 n->pre_connect_message_buffer = NULL;
2688 handle_payload_message (prem, n);
2692 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2694 GNUNET_SCHEDULER_cancel (sched,
2696 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2697 try_transmission_to_peer (n);
2701 /* clean up validation entry */
2702 GNUNET_assert (GNUNET_YES ==
2703 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2706 GNUNET_SCHEDULER_cancel (sched,
2708 GNUNET_free (ve->transport_name);
2715 * Function that will be called if we receive a validation
2716 * of an address challenge that we transmitted to another
2717 * peer. Note that the validation should only be considered
2718 * acceptable if the challenge matches AND if the sender
2719 * address is at least a plausible address for this peer
2720 * (otherwise we may be seeing a MiM attack).
2722 * @param cls closure
2723 * @param message the pong message
2724 * @param peer who responded to our challenge
2725 * @param sender_address string describing our sender address (as observed
2726 * by the other peer in binary format)
2727 * @param sender_address_len number of bytes in 'sender_address'
2730 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2731 const struct GNUNET_PeerIdentity *peer,
2732 const char *sender_address,
2733 size_t sender_address_len)
2735 #if DEBUG_TRANSPORT > 1
2736 /* we get tons of these that just get discarded, only log
2737 if we are quite verbose */
2738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2739 "Receiving `%s' message from `%4s'.\n", "PONG",
2742 GNUNET_STATISTICS_update (stats,
2743 gettext_noop ("# PONG messages received"),
2746 if (GNUNET_SYSERR !=
2747 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2749 &check_pending_validation,
2752 /* This is *expected* to happen a lot since we send
2753 PONGs to *all* known addresses of the sender of
2754 the PING, so most likely we get multiple PONGs
2755 per PING, and all but the first PONG will end up
2756 here. So really we should not print anything here
2757 unless we want to be very, very verbose... */
2758 #if DEBUG_TRANSPORT > 2
2759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2760 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2769 /* FIXME: add given address to potential pool of our addresses
2771 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2772 _("Another peer saw us using the address `%s' via `%s'.\n"),
2773 GNUNET_a2s ((const struct sockaddr *) &pong[1],
2774 ntohs(pong->addrlen)),
2775 va->transport_name);
2781 * Check if the given address is already being validated; if not,
2782 * append the given address to the list of entries that are being be
2783 * validated and initiate validation.
2785 * @param cls closure ('struct CheckHelloValidatedContext *')
2786 * @param tname name of the transport
2787 * @param expiration expiration time
2788 * @param addr the address
2789 * @param addrlen length of the address
2790 * @return GNUNET_OK (always)
2793 run_validation (void *cls,
2795 struct GNUNET_TIME_Absolute expiration,
2796 const void *addr, size_t addrlen)
2798 struct CheckHelloValidatedContext *chvc = cls;
2799 struct GNUNET_PeerIdentity id;
2800 struct TransportPlugin *tp;
2801 struct ValidationEntry *va;
2802 struct NeighbourList *neighbour;
2803 struct ForeignAddressList *peer_address;
2804 struct TransportPingMessage ping;
2805 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2806 struct CheckAddressExistsClosure caec;
2808 uint16_t hello_size;
2811 GNUNET_assert (addr != NULL);
2812 GNUNET_STATISTICS_update (stats,
2813 gettext_noop ("# peer addresses scheduled for validation"),
2816 tp = find_transport (tname);
2819 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2820 GNUNET_ERROR_TYPE_BULK,
2822 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2824 GNUNET_STATISTICS_update (stats,
2825 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2830 GNUNET_HELLO_get_key (chvc->hello, &pk);
2831 GNUNET_CRYPTO_hash (&pk,
2833 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2836 caec.addrlen = addrlen;
2837 caec.session = NULL;
2839 caec.exists = GNUNET_NO;
2840 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2841 &check_address_exists,
2843 if (caec.exists == GNUNET_YES)
2845 /* During validation attempts we will likely trigger the other
2846 peer trying to validate our address which in turn will cause
2847 it to send us its HELLO, so we expect to hit this case rather
2848 frequently. Only print something if we are very verbose. */
2849 #if DEBUG_TRANSPORT > 1
2850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2852 GNUNET_a2s (addr, addrlen),
2856 GNUNET_STATISTICS_update (stats,
2857 gettext_noop ("# peer addresses not validated (in progress)"),
2862 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2863 va->transport_name = GNUNET_strdup (tname);
2864 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2866 va->send_time = GNUNET_TIME_absolute_get();
2867 va->addr = (const void*) &va[1];
2868 memcpy (&va[1], addr, addrlen);
2869 va->addrlen = addrlen;
2870 GNUNET_HELLO_get_key (chvc->hello,
2872 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2873 HELLO_VERIFICATION_TIMEOUT,
2874 &timeout_hello_validation,
2876 GNUNET_CONTAINER_multihashmap_put (validation_map,
2879 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2880 neighbour = find_neighbour(&id);
2881 if (neighbour == NULL)
2882 neighbour = setup_new_neighbour(&id);
2883 neighbour->publicKey = va->publicKey;
2884 neighbour->public_key_valid = GNUNET_YES;
2885 peer_address = add_peer_address (neighbour, tname, NULL, addr, addrlen);
2886 GNUNET_assert(peer_address != NULL);
2887 hello_size = GNUNET_HELLO_size(our_hello);
2888 tsize = sizeof(struct TransportPingMessage) + hello_size;
2889 message_buf = GNUNET_malloc(tsize);
2890 ping.challenge = htonl(va->challenge);
2891 ping.header.size = htons(sizeof(struct TransportPingMessage));
2892 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2893 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2894 memcpy(message_buf, our_hello, hello_size);
2895 memcpy(&message_buf[hello_size],
2897 sizeof(struct TransportPingMessage));
2899 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2901 GNUNET_a2s (addr, addrlen),
2904 "HELLO", hello_size,
2905 "PING", sizeof (struct TransportPingMessage));
2907 GNUNET_STATISTICS_update (stats,
2908 gettext_noop ("# PING messages sent for initial validation"),
2911 transmit_to_peer (NULL, peer_address,
2912 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2913 HELLO_VERIFICATION_TIMEOUT,
2915 GNUNET_YES, neighbour);
2916 GNUNET_free(message_buf);
2922 * Check if addresses in validated hello "h" overlap with
2923 * those in "chvc->hello" and validate the rest.
2925 * @param cls closure
2926 * @param peer id of the peer, NULL for last call
2927 * @param h hello message for the peer (can be NULL)
2928 * @param trust amount of trust we have in the peer (not used)
2931 check_hello_validated (void *cls,
2932 const struct GNUNET_PeerIdentity *peer,
2933 const struct GNUNET_HELLO_Message *h,
2936 struct CheckHelloValidatedContext *chvc = cls;
2937 struct GNUNET_HELLO_Message *plain_hello;
2938 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2939 struct GNUNET_PeerIdentity target;
2940 struct NeighbourList *n;
2945 GNUNET_CONTAINER_DLL_remove (chvc_head,
2948 if (GNUNET_NO == chvc->hello_known)
2950 /* notify PEERINFO about the peer now, so that we at least
2951 have the public key if some other component needs it */
2952 GNUNET_HELLO_get_key (chvc->hello, &pk);
2953 GNUNET_CRYPTO_hash (&pk,
2954 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2955 &target.hashPubKey);
2956 plain_hello = GNUNET_HELLO_create (&pk,
2959 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2960 GNUNET_free (plain_hello);
2962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2963 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2965 GNUNET_i2s (&target));
2967 GNUNET_STATISTICS_update (stats,
2968 gettext_noop ("# new HELLOs requiring full validation"),
2971 GNUNET_HELLO_iterate_addresses (chvc->hello,
2978 GNUNET_STATISTICS_update (stats,
2979 gettext_noop ("# duplicate HELLO (peer known)"),
2989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2990 "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2994 chvc->hello_known = GNUNET_YES;
2995 n = find_neighbour (peer);
2998 GNUNET_HELLO_iterate_addresses (h,
3000 &add_to_foreign_address_list,
3002 try_transmission_to_peer (n);
3006 GNUNET_STATISTICS_update (stats,
3007 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3011 GNUNET_STATISTICS_update (stats,
3012 gettext_noop ("# HELLO validations (update case)"),
3015 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3017 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3023 * Process HELLO-message.
3025 * @param plugin transport involved, may be NULL
3026 * @param message the actual message
3027 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3030 process_hello (struct TransportPlugin *plugin,
3031 const struct GNUNET_MessageHeader *message)
3034 struct GNUNET_PeerIdentity target;
3035 const struct GNUNET_HELLO_Message *hello;
3036 struct CheckHelloValidatedContext *chvc;
3037 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3039 hsize = ntohs (message->size);
3040 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3041 (hsize < sizeof (struct GNUNET_MessageHeader)))
3044 return GNUNET_SYSERR;
3046 GNUNET_STATISTICS_update (stats,
3047 gettext_noop ("# HELLOs received for validation"),
3050 /* first, check if load is too high */
3051 if (GNUNET_SCHEDULER_get_load (sched,
3052 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3054 GNUNET_STATISTICS_update (stats,
3055 gettext_noop ("# HELLOs ignored due to high load"),
3060 hello = (const struct GNUNET_HELLO_Message *) message;
3061 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3063 GNUNET_break_op (0);
3064 return GNUNET_SYSERR;
3066 GNUNET_CRYPTO_hash (&publicKey,
3067 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3068 &target.hashPubKey);
3069 if (0 == memcmp (&my_identity,
3071 sizeof (struct GNUNET_PeerIdentity)))
3073 GNUNET_STATISTICS_update (stats,
3074 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3079 #if DEBUG_TRANSPORT > 1
3080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3081 "Processing `%s' message for `%4s' of size %u\n",
3083 GNUNET_i2s (&target),
3084 GNUNET_HELLO_size(hello));
3086 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3087 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3088 memcpy (&chvc[1], hello, hsize);
3089 GNUNET_CONTAINER_DLL_insert (chvc_head,
3092 /* finally, check if HELLO was previously validated
3093 (continuation will then schedule actual validation) */
3094 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
3098 HELLO_VERIFICATION_TIMEOUT,
3099 &check_hello_validated, chvc);
3105 * The peer specified by the given neighbour has timed-out or a plugin
3106 * has disconnected. We may either need to do nothing (other plugins
3107 * still up), or trigger a full disconnect and clean up. This
3108 * function updates our state and does the necessary notifications.
3109 * Also notifies our clients that the neighbour is now officially
3112 * @param n the neighbour list entry for the peer
3113 * @param check should we just check if all plugins
3114 * disconnected or must we ask all plugins to
3118 disconnect_neighbour (struct NeighbourList *n, int check)
3120 struct ReadyList *rpos;
3121 struct NeighbourList *npos;
3122 struct NeighbourList *nprev;
3123 struct MessageQueue *mq;
3124 struct ForeignAddressList *peer_addresses;
3125 struct ForeignAddressList *peer_pos;
3127 if (GNUNET_YES == check)
3130 while (NULL != rpos)
3132 peer_addresses = rpos->addresses;
3133 while (peer_addresses != NULL)
3135 if (GNUNET_YES == peer_addresses->connected)
3136 return; /* still connected */
3137 peer_addresses = peer_addresses->next;
3143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3144 "Disconnecting from `%4s'\n",
3145 GNUNET_i2s (&n->id));
3147 /* remove n from neighbours list */
3150 while ((npos != NULL) && (npos != n))
3155 GNUNET_assert (npos != NULL);
3157 neighbours = n->next;
3159 nprev->next = n->next;
3161 /* notify all clients about disconnect */
3162 if (GNUNET_YES == n->received_pong)
3163 notify_clients_disconnect (&n->id);
3165 /* clean up all plugins, cancel connections and pending transmissions */
3166 while (NULL != (rpos = n->plugins))
3168 n->plugins = rpos->next;
3169 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3170 while (rpos->addresses != NULL)
3172 peer_pos = rpos->addresses;
3173 rpos->addresses = peer_pos->next;
3174 if (peer_pos->connected == GNUNET_YES)
3175 GNUNET_STATISTICS_update (stats,
3176 gettext_noop ("# connected addresses"),
3179 if (GNUNET_YES == peer_pos->validated)
3180 GNUNET_STATISTICS_update (stats,
3181 gettext_noop ("# peer addresses considered valid"),
3184 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3186 GNUNET_SCHEDULER_cancel (sched,
3187 peer_pos->revalidate_task);
3188 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3190 GNUNET_free(peer_pos);
3195 /* free all messages on the queue */
3196 while (NULL != (mq = n->messages_head))
3198 GNUNET_STATISTICS_update (stats,
3199 gettext_noop ("# bytes in message queue for other peers"),
3200 - (int64_t) mq->message_buf_size,
3202 GNUNET_STATISTICS_update (stats,
3203 gettext_noop ("# bytes discarded due to disconnect"),
3204 mq->message_buf_size,
3206 GNUNET_CONTAINER_DLL_remove (n->messages_head,
3209 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
3211 sizeof(struct GNUNET_PeerIdentity)));
3214 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
3216 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
3217 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3219 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3221 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
3222 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3224 if (n->piter != NULL)
3226 GNUNET_PEERINFO_iterate_cancel (n->piter);
3229 /* finally, free n itself */
3230 GNUNET_STATISTICS_update (stats,
3231 gettext_noop ("# active neighbours"),
3234 GNUNET_free_non_null (n->pre_connect_message_buffer);
3240 * We have received a PING message from someone. Need to send a PONG message
3241 * in response to the peer by any means necessary.
3244 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
3245 const struct GNUNET_PeerIdentity *peer,
3246 const char *sender_address,
3247 size_t sender_address_len)
3249 struct TransportPlugin *plugin = cls;
3250 struct TransportPingMessage *ping;
3251 struct TransportPongMessage *pong;
3252 struct NeighbourList *n;
3253 struct ReadyList *rl;
3254 struct ForeignAddressList *fal;
3256 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
3258 GNUNET_break_op (0);
3259 return GNUNET_SYSERR;
3261 ping = (struct TransportPingMessage *) message;
3262 if (0 != memcmp (&ping->target,
3263 plugin->env.my_identity,
3264 sizeof (struct GNUNET_PeerIdentity)))
3266 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3267 _("Received `%s' message not destined for me!\n"),
3269 return GNUNET_SYSERR;
3272 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3273 "Processing `%s' from `%s'\n",
3275 GNUNET_a2s ((const struct sockaddr *)sender_address,
3276 sender_address_len));
3278 GNUNET_STATISTICS_update (stats,
3279 gettext_noop ("# PING messages received"),
3282 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
3283 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
3284 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
3285 pong->purpose.size =
3286 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3288 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
3289 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
3290 pong->challenge = ping->challenge;
3291 pong->addrlen = htons(sender_address_len);
3292 memcpy(&pong->signer,
3294 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3295 memcpy (&pong[1], sender_address, sender_address_len);
3296 GNUNET_assert (GNUNET_OK ==
3297 GNUNET_CRYPTO_rsa_sign (my_private_key,
3298 &pong->purpose, &pong->signature));
3299 n = find_neighbour(peer);
3300 GNUNET_assert (n != NULL);
3301 /* first try reliable response transmission */
3305 fal = rl->addresses;
3308 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3311 ntohs (pong->header.size),
3312 TRANSPORT_PONG_PRIORITY,
3313 HELLO_VERIFICATION_TIMEOUT,
3321 GNUNET_STATISTICS_update (stats,
3322 gettext_noop ("# PONGs unicast via reliable transport"),
3332 /* no reliable method found, do multicast */
3333 GNUNET_STATISTICS_update (stats,
3334 gettext_noop ("# PONGs multicast to all available addresses"),
3340 fal = rl->addresses;
3343 transmit_to_peer(NULL, fal,
3344 TRANSPORT_PONG_PRIORITY,
3345 HELLO_VERIFICATION_TIMEOUT,
3347 ntohs(pong->header.size),
3360 * Function called by the plugin for each received message.
3361 * Update data volumes, possibly notify plugins about
3362 * reducing the rate at which they read from the socket
3363 * and generally forward to our receive callback.
3365 * @param cls the "struct TransportPlugin *" we gave to the plugin
3366 * @param peer (claimed) identity of the other peer
3367 * @param message the message, NULL if we only care about
3368 * learning about the delay until we should receive again
3369 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3370 * @param session identifier used for this session (can be NULL)
3371 * @param sender_address binary address of the sender (if observed)
3372 * @param sender_address_len number of bytes in sender_address
3373 * @return how long the plugin should wait until receiving more data
3374 * (plugins that do not support this, can ignore the return value)
3376 static struct GNUNET_TIME_Relative
3377 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3378 const struct GNUNET_MessageHeader *message,
3379 unsigned int distance,
3380 struct Session *session,
3381 const char *sender_address,
3382 size_t sender_address_len)
3384 struct TransportPlugin *plugin = cls;
3385 struct ReadyList *service_context;
3386 struct ForeignAddressList *peer_address;
3388 struct NeighbourList *n;
3389 struct GNUNET_TIME_Relative ret;
3391 n = find_neighbour (peer);
3393 n = setup_new_neighbour (peer);
3394 service_context = n->plugins;
3395 while ((service_context != NULL) && (plugin != service_context->plugin))
3396 service_context = service_context->next;
3397 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3398 peer_address = NULL;
3399 if (message != NULL)
3401 if ( (session != NULL) ||
3402 (sender_address != NULL) )
3403 peer_address = add_peer_address (n,
3407 sender_address_len);
3408 if (peer_address != NULL)
3410 peer_address->distance = distance;
3411 if (GNUNET_YES == peer_address->validated)
3412 mark_address_connected (peer_address);
3413 peer_address->timeout
3415 GNUNET_TIME_relative_to_absolute
3416 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3417 schedule_next_ping (peer_address);
3419 /* update traffic received amount ... */
3420 msize = ntohs (message->size);
3421 GNUNET_STATISTICS_update (stats,
3422 gettext_noop ("# bytes received from other peers"),
3425 n->distance = distance;
3427 GNUNET_TIME_relative_to_absolute
3428 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3429 GNUNET_SCHEDULER_cancel (sched,
3432 GNUNET_SCHEDULER_add_delayed (sched,
3433 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3434 &neighbour_timeout_task, n);
3435 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3437 /* dropping message due to frequent inbound volume violations! */
3438 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3439 GNUNET_ERROR_TYPE_BULK,
3441 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
3442 n->in_tracker.available_bytes_per_s__,
3443 n->quota_violation_count);
3444 GNUNET_STATISTICS_update (stats,
3445 gettext_noop ("# bandwidth quota violations by other peers"),
3448 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
3450 switch (ntohs (message->type))
3452 case GNUNET_MESSAGE_TYPE_HELLO:
3453 GNUNET_STATISTICS_update (stats,
3454 gettext_noop ("# HELLO messages received from other peers"),
3457 process_hello (plugin, message);
3459 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3460 handle_ping (plugin, message, peer, sender_address, sender_address_len);
3462 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3463 handle_pong (plugin, message, peer, sender_address, sender_address_len);
3466 handle_payload_message (message, n);
3470 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3473 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3474 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3475 (unsigned long long) n->in_tracker.consumption_since_last_update__,
3476 (unsigned int) n->in_tracker.available_bytes_per_s__,
3477 (unsigned long long) ret.value);
3478 GNUNET_STATISTICS_update (stats,
3479 gettext_noop ("# ms throttling suggested"),
3480 (int64_t) ret.value,
3488 * Handle START-message. This is the first message sent to us
3489 * by any client which causes us to add it to our list.
3491 * @param cls closure (always NULL)
3492 * @param client identification of the client
3493 * @param message the actual message
3496 handle_start (void *cls,
3497 struct GNUNET_SERVER_Client *client,
3498 const struct GNUNET_MessageHeader *message)
3500 struct TransportClient *c;
3501 struct ConnectInfoMessage cim;
3502 struct NeighbourList *n;
3505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3506 "Received `%s' request from client\n", "START");
3511 if (c->client == client)
3513 /* client already on our list! */
3515 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3520 c = GNUNET_malloc (sizeof (struct TransportClient));
3524 if (our_hello != NULL)
3527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3528 "Sending our own `%s' to new client\n", "HELLO");
3530 transmit_to_client (c,
3531 (const struct GNUNET_MessageHeader *) our_hello,
3533 /* tell new client about all existing connections */
3534 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3535 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3539 if (GNUNET_YES == n->received_pong)
3542 cim.latency = GNUNET_TIME_relative_hton (n->latency);
3543 cim.distance = htonl (n->distance);
3544 transmit_to_client (c, &cim.header, GNUNET_NO);
3549 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3554 * Handle HELLO-message.
3556 * @param cls closure (always NULL)
3557 * @param client identification of the client
3558 * @param message the actual message
3561 handle_hello (void *cls,
3562 struct GNUNET_SERVER_Client *client,
3563 const struct GNUNET_MessageHeader *message)
3567 GNUNET_STATISTICS_update (stats,
3568 gettext_noop ("# HELLOs received from clients"),
3571 ret = process_hello (NULL, message);
3572 GNUNET_SERVER_receive_done (client, ret);
3577 * Handle SEND-message.
3579 * @param cls closure (always NULL)
3580 * @param client identification of the client
3581 * @param message the actual message
3584 handle_send (void *cls,
3585 struct GNUNET_SERVER_Client *client,
3586 const struct GNUNET_MessageHeader *message)
3588 struct TransportClient *tc;
3589 struct NeighbourList *n;
3590 const struct OutboundMessage *obm;
3591 const struct GNUNET_MessageHeader *obmm;
3595 size = ntohs (message->size);
3597 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3600 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3603 GNUNET_STATISTICS_update (stats,
3604 gettext_noop ("# payload received for other peers"),
3607 obm = (const struct OutboundMessage *) message;
3609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3610 "Received `%s' request from client with target `%4s'\n",
3611 "SEND", GNUNET_i2s (&obm->peer));
3613 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3614 msize = ntohs (obmm->size);
3615 if (size != msize + sizeof (struct OutboundMessage))
3618 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3621 n = find_neighbour (&obm->peer);
3623 n = setup_new_neighbour (&obm->peer);
3625 while ((tc != NULL) && (tc->client != client))
3629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3630 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3632 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3634 transmit_to_peer (tc, NULL, ntohl (obm->priority),
3635 GNUNET_TIME_relative_ntoh (obm->timeout),
3637 ntohs (obmm->size), GNUNET_NO, n);
3638 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3643 * Handle SET_QUOTA-message.
3645 * @param cls closure (always NULL)
3646 * @param client identification of the client
3647 * @param message the actual message
3650 handle_set_quota (void *cls,
3651 struct GNUNET_SERVER_Client *client,
3652 const struct GNUNET_MessageHeader *message)
3654 const struct QuotaSetMessage *qsm =
3655 (const struct QuotaSetMessage *) message;
3656 struct NeighbourList *n;
3658 GNUNET_STATISTICS_update (stats,
3659 gettext_noop ("# SET QUOTA messages received"),
3662 n = find_neighbour (&qsm->peer);
3665 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3666 GNUNET_STATISTICS_update (stats,
3667 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3673 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3674 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3676 (unsigned int) ntohl (qsm->quota.value__),
3677 (unsigned int) n->in_tracker.available_bytes_per_s__,
3678 GNUNET_i2s (&qsm->peer));
3680 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3682 if (0 == ntohl (qsm->quota.value__))
3683 disconnect_neighbour (n, GNUNET_NO);
3684 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3689 * Take the given address and append it to the set of results send back to
3692 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3693 * @param address the resolved name, NULL to indicate the last response
3696 transmit_address_to_client (void *cls, const char *address)
3698 struct GNUNET_SERVER_TransmitContext *tc = cls;
3701 if (NULL == address)
3704 slen = strlen (address) + 1;
3705 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3706 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3707 if (NULL == address)
3708 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3713 * Handle AddressLookup-message.
3715 * @param cls closure (always NULL)
3716 * @param client identification of the client
3717 * @param message the actual message
3720 handle_address_lookup (void *cls,
3721 struct GNUNET_SERVER_Client *client,
3722 const struct GNUNET_MessageHeader *message)
3724 const struct AddressLookupMessage *alum;
3725 struct TransportPlugin *lsPlugin;
3726 const char *nameTransport;
3727 const char *address;
3729 struct GNUNET_SERVER_TransmitContext *tc;
3730 struct GNUNET_TIME_Absolute timeout;
3731 struct GNUNET_TIME_Relative rtimeout;
3734 size = ntohs (message->size);
3735 if (size < sizeof (struct AddressLookupMessage))
3737 GNUNET_break_op (0);
3738 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3741 alum = (const struct AddressLookupMessage *) message;
3742 uint32_t addressLen = ntohl (alum->addrlen);
3743 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3745 GNUNET_break_op (0);
3746 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3749 address = (const char *) &alum[1];
3750 nameTransport = (const char *) &address[addressLen];
3752 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3754 GNUNET_break_op (0);
3755 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3758 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3759 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3760 numeric = ntohl (alum->numeric_only);
3761 lsPlugin = find_transport (nameTransport);
3762 if (NULL == lsPlugin)
3764 tc = GNUNET_SERVER_transmit_context_create (client);
3765 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3766 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3767 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3770 tc = GNUNET_SERVER_transmit_context_create (client);
3771 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
3773 address, addressLen,
3776 &transmit_address_to_client, tc);
3780 * List of handlers for the messages understood by this
3783 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3784 {&handle_start, NULL,
3785 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3786 {&handle_hello, NULL,
3787 GNUNET_MESSAGE_TYPE_HELLO, 0},
3788 {&handle_send, NULL,
3789 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3790 {&handle_set_quota, NULL,
3791 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3792 {&handle_address_lookup, NULL,
3793 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3800 * Setup the environment for this plugin.
3803 create_environment (struct TransportPlugin *plug)
3805 plug->env.cfg = cfg;
3806 plug->env.sched = sched;
3807 plug->env.my_identity = &my_identity;
3808 plug->env.cls = plug;
3809 plug->env.receive = &plugin_env_receive;
3810 plug->env.notify_address = &plugin_env_notify_address;
3811 plug->env.session_end = &plugin_env_session_end;
3812 plug->env.max_connections = max_connect_per_transport;
3813 plug->env.stats = stats;
3818 * Start the specified transport (load the plugin).
3821 start_transport (struct GNUNET_SERVER_Handle *server,
3824 struct TransportPlugin *plug;
3827 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3828 _("Loading `%s' transport plugin\n"), name);
3829 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3830 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3831 create_environment (plug);
3832 plug->short_name = GNUNET_strdup (name);
3833 plug->lib_name = libname;
3834 plug->next = plugins;
3836 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3837 if (plug->api == NULL)
3839 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3840 _("Failed to load transport plugin for `%s'\n"), name);
3841 GNUNET_free (plug->short_name);
3842 plugins = plug->next;
3843 GNUNET_free (libname);
3850 * Called whenever a client is disconnected. Frees our
3851 * resources associated with that client.
3853 * @param cls closure
3854 * @param client identification of the client
3857 client_disconnect_notification (void *cls,
3858 struct GNUNET_SERVER_Client *client)
3860 struct TransportClient *pos;
3861 struct TransportClient *prev;
3862 struct ClientMessageQueueEntry *mqe;
3867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3868 "Client disconnected, cleaning up.\n");
3872 while ((pos != NULL) && (pos->client != client))
3879 while (NULL != (mqe = pos->message_queue_head))
3881 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3882 pos->message_queue_tail,
3884 pos->message_count--;
3888 clients = pos->next;
3890 prev->next = pos->next;
3891 if (GNUNET_YES == pos->tcs_pending)
3896 if (pos->th != NULL)
3898 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3901 GNUNET_break (0 == pos->message_count);
3907 * Iterator to free entries in the validation_map.
3909 * @param cls closure (unused)
3910 * @param key current key code
3911 * @param value value in the hash map (validation to abort)
3912 * @return GNUNET_YES (always)
3915 abort_validation (void *cls,
3916 const GNUNET_HashCode * key,
3919 struct ValidationEntry *va = value;
3921 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3922 GNUNET_free (va->transport_name);
3929 * Function called when the service shuts down. Unloads our plugins
3930 * and cancels pending validations.
3932 * @param cls closure, unused
3933 * @param tc task context (unused)
3936 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3938 struct TransportPlugin *plug;
3939 struct OwnAddressList *al;
3940 struct CheckHelloValidatedContext *chvc;
3942 while (neighbours != NULL)
3943 disconnect_neighbour (neighbours, GNUNET_NO);
3945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3946 "Transport service is unloading plugins...\n");
3948 while (NULL != (plug = plugins))
3950 plugins = plug->next;
3951 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
3953 GNUNET_SCHEDULER_cancel (plug->env.sched,
3954 plug->address_update_task);
3955 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
3957 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3958 GNUNET_free (plug->lib_name);
3959 GNUNET_free (plug->short_name);
3960 while (NULL != (al = plug->addresses))
3962 plug->addresses = al->next;
3967 if (my_private_key != NULL)
3968 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3969 GNUNET_free_non_null (our_hello);
3971 /* free 'chvc' data structure */
3972 while (NULL != (chvc = chvc_head))
3974 chvc_head = chvc->next;
3975 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3980 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3983 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3984 validation_map = NULL;
3987 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3994 * Initiate transport service.
3996 * @param cls closure
3997 * @param s scheduler to use
3998 * @param serv the initialized server
3999 * @param c configuration to use
4003 struct GNUNET_SCHEDULER_Handle *s,
4004 struct GNUNET_SERVER_Handle *serv,
4005 const struct GNUNET_CONFIGURATION_Handle *c)
4010 unsigned long long tneigh;
4015 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4016 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4017 /* parse configuration */
4019 GNUNET_CONFIGURATION_get_value_number (c,
4024 GNUNET_CONFIGURATION_get_value_filename (c,
4026 "HOSTKEY", &keyfile)))
4028 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4030 ("Transport service is lacking key configuration settings. Exiting.\n"));
4031 GNUNET_SCHEDULER_shutdown (s);
4034 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4037 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4038 validation_map = NULL;
4041 max_connect_per_transport = (uint32_t) tneigh;
4042 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4043 GNUNET_free (keyfile);
4044 if (my_private_key == NULL)
4046 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4048 ("Transport service could not access hostkey. Exiting.\n"));
4049 GNUNET_SCHEDULER_shutdown (s);
4052 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4055 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4056 validation_map = NULL;
4059 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4060 GNUNET_CRYPTO_hash (&my_public_key,
4061 sizeof (my_public_key), &my_identity.hashPubKey);
4062 /* setup notification */
4064 GNUNET_SERVER_disconnect_notify (server,
4065 &client_disconnect_notification, NULL);
4066 /* load plugins... */
4069 GNUNET_CONFIGURATION_get_value_string (c,
4070 "TRANSPORT", "PLUGINS", &plugs))
4072 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4073 _("Starting transport plugins `%s'\n"), plugs);
4074 pos = strtok (plugs, " ");
4077 start_transport (server, pos);
4079 pos = strtok (NULL, " ");
4081 GNUNET_free (plugs);
4083 GNUNET_SCHEDULER_add_delayed (sched,
4084 GNUNET_TIME_UNIT_FOREVER_REL,
4085 &shutdown_task, NULL);
4090 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
4092 /* process client requests */
4093 GNUNET_SERVER_add_handlers (server, handlers);
4098 * The main function for the transport service.
4100 * @param argc number of arguments from the command line
4101 * @param argv command line arguments
4102 * @return 0 ok, 1 on error
4105 main (int argc, char *const *argv)
4107 return (GNUNET_OK ==
4108 GNUNET_SERVICE_run (argc,
4111 GNUNET_SERVICE_OPTION_NONE,
4112 &run, NULL)) ? 0 : 1;
4115 /* end of gnunet-service-transport.c */