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;
1751 if (nl->received_pong == GNUNET_NO)
1752 return; /* nothing to do */
1753 /* check if we have any validated addresses left */
1754 pos = rl->addresses;
1761 /* no valid addresses left, signal disconnect! */
1762 disconnect_neighbour (nl, GNUNET_NO);
1767 * Function that must be called by each plugin to notify the
1768 * transport service about the addresses under which the transport
1769 * provided by the plugin can be reached.
1771 * @param cls closure
1772 * @param name name of the transport that generated the address
1773 * @param addr one of the addresses of the host, NULL for the last address
1774 * the specific address format depends on the transport
1775 * @param addrlen length of the address
1776 * @param expires when should this address automatically expire?
1779 plugin_env_notify_address (void *cls,
1783 struct GNUNET_TIME_Relative expires)
1785 struct TransportPlugin *p = cls;
1786 struct OwnAddressList *al;
1787 struct GNUNET_TIME_Absolute abex;
1789 GNUNET_assert (addr != NULL);
1790 abex = GNUNET_TIME_relative_to_absolute (expires);
1791 GNUNET_assert (p == find_transport (name));
1795 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1797 if (al->expires.value < abex.value)
1804 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1806 al->next = p->addresses;
1809 al->addrlen = addrlen;
1810 memcpy (&al[1], addr, addrlen);
1811 update_addresses (p, GNUNET_YES);
1816 * Notify all of our clients about a peer connecting.
1819 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1820 struct GNUNET_TIME_Relative latency,
1823 struct ConnectInfoMessage cim;
1824 struct TransportClient *cpos;
1827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1828 "Notifying clients about connection from `%s'\n",
1831 GNUNET_STATISTICS_update (stats,
1832 gettext_noop ("# peers connected"),
1835 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1836 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1837 cim.distance = htonl (distance);
1838 cim.latency = GNUNET_TIME_relative_hton (latency);
1839 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1841 while (cpos != NULL)
1843 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1850 * Notify all of our clients about a peer disconnecting.
1853 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1855 struct DisconnectInfoMessage dim;
1856 struct TransportClient *cpos;
1859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1860 "Notifying clients about lost connection to `%s'\n",
1863 GNUNET_STATISTICS_update (stats,
1864 gettext_noop ("# peers connected"),
1867 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1868 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1869 dim.reserved = htonl (0);
1870 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1872 while (cpos != NULL)
1874 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1881 * Find a ForeignAddressList entry for the given neighbour
1882 * that matches the given address and transport.
1884 * @param neighbour which peer we care about
1885 * @param tname name of the transport plugin
1886 * @param session session to look for, NULL for 'any'; otherwise
1887 * can be used for the service to "learn" this session ID
1889 * @param addr binary address
1890 * @param addrlen length of addr
1891 * @return NULL if no such entry exists
1893 static struct ForeignAddressList *
1894 find_peer_address(struct NeighbourList *neighbour,
1896 struct Session *session,
1900 struct ReadyList *head;
1901 struct ForeignAddressList *pos;
1903 head = neighbour->plugins;
1904 while (head != NULL)
1906 if (0 == strcmp (tname, head->plugin->short_name))
1912 pos = head->addresses;
1913 while ( (pos != NULL) &&
1914 ( (pos->addrlen != addrlen) ||
1915 (memcmp(pos->addr, addr, addrlen) != 0) ) )
1917 if ( (session != NULL) &&
1918 (pos->session == session) )
1922 if ( (session != NULL) && (pos != NULL) )
1923 pos->session = session; /* learn it! */
1929 * Get the peer address struct for the given neighbour and
1930 * address. If it doesn't yet exist, create it.
1932 * @param neighbour which peer we care about
1933 * @param tname name of the transport plugin
1934 * @param session session of the plugin, or NULL for none
1935 * @param addr binary address
1936 * @param addrlen length of addr
1937 * @return NULL if we do not have a transport plugin for 'tname'
1939 static struct ForeignAddressList *
1940 add_peer_address (struct NeighbourList *neighbour,
1942 struct Session *session,
1946 struct ReadyList *head;
1947 struct ForeignAddressList *ret;
1949 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
1952 head = neighbour->plugins;
1953 while (head != NULL)
1955 if (0 == strcmp (tname, head->plugin->short_name))
1961 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1962 ret->session = session;
1965 ret->addr = (const char*) &ret[1];
1966 memcpy (&ret[1], addr, addrlen);
1972 ret->addrlen = addrlen;
1973 ret->expires = GNUNET_TIME_relative_to_absolute
1974 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1975 ret->latency = GNUNET_TIME_relative_get_forever();
1977 ret->timeout = GNUNET_TIME_relative_to_absolute
1978 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1979 ret->ready_list = head;
1980 ret->next = head->addresses;
1981 head->addresses = ret;
1987 * Closure for 'add_validated_address'.
1989 struct AddValidatedAddressContext
1992 * Entry that has been validated.
1994 const struct ValidationEntry *ve;
1997 * Flag set after we have added the address so
1998 * that we terminate the iteration next time.
2005 * Callback function used to fill a buffer of max bytes with a list of
2006 * addresses in the format used by HELLOs. Should use
2007 * "GNUNET_HELLO_add_address" as a helper function.
2009 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2010 * @param max maximum number of bytes that can be written to buf
2011 * @param buf where to write the address information
2012 * @return number of bytes written, 0 to signal the
2013 * end of the iteration.
2016 add_validated_address (void *cls,
2017 size_t max, void *buf)
2019 struct AddValidatedAddressContext *avac = cls;
2020 const struct ValidationEntry *ve = avac->ve;
2022 if (GNUNET_YES == avac->done)
2024 avac->done = GNUNET_YES;
2025 return GNUNET_HELLO_add_address (ve->transport_name,
2026 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2036 * Closure for 'check_address_exists'.
2038 struct CheckAddressExistsClosure
2041 * Address to check for.
2046 * Name of the transport.
2053 struct Session *session;
2061 * Set to GNUNET_YES if the address exists.
2068 * Iterator over hash map entries. Checks if the given
2069 * validation entry is for the same address as what is given
2072 * @param cls the 'struct CheckAddressExistsClosure*'
2073 * @param key current key code (ignored)
2074 * @param value value in the hash map ('struct ValidationEntry')
2075 * @return GNUNET_YES if we should continue to
2076 * iterate (mismatch), GNUNET_NO if not (entry matched)
2079 check_address_exists (void *cls,
2080 const GNUNET_HashCode * key,
2083 struct CheckAddressExistsClosure *caec = cls;
2084 struct ValidationEntry *ve = value;
2086 if ( (0 == strcmp (caec->tname,
2087 ve->transport_name)) &&
2088 (caec->addrlen == ve->addrlen) &&
2089 (0 == memcmp (caec->addr,
2093 caec->exists = GNUNET_YES;
2096 if ( (ve->session != NULL) &&
2097 (caec->session == ve->session) )
2099 caec->exists = GNUNET_YES;
2107 * HELLO validation cleanup task (validation failed).
2109 * @param cls the 'struct ValidationEntry' that failed
2110 * @param tc scheduler context (unused)
2113 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2115 struct ValidationEntry *va = cls;
2116 struct GNUNET_PeerIdentity pid;
2118 GNUNET_STATISTICS_update (stats,
2119 gettext_noop ("# address validation timeouts"),
2122 GNUNET_CRYPTO_hash (&va->publicKey,
2124 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2126 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2129 GNUNET_free (va->transport_name);
2135 neighbour_timeout_task (void *cls,
2136 const struct GNUNET_SCHEDULER_TaskContext *tc)
2138 struct NeighbourList *n = cls;
2141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2142 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2144 GNUNET_STATISTICS_update (stats,
2145 gettext_noop ("# disconnects due to timeout"),
2148 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2149 disconnect_neighbour (n, GNUNET_NO);
2154 * Schedule the job that will cause us to send a PING to the
2155 * foreign address to evaluate its validity and latency.
2157 * @param fal address to PING
2160 schedule_next_ping (struct ForeignAddressList *fal);
2164 * Add the given address to the list of foreign addresses
2165 * available for the given peer (check for duplicates).
2167 * @param cls the respective 'struct NeighbourList' to update
2168 * @param tname name of the transport
2169 * @param expiration expiration time
2170 * @param addr the address
2171 * @param addrlen length of the address
2172 * @return GNUNET_OK (always)
2175 add_to_foreign_address_list (void *cls,
2177 struct GNUNET_TIME_Absolute expiration,
2178 const void *addr, size_t addrlen)
2180 struct NeighbourList *n = cls;
2181 struct ForeignAddressList *fal;
2184 GNUNET_STATISTICS_update (stats,
2185 gettext_noop ("# valid peer addresses returned by peerinfo"),
2189 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2195 GNUNET_a2s (addr, addrlen),
2197 GNUNET_i2s (&n->id),
2200 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2203 GNUNET_STATISTICS_update (stats,
2204 gettext_noop ("# previously validated addresses lacking transport"),
2210 fal->expires = GNUNET_TIME_absolute_max (expiration,
2212 schedule_next_ping (fal);
2218 fal->expires = GNUNET_TIME_absolute_max (expiration,
2223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2224 "Failed to add new address for `%4s'\n",
2225 GNUNET_i2s (&n->id));
2228 if (fal->validated == GNUNET_NO)
2230 fal->validated = GNUNET_YES;
2231 GNUNET_STATISTICS_update (stats,
2232 gettext_noop ("# peer addresses considered valid"),
2236 if (try == GNUNET_YES)
2238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2239 "Have new addresses, will try to trigger transmissions.\n");
2240 try_transmission_to_peer (n);
2247 * Add addresses in validated HELLO "h" to the set of addresses
2248 * we have for this peer.
2250 * @param cls closure ('struct NeighbourList*')
2251 * @param peer id of the peer, NULL for last call
2252 * @param h hello message for the peer (can be NULL)
2253 * @param trust amount of trust we have in the peer (not used)
2256 add_hello_for_peer (void *cls,
2257 const struct GNUNET_PeerIdentity *peer,
2258 const struct GNUNET_HELLO_Message *h,
2261 struct NeighbourList *n = cls;
2269 return; /* no HELLO available */
2271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2272 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2276 if (GNUNET_YES != n->public_key_valid)
2278 GNUNET_HELLO_get_key (h, &n->publicKey);
2279 n->public_key_valid = GNUNET_YES;
2281 GNUNET_HELLO_iterate_addresses (h,
2283 &add_to_foreign_address_list,
2289 * Create a fresh entry in our neighbour list for the given peer.
2290 * Will try to transmit our current HELLO to the new neighbour.
2292 * @param peer the peer for which we create the entry
2293 * @return the new neighbour list entry
2295 static struct NeighbourList *
2296 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2298 struct NeighbourList *n;
2299 struct TransportPlugin *tp;
2300 struct ReadyList *rl;
2302 GNUNET_assert (our_hello != NULL);
2303 GNUNET_STATISTICS_update (stats,
2304 gettext_noop ("# active neighbours"),
2307 n = GNUNET_malloc (sizeof (struct NeighbourList));
2308 n->next = neighbours;
2312 GNUNET_TIME_relative_to_absolute
2313 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2314 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2315 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2316 MAX_BANDWIDTH_CARRY_S);
2320 if (tp->api->send != NULL)
2322 rl = GNUNET_malloc (sizeof (struct ReadyList));
2324 rl->next = n->plugins;
2327 rl->addresses = NULL;
2331 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2333 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2334 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2335 &neighbour_timeout_task, n);
2336 n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2337 0, GNUNET_TIME_UNIT_FOREVER_REL,
2338 &add_hello_for_peer, n);
2339 transmit_to_peer (NULL, NULL, 0,
2340 HELLO_ADDRESS_EXPIRATION,
2341 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2348 * Send periodic PING messages to a give foreign address.
2350 * @param cls our 'struct PeriodicValidationContext*'
2351 * @param tc task context
2354 send_periodic_ping (void *cls,
2355 const struct GNUNET_SCHEDULER_TaskContext *tc)
2357 struct ForeignAddressList *peer_address = cls;
2358 struct TransportPlugin *tp;
2359 struct ValidationEntry *va;
2360 struct NeighbourList *neighbour;
2361 struct TransportPingMessage ping;
2362 struct CheckAddressExistsClosure caec;
2364 uint16_t hello_size;
2367 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2368 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2370 tp = peer_address->ready_list->plugin;
2371 neighbour = peer_address->ready_list->neighbour;
2372 if (GNUNET_YES != neighbour->public_key_valid)
2374 /* no public key yet, try again later */
2375 schedule_next_ping (peer_address);
2378 caec.addr = peer_address->addr;
2379 caec.addrlen = peer_address->addrlen;
2380 caec.tname = tp->short_name;
2381 caec.session = peer_address->session;
2382 caec.exists = GNUNET_NO;
2383 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2384 &check_address_exists,
2386 if (caec.exists == GNUNET_YES)
2388 /* During validation attempts we will likely trigger the other
2389 peer trying to validate our address which in turn will cause
2390 it to send us its HELLO, so we expect to hit this case rather
2391 frequently. Only print something if we are very verbose. */
2392 #if DEBUG_TRANSPORT > 1
2393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2395 (peer_address->addr != NULL)
2396 ? GNUNET_a2s (peer_address->addr,
2397 peer_address->addrlen)
2400 GNUNET_i2s (&neighbour->id));
2402 schedule_next_ping (peer_address);
2405 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2406 va->transport_name = GNUNET_strdup (tp->short_name);
2407 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2409 va->send_time = GNUNET_TIME_absolute_get();
2410 va->session = peer_address->session;
2411 if (peer_address->addr != NULL)
2413 va->addr = (const void*) &va[1];
2414 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2415 va->addrlen = peer_address->addrlen;
2417 memcpy(&va->publicKey,
2418 &neighbour->publicKey,
2419 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2421 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2422 HELLO_VERIFICATION_TIMEOUT,
2423 &timeout_hello_validation,
2425 GNUNET_CONTAINER_multihashmap_put (validation_map,
2426 &neighbour->id.hashPubKey,
2428 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2429 hello_size = GNUNET_HELLO_size(our_hello);
2430 tsize = sizeof(struct TransportPingMessage) + hello_size;
2431 message_buf = GNUNET_malloc(tsize);
2432 ping.challenge = htonl(va->challenge);
2433 ping.header.size = htons(sizeof(struct TransportPingMessage));
2434 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2435 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2436 memcpy(message_buf, our_hello, hello_size);
2437 memcpy(&message_buf[hello_size],
2439 sizeof(struct TransportPingMessage));
2440 #if DEBUG_TRANSPORT_REVALIDATION
2441 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2443 (peer_address->addr != NULL)
2444 ? GNUNET_a2s (peer_address->addr,
2445 peer_address->addrlen)
2448 GNUNET_i2s (&neighbour->id),
2449 "HELLO", hello_size,
2450 "PING", sizeof (struct TransportPingMessage));
2452 GNUNET_STATISTICS_update (stats,
2453 gettext_noop ("# PING messages sent for re-validation"),
2456 transmit_to_peer (NULL, peer_address,
2457 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2458 HELLO_VERIFICATION_TIMEOUT,
2460 GNUNET_YES, neighbour);
2461 GNUNET_free(message_buf);
2462 schedule_next_ping (peer_address);
2467 * Schedule the job that will cause us to send a PING to the
2468 * foreign address to evaluate its validity and latency.
2470 * @param fal address to PING
2473 schedule_next_ping (struct ForeignAddressList *fal)
2475 struct GNUNET_TIME_Relative delay;
2477 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2479 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2480 delay.value /= 2; /* do before expiration */
2481 delay = GNUNET_TIME_relative_min (delay,
2482 LATENCY_EVALUATION_MAX_DELAY);
2483 if (GNUNET_YES != fal->estimated)
2485 delay = GNUNET_TIME_UNIT_ZERO;
2486 fal->estimated = GNUNET_YES;
2488 if (GNUNET_YES == fal->connected)
2490 delay = GNUNET_TIME_relative_min (delay,
2491 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2493 /* FIXME: also adjust delay based on how close the last
2494 observed latency is to the latency of the best alternative */
2495 /* bound how fast we can go */
2496 delay = GNUNET_TIME_relative_max (delay,
2497 GNUNET_TIME_UNIT_SECONDS);
2498 /* randomize a bit (to avoid doing all at the same time) */
2499 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2500 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
2502 &send_periodic_ping,
2510 * Function that will be called if we receive some payload
2511 * from another peer.
2513 * @param message the payload
2514 * @param n peer who claimed to be the sender
2517 handle_payload_message (const struct GNUNET_MessageHeader *message,
2518 struct NeighbourList *n)
2520 struct InboundMessage *im;
2521 struct TransportClient *cpos;
2524 msize = ntohs (message->size);
2525 if (n->received_pong == GNUNET_NO)
2527 GNUNET_free_non_null (n->pre_connect_message_buffer);
2528 n->pre_connect_message_buffer = GNUNET_malloc (msize);
2529 memcpy (n->pre_connect_message_buffer, message, msize);
2533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534 "Received message of type %u from `%4s', sending to all clients.\n",
2535 ntohs (message->type),
2536 GNUNET_i2s (&n->id));
2538 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2541 n->quota_violation_count++;
2543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2544 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
2545 n->in_tracker.available_bytes_per_s__,
2546 n->quota_violation_count);
2548 /* Discount 32k per violation */
2549 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2554 if (n->quota_violation_count > 0)
2556 /* try to add 32k back */
2557 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2559 n->quota_violation_count--;
2562 GNUNET_STATISTICS_update (stats,
2563 gettext_noop ("# payload received from other peers"),
2566 /* transmit message to all clients */
2567 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2568 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2569 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2570 im->latency = GNUNET_TIME_relative_hton (n->latency);
2572 memcpy (&im[1], message, msize);
2574 while (cpos != NULL)
2576 transmit_to_client (cpos, &im->header, GNUNET_YES);
2584 * Iterator over hash map entries. Checks if the given validation
2585 * entry is for the same challenge as what is given in the PONG.
2587 * @param cls the 'struct TransportPongMessage*'
2588 * @param key peer identity
2589 * @param value value in the hash map ('struct ValidationEntry')
2590 * @return GNUNET_YES if we should continue to
2591 * iterate (mismatch), GNUNET_NO if not (entry matched)
2594 check_pending_validation (void *cls,
2595 const GNUNET_HashCode * key,
2598 const struct TransportPongMessage *pong = cls;
2599 struct ValidationEntry *ve = value;
2600 struct AddValidatedAddressContext avac;
2601 unsigned int challenge = ntohl(pong->challenge);
2602 struct GNUNET_HELLO_Message *hello;
2603 struct GNUNET_PeerIdentity target;
2604 struct NeighbourList *n;
2605 struct ForeignAddressList *fal;
2606 struct GNUNET_MessageHeader *prem;
2608 if (ve->challenge != challenge)
2611 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING,
2616 GNUNET_break_op (0);
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2625 ? GNUNET_a2s ((const struct sockaddr *) ve->addr,
2628 ve->transport_name);
2630 GNUNET_STATISTICS_update (stats,
2631 gettext_noop ("# address validation successes"),
2634 /* create the updated HELLO */
2635 GNUNET_CRYPTO_hash (&ve->publicKey,
2636 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2637 &target.hashPubKey);
2638 if (ve->addr != NULL)
2640 avac.done = GNUNET_NO;
2642 hello = GNUNET_HELLO_create (&ve->publicKey,
2643 &add_validated_address,
2645 GNUNET_PEERINFO_add_peer (cfg, sched,
2648 GNUNET_free (hello);
2650 n = find_neighbour (&target);
2653 n->publicKey = ve->publicKey;
2654 n->public_key_valid = GNUNET_YES;
2655 fal = add_peer_address (n,
2660 GNUNET_assert (fal != NULL);
2661 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2662 fal->validated = GNUNET_YES;
2663 mark_address_connected (fal);
2664 GNUNET_STATISTICS_update (stats,
2665 gettext_noop ("# peer addresses considered valid"),
2668 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2669 schedule_next_ping (fal);
2670 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2671 n->latency = fal->latency;
2673 n->latency.value = (fal->latency.value + n->latency.value) / 2;
2674 n->distance = fal->distance;
2675 if (GNUNET_NO == n->received_pong)
2677 n->received_pong = GNUNET_YES;
2678 notify_clients_connect (&target, n->latency, n->distance);
2679 if (NULL != (prem = n->pre_connect_message_buffer))
2681 n->pre_connect_message_buffer = NULL;
2682 handle_payload_message (prem, n);
2686 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2688 GNUNET_SCHEDULER_cancel (sched,
2690 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2691 try_transmission_to_peer (n);
2695 /* clean up validation entry */
2696 GNUNET_assert (GNUNET_YES ==
2697 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2700 GNUNET_SCHEDULER_cancel (sched,
2702 GNUNET_free (ve->transport_name);
2709 * Function that will be called if we receive a validation
2710 * of an address challenge that we transmitted to another
2711 * peer. Note that the validation should only be considered
2712 * acceptable if the challenge matches AND if the sender
2713 * address is at least a plausible address for this peer
2714 * (otherwise we may be seeing a MiM attack).
2716 * @param cls closure
2717 * @param message the pong message
2718 * @param peer who responded to our challenge
2719 * @param sender_address string describing our sender address (as observed
2720 * by the other peer in binary format)
2721 * @param sender_address_len number of bytes in 'sender_address'
2724 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2725 const struct GNUNET_PeerIdentity *peer,
2726 const char *sender_address,
2727 size_t sender_address_len)
2729 #if DEBUG_TRANSPORT > 1
2730 /* we get tons of these that just get discarded, only log
2731 if we are quite verbose */
2732 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2733 "Receiving `%s' message from `%4s'.\n", "PONG",
2736 GNUNET_STATISTICS_update (stats,
2737 gettext_noop ("# PONG messages received"),
2740 if (GNUNET_SYSERR !=
2741 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2743 &check_pending_validation,
2746 /* This is *expected* to happen a lot since we send
2747 PONGs to *all* known addresses of the sender of
2748 the PING, so most likely we get multiple PONGs
2749 per PING, and all but the first PONG will end up
2750 here. So really we should not print anything here
2751 unless we want to be very, very verbose... */
2752 #if DEBUG_TRANSPORT > 2
2753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2754 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2763 /* FIXME: add given address to potential pool of our addresses
2765 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2766 _("Another peer saw us using the address `%s' via `%s'.\n"),
2767 GNUNET_a2s ((const struct sockaddr *) &pong[1],
2768 ntohs(pong->addrlen)),
2769 va->transport_name);
2775 * Check if the given address is already being validated; if not,
2776 * append the given address to the list of entries that are being be
2777 * validated and initiate validation.
2779 * @param cls closure ('struct CheckHelloValidatedContext *')
2780 * @param tname name of the transport
2781 * @param expiration expiration time
2782 * @param addr the address
2783 * @param addrlen length of the address
2784 * @return GNUNET_OK (always)
2787 run_validation (void *cls,
2789 struct GNUNET_TIME_Absolute expiration,
2790 const void *addr, size_t addrlen)
2792 struct CheckHelloValidatedContext *chvc = cls;
2793 struct GNUNET_PeerIdentity id;
2794 struct TransportPlugin *tp;
2795 struct ValidationEntry *va;
2796 struct NeighbourList *neighbour;
2797 struct ForeignAddressList *peer_address;
2798 struct TransportPingMessage ping;
2799 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2800 struct CheckAddressExistsClosure caec;
2802 uint16_t hello_size;
2805 GNUNET_assert (addr != NULL);
2806 GNUNET_STATISTICS_update (stats,
2807 gettext_noop ("# peer addresses scheduled for validation"),
2810 tp = find_transport (tname);
2813 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2814 GNUNET_ERROR_TYPE_BULK,
2816 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2818 GNUNET_STATISTICS_update (stats,
2819 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2824 GNUNET_HELLO_get_key (chvc->hello, &pk);
2825 GNUNET_CRYPTO_hash (&pk,
2827 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2830 caec.addrlen = addrlen;
2832 caec.exists = GNUNET_NO;
2833 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2834 &check_address_exists,
2836 if (caec.exists == GNUNET_YES)
2838 /* During validation attempts we will likely trigger the other
2839 peer trying to validate our address which in turn will cause
2840 it to send us its HELLO, so we expect to hit this case rather
2841 frequently. Only print something if we are very verbose. */
2842 #if DEBUG_TRANSPORT > 1
2843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2844 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2845 GNUNET_a2s (addr, addrlen),
2849 GNUNET_STATISTICS_update (stats,
2850 gettext_noop ("# peer addresses not validated (in progress)"),
2855 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2856 va->transport_name = GNUNET_strdup (tname);
2857 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2859 va->send_time = GNUNET_TIME_absolute_get();
2860 va->addr = (const void*) &va[1];
2861 memcpy (&va[1], addr, addrlen);
2862 va->addrlen = addrlen;
2863 GNUNET_HELLO_get_key (chvc->hello,
2865 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2866 HELLO_VERIFICATION_TIMEOUT,
2867 &timeout_hello_validation,
2869 GNUNET_CONTAINER_multihashmap_put (validation_map,
2872 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2873 neighbour = find_neighbour(&id);
2874 if (neighbour == NULL)
2875 neighbour = setup_new_neighbour(&id);
2876 neighbour->publicKey = va->publicKey;
2877 neighbour->public_key_valid = GNUNET_YES;
2878 peer_address = add_peer_address (neighbour, tname, NULL, addr, addrlen);
2879 GNUNET_assert(peer_address != NULL);
2880 hello_size = GNUNET_HELLO_size(our_hello);
2881 tsize = sizeof(struct TransportPingMessage) + hello_size;
2882 message_buf = GNUNET_malloc(tsize);
2883 ping.challenge = htonl(va->challenge);
2884 ping.header.size = htons(sizeof(struct TransportPingMessage));
2885 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2886 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2887 memcpy(message_buf, our_hello, hello_size);
2888 memcpy(&message_buf[hello_size],
2890 sizeof(struct TransportPingMessage));
2892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2893 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2894 GNUNET_a2s (addr, addrlen),
2897 "HELLO", hello_size,
2898 "PING", sizeof (struct TransportPingMessage));
2900 GNUNET_STATISTICS_update (stats,
2901 gettext_noop ("# PING messages sent for initial validation"),
2904 transmit_to_peer (NULL, peer_address,
2905 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2906 HELLO_VERIFICATION_TIMEOUT,
2908 GNUNET_YES, neighbour);
2909 GNUNET_free(message_buf);
2915 * Check if addresses in validated hello "h" overlap with
2916 * those in "chvc->hello" and validate the rest.
2918 * @param cls closure
2919 * @param peer id of the peer, NULL for last call
2920 * @param h hello message for the peer (can be NULL)
2921 * @param trust amount of trust we have in the peer (not used)
2924 check_hello_validated (void *cls,
2925 const struct GNUNET_PeerIdentity *peer,
2926 const struct GNUNET_HELLO_Message *h,
2929 struct CheckHelloValidatedContext *chvc = cls;
2930 struct GNUNET_HELLO_Message *plain_hello;
2931 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2932 struct GNUNET_PeerIdentity target;
2933 struct NeighbourList *n;
2938 GNUNET_CONTAINER_DLL_remove (chvc_head,
2941 if (GNUNET_NO == chvc->hello_known)
2943 /* notify PEERINFO about the peer now, so that we at least
2944 have the public key if some other component needs it */
2945 GNUNET_HELLO_get_key (chvc->hello, &pk);
2946 GNUNET_CRYPTO_hash (&pk,
2947 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2948 &target.hashPubKey);
2949 plain_hello = GNUNET_HELLO_create (&pk,
2952 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2953 GNUNET_free (plain_hello);
2955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2958 GNUNET_i2s (&target));
2960 GNUNET_STATISTICS_update (stats,
2961 gettext_noop ("# new HELLOs requiring full validation"),
2964 GNUNET_HELLO_iterate_addresses (chvc->hello,
2971 GNUNET_STATISTICS_update (stats,
2972 gettext_noop ("# duplicate HELLO (peer known)"),
2982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2983 "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2987 chvc->hello_known = GNUNET_YES;
2988 n = find_neighbour (peer);
2991 GNUNET_HELLO_iterate_addresses (h,
2993 &add_to_foreign_address_list,
2995 try_transmission_to_peer (n);
2999 GNUNET_STATISTICS_update (stats,
3000 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3004 GNUNET_STATISTICS_update (stats,
3005 gettext_noop ("# HELLO validations (update case)"),
3008 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3010 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3016 * Process HELLO-message.
3018 * @param plugin transport involved, may be NULL
3019 * @param message the actual message
3020 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3023 process_hello (struct TransportPlugin *plugin,
3024 const struct GNUNET_MessageHeader *message)
3027 struct GNUNET_PeerIdentity target;
3028 const struct GNUNET_HELLO_Message *hello;
3029 struct CheckHelloValidatedContext *chvc;
3030 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3032 hsize = ntohs (message->size);
3033 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3034 (hsize < sizeof (struct GNUNET_MessageHeader)))
3037 return GNUNET_SYSERR;
3039 GNUNET_STATISTICS_update (stats,
3040 gettext_noop ("# HELLOs received for validation"),
3043 /* first, check if load is too high */
3044 if (GNUNET_SCHEDULER_get_load (sched,
3045 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3047 GNUNET_STATISTICS_update (stats,
3048 gettext_noop ("# HELLOs ignored due to high load"),
3053 hello = (const struct GNUNET_HELLO_Message *) message;
3054 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3056 GNUNET_break_op (0);
3057 return GNUNET_SYSERR;
3059 GNUNET_CRYPTO_hash (&publicKey,
3060 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3061 &target.hashPubKey);
3062 if (0 == memcmp (&my_identity,
3064 sizeof (struct GNUNET_PeerIdentity)))
3066 GNUNET_STATISTICS_update (stats,
3067 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3072 #if DEBUG_TRANSPORT > 1
3073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3074 "Processing `%s' message for `%4s' of size %u\n",
3076 GNUNET_i2s (&target),
3077 GNUNET_HELLO_size(hello));
3079 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3080 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3081 memcpy (&chvc[1], hello, hsize);
3082 GNUNET_CONTAINER_DLL_insert (chvc_head,
3085 /* finally, check if HELLO was previously validated
3086 (continuation will then schedule actual validation) */
3087 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
3091 HELLO_VERIFICATION_TIMEOUT,
3092 &check_hello_validated, chvc);
3098 * The peer specified by the given neighbour has timed-out or a plugin
3099 * has disconnected. We may either need to do nothing (other plugins
3100 * still up), or trigger a full disconnect and clean up. This
3101 * function updates our state and does the necessary notifications.
3102 * Also notifies our clients that the neighbour is now officially
3105 * @param n the neighbour list entry for the peer
3106 * @param check should we just check if all plugins
3107 * disconnected or must we ask all plugins to
3111 disconnect_neighbour (struct NeighbourList *n, int check)
3113 struct ReadyList *rpos;
3114 struct NeighbourList *npos;
3115 struct NeighbourList *nprev;
3116 struct MessageQueue *mq;
3117 struct ForeignAddressList *peer_addresses;
3118 struct ForeignAddressList *peer_pos;
3120 if (GNUNET_YES == check)
3123 while (NULL != rpos)
3125 peer_addresses = rpos->addresses;
3126 while (peer_addresses != NULL)
3128 if (GNUNET_YES == peer_addresses->connected)
3129 return; /* still connected */
3130 peer_addresses = peer_addresses->next;
3136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3137 "Disconnecting from `%4s'\n",
3138 GNUNET_i2s (&n->id));
3140 /* remove n from neighbours list */
3143 while ((npos != NULL) && (npos != n))
3148 GNUNET_assert (npos != NULL);
3150 neighbours = n->next;
3152 nprev->next = n->next;
3154 /* notify all clients about disconnect */
3155 if (GNUNET_YES == n->received_pong)
3156 notify_clients_disconnect (&n->id);
3158 /* clean up all plugins, cancel connections and pending transmissions */
3159 while (NULL != (rpos = n->plugins))
3161 n->plugins = rpos->next;
3162 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3163 while (rpos->addresses != NULL)
3165 peer_pos = rpos->addresses;
3166 rpos->addresses = peer_pos->next;
3167 if (peer_pos->connected == GNUNET_YES)
3168 GNUNET_STATISTICS_update (stats,
3169 gettext_noop ("# connected addresses"),
3172 if (GNUNET_YES == peer_pos->validated)
3173 GNUNET_STATISTICS_update (stats,
3174 gettext_noop ("# peer addresses considered valid"),
3177 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3179 GNUNET_SCHEDULER_cancel (sched,
3180 peer_pos->revalidate_task);
3181 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3183 GNUNET_free(peer_pos);
3188 /* free all messages on the queue */
3189 while (NULL != (mq = n->messages_head))
3191 GNUNET_STATISTICS_update (stats,
3192 gettext_noop ("# bytes in message queue for other peers"),
3193 - (int64_t) mq->message_buf_size,
3195 GNUNET_STATISTICS_update (stats,
3196 gettext_noop ("# bytes discarded due to disconnect"),
3197 mq->message_buf_size,
3199 GNUNET_CONTAINER_DLL_remove (n->messages_head,
3202 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
3204 sizeof(struct GNUNET_PeerIdentity)));
3207 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
3209 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
3210 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3212 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3214 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
3215 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3217 if (n->piter != NULL)
3219 GNUNET_PEERINFO_iterate_cancel (n->piter);
3222 /* finally, free n itself */
3223 GNUNET_STATISTICS_update (stats,
3224 gettext_noop ("# active neighbours"),
3227 GNUNET_free_non_null (n->pre_connect_message_buffer);
3233 * We have received a PING message from someone. Need to send a PONG message
3234 * in response to the peer by any means necessary.
3237 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
3238 const struct GNUNET_PeerIdentity *peer,
3239 const char *sender_address,
3240 size_t sender_address_len)
3242 struct TransportPlugin *plugin = cls;
3243 struct TransportPingMessage *ping;
3244 struct TransportPongMessage *pong;
3245 struct NeighbourList *n;
3246 struct ReadyList *rl;
3247 struct ForeignAddressList *fal;
3249 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
3251 GNUNET_break_op (0);
3252 return GNUNET_SYSERR;
3254 ping = (struct TransportPingMessage *) message;
3255 if (0 != memcmp (&ping->target,
3256 plugin->env.my_identity,
3257 sizeof (struct GNUNET_PeerIdentity)))
3259 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3260 _("Received `%s' message not destined for me!\n"),
3262 return GNUNET_SYSERR;
3265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3266 "Processing `%s' from `%s'\n",
3268 GNUNET_a2s ((const struct sockaddr *)sender_address,
3269 sender_address_len));
3271 GNUNET_STATISTICS_update (stats,
3272 gettext_noop ("# PING messages received"),
3275 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
3276 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
3277 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
3278 pong->purpose.size =
3279 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3281 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
3282 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
3283 pong->challenge = ping->challenge;
3284 pong->addrlen = htons(sender_address_len);
3285 memcpy(&pong->signer,
3287 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3288 memcpy (&pong[1], sender_address, sender_address_len);
3289 GNUNET_assert (GNUNET_OK ==
3290 GNUNET_CRYPTO_rsa_sign (my_private_key,
3291 &pong->purpose, &pong->signature));
3292 n = find_neighbour(peer);
3293 GNUNET_assert (n != NULL);
3294 /* first try reliable response transmission */
3298 fal = rl->addresses;
3301 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3304 ntohs (pong->header.size),
3305 TRANSPORT_PONG_PRIORITY,
3306 HELLO_VERIFICATION_TIMEOUT,
3314 GNUNET_STATISTICS_update (stats,
3315 gettext_noop ("# PONGs unicast via reliable transport"),
3325 /* no reliable method found, do multicast */
3326 GNUNET_STATISTICS_update (stats,
3327 gettext_noop ("# PONGs multicast to all available addresses"),
3333 fal = rl->addresses;
3336 transmit_to_peer(NULL, fal,
3337 TRANSPORT_PONG_PRIORITY,
3338 HELLO_VERIFICATION_TIMEOUT,
3340 ntohs(pong->header.size),
3353 * Function called by the plugin for each received message.
3354 * Update data volumes, possibly notify plugins about
3355 * reducing the rate at which they read from the socket
3356 * and generally forward to our receive callback.
3358 * @param cls the "struct TransportPlugin *" we gave to the plugin
3359 * @param peer (claimed) identity of the other peer
3360 * @param message the message, NULL if we only care about
3361 * learning about the delay until we should receive again
3362 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3363 * @param session identifier used for this session (can be NULL)
3364 * @param sender_address binary address of the sender (if observed)
3365 * @param sender_address_len number of bytes in sender_address
3366 * @return how long the plugin should wait until receiving more data
3367 * (plugins that do not support this, can ignore the return value)
3369 static struct GNUNET_TIME_Relative
3370 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3371 const struct GNUNET_MessageHeader *message,
3372 unsigned int distance,
3373 struct Session *session,
3374 const char *sender_address,
3375 size_t sender_address_len)
3377 struct TransportPlugin *plugin = cls;
3378 struct ReadyList *service_context;
3379 struct ForeignAddressList *peer_address;
3381 struct NeighbourList *n;
3382 struct GNUNET_TIME_Relative ret;
3384 n = find_neighbour (peer);
3386 n = setup_new_neighbour (peer);
3387 service_context = n->plugins;
3388 while ((service_context != NULL) && (plugin != service_context->plugin))
3389 service_context = service_context->next;
3390 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3391 peer_address = NULL;
3392 if (message != NULL)
3394 if ( (session != NULL) ||
3395 (sender_address != NULL) )
3396 peer_address = add_peer_address (n,
3400 sender_address_len);
3401 if (peer_address != NULL)
3403 peer_address->distance = distance;
3404 if (GNUNET_YES == peer_address->validated)
3405 mark_address_connected (peer_address);
3406 peer_address->timeout
3408 GNUNET_TIME_relative_to_absolute
3409 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3410 schedule_next_ping (peer_address);
3412 /* update traffic received amount ... */
3413 msize = ntohs (message->size);
3414 GNUNET_STATISTICS_update (stats,
3415 gettext_noop ("# bytes received from other peers"),
3418 n->distance = distance;
3420 GNUNET_TIME_relative_to_absolute
3421 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3422 GNUNET_SCHEDULER_cancel (sched,
3425 GNUNET_SCHEDULER_add_delayed (sched,
3426 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3427 &neighbour_timeout_task, n);
3428 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3430 /* dropping message due to frequent inbound volume violations! */
3431 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3432 GNUNET_ERROR_TYPE_BULK,
3434 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
3435 n->in_tracker.available_bytes_per_s__,
3436 n->quota_violation_count);
3437 GNUNET_STATISTICS_update (stats,
3438 gettext_noop ("# bandwidth quota violations by other peers"),
3441 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
3443 switch (ntohs (message->type))
3445 case GNUNET_MESSAGE_TYPE_HELLO:
3446 GNUNET_STATISTICS_update (stats,
3447 gettext_noop ("# HELLO messages received from other peers"),
3450 process_hello (plugin, message);
3452 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3453 handle_ping (plugin, message, peer, sender_address, sender_address_len);
3455 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3456 handle_pong (plugin, message, peer, sender_address, sender_address_len);
3459 handle_payload_message (message, n);
3463 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3466 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3467 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3468 (unsigned long long) n->in_tracker.consumption_since_last_update__,
3469 (unsigned int) n->in_tracker.available_bytes_per_s__,
3470 (unsigned long long) ret.value);
3471 GNUNET_STATISTICS_update (stats,
3472 gettext_noop ("# ms throttling suggested"),
3473 (int64_t) ret.value,
3481 * Handle START-message. This is the first message sent to us
3482 * by any client which causes us to add it to our list.
3484 * @param cls closure (always NULL)
3485 * @param client identification of the client
3486 * @param message the actual message
3489 handle_start (void *cls,
3490 struct GNUNET_SERVER_Client *client,
3491 const struct GNUNET_MessageHeader *message)
3493 struct TransportClient *c;
3494 struct ConnectInfoMessage cim;
3495 struct NeighbourList *n;
3498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3499 "Received `%s' request from client\n", "START");
3504 if (c->client == client)
3506 /* client already on our list! */
3508 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3513 c = GNUNET_malloc (sizeof (struct TransportClient));
3517 if (our_hello != NULL)
3520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3521 "Sending our own `%s' to new client\n", "HELLO");
3523 transmit_to_client (c,
3524 (const struct GNUNET_MessageHeader *) our_hello,
3526 /* tell new client about all existing connections */
3527 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3528 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3532 if (GNUNET_YES == n->received_pong)
3535 cim.latency = GNUNET_TIME_relative_hton (n->latency);
3536 cim.distance = htonl (n->distance);
3537 transmit_to_client (c, &cim.header, GNUNET_NO);
3542 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3547 * Handle HELLO-message.
3549 * @param cls closure (always NULL)
3550 * @param client identification of the client
3551 * @param message the actual message
3554 handle_hello (void *cls,
3555 struct GNUNET_SERVER_Client *client,
3556 const struct GNUNET_MessageHeader *message)
3560 GNUNET_STATISTICS_update (stats,
3561 gettext_noop ("# HELLOs received from clients"),
3564 ret = process_hello (NULL, message);
3565 GNUNET_SERVER_receive_done (client, ret);
3570 * Handle SEND-message.
3572 * @param cls closure (always NULL)
3573 * @param client identification of the client
3574 * @param message the actual message
3577 handle_send (void *cls,
3578 struct GNUNET_SERVER_Client *client,
3579 const struct GNUNET_MessageHeader *message)
3581 struct TransportClient *tc;
3582 struct NeighbourList *n;
3583 const struct OutboundMessage *obm;
3584 const struct GNUNET_MessageHeader *obmm;
3588 size = ntohs (message->size);
3590 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3593 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3596 GNUNET_STATISTICS_update (stats,
3597 gettext_noop ("# payload received for other peers"),
3600 obm = (const struct OutboundMessage *) message;
3602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3603 "Received `%s' request from client with target `%4s'\n",
3604 "SEND", GNUNET_i2s (&obm->peer));
3606 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3607 msize = ntohs (obmm->size);
3608 if (size != msize + sizeof (struct OutboundMessage))
3611 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3614 n = find_neighbour (&obm->peer);
3616 n = setup_new_neighbour (&obm->peer);
3618 while ((tc != NULL) && (tc->client != client))
3622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3623 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3625 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3627 transmit_to_peer (tc, NULL, ntohl (obm->priority),
3628 GNUNET_TIME_relative_ntoh (obm->timeout),
3630 ntohs (obmm->size), GNUNET_NO, n);
3631 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3636 * Handle SET_QUOTA-message.
3638 * @param cls closure (always NULL)
3639 * @param client identification of the client
3640 * @param message the actual message
3643 handle_set_quota (void *cls,
3644 struct GNUNET_SERVER_Client *client,
3645 const struct GNUNET_MessageHeader *message)
3647 const struct QuotaSetMessage *qsm =
3648 (const struct QuotaSetMessage *) message;
3649 struct NeighbourList *n;
3651 GNUNET_STATISTICS_update (stats,
3652 gettext_noop ("# SET QUOTA messages received"),
3655 n = find_neighbour (&qsm->peer);
3658 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3659 GNUNET_STATISTICS_update (stats,
3660 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3667 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3669 (unsigned int) ntohl (qsm->quota.value__),
3670 (unsigned int) n->in_tracker.available_bytes_per_s__,
3671 GNUNET_i2s (&qsm->peer));
3673 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3675 if (0 == ntohl (qsm->quota.value__))
3676 disconnect_neighbour (n, GNUNET_NO);
3677 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3682 * Take the given address and append it to the set of results send back to
3685 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3686 * @param address the resolved name, NULL to indicate the last response
3689 transmit_address_to_client (void *cls, const char *address)
3691 struct GNUNET_SERVER_TransmitContext *tc = cls;
3694 if (NULL == address)
3697 slen = strlen (address) + 1;
3698 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3699 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3700 if (NULL == address)
3701 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3706 * Handle AddressLookup-message.
3708 * @param cls closure (always NULL)
3709 * @param client identification of the client
3710 * @param message the actual message
3713 handle_address_lookup (void *cls,
3714 struct GNUNET_SERVER_Client *client,
3715 const struct GNUNET_MessageHeader *message)
3717 const struct AddressLookupMessage *alum;
3718 struct TransportPlugin *lsPlugin;
3719 const char *nameTransport;
3720 const char *address;
3722 struct GNUNET_SERVER_TransmitContext *tc;
3723 struct GNUNET_TIME_Absolute timeout;
3724 struct GNUNET_TIME_Relative rtimeout;
3727 size = ntohs (message->size);
3728 if (size < sizeof (struct AddressLookupMessage))
3730 GNUNET_break_op (0);
3731 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3734 alum = (const struct AddressLookupMessage *) message;
3735 uint32_t addressLen = ntohl (alum->addrlen);
3736 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3738 GNUNET_break_op (0);
3739 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3742 address = (const char *) &alum[1];
3743 nameTransport = (const char *) &address[addressLen];
3745 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3747 GNUNET_break_op (0);
3748 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3751 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3752 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3753 numeric = ntohl (alum->numeric_only);
3754 lsPlugin = find_transport (nameTransport);
3755 if (NULL == lsPlugin)
3757 tc = GNUNET_SERVER_transmit_context_create (client);
3758 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3759 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3760 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3763 tc = GNUNET_SERVER_transmit_context_create (client);
3764 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
3766 address, addressLen,
3769 &transmit_address_to_client, tc);
3773 * List of handlers for the messages understood by this
3776 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3777 {&handle_start, NULL,
3778 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3779 {&handle_hello, NULL,
3780 GNUNET_MESSAGE_TYPE_HELLO, 0},
3781 {&handle_send, NULL,
3782 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3783 {&handle_set_quota, NULL,
3784 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3785 {&handle_address_lookup, NULL,
3786 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3793 * Setup the environment for this plugin.
3796 create_environment (struct TransportPlugin *plug)
3798 plug->env.cfg = cfg;
3799 plug->env.sched = sched;
3800 plug->env.my_identity = &my_identity;
3801 plug->env.cls = plug;
3802 plug->env.receive = &plugin_env_receive;
3803 plug->env.notify_address = &plugin_env_notify_address;
3804 plug->env.session_end = &plugin_env_session_end;
3805 plug->env.max_connections = max_connect_per_transport;
3806 plug->env.stats = stats;
3811 * Start the specified transport (load the plugin).
3814 start_transport (struct GNUNET_SERVER_Handle *server,
3817 struct TransportPlugin *plug;
3820 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3821 _("Loading `%s' transport plugin\n"), name);
3822 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3823 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3824 create_environment (plug);
3825 plug->short_name = GNUNET_strdup (name);
3826 plug->lib_name = libname;
3827 plug->next = plugins;
3829 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3830 if (plug->api == NULL)
3832 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3833 _("Failed to load transport plugin for `%s'\n"), name);
3834 GNUNET_free (plug->short_name);
3835 plugins = plug->next;
3836 GNUNET_free (libname);
3843 * Called whenever a client is disconnected. Frees our
3844 * resources associated with that client.
3846 * @param cls closure
3847 * @param client identification of the client
3850 client_disconnect_notification (void *cls,
3851 struct GNUNET_SERVER_Client *client)
3853 struct TransportClient *pos;
3854 struct TransportClient *prev;
3855 struct ClientMessageQueueEntry *mqe;
3860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3861 "Client disconnected, cleaning up.\n");
3865 while ((pos != NULL) && (pos->client != client))
3872 while (NULL != (mqe = pos->message_queue_head))
3874 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3875 pos->message_queue_tail,
3877 pos->message_count--;
3881 clients = pos->next;
3883 prev->next = pos->next;
3884 if (GNUNET_YES == pos->tcs_pending)
3889 if (pos->th != NULL)
3891 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3894 GNUNET_break (0 == pos->message_count);
3900 * Iterator to free entries in the validation_map.
3902 * @param cls closure (unused)
3903 * @param key current key code
3904 * @param value value in the hash map (validation to abort)
3905 * @return GNUNET_YES (always)
3908 abort_validation (void *cls,
3909 const GNUNET_HashCode * key,
3912 struct ValidationEntry *va = value;
3914 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3915 GNUNET_free (va->transport_name);
3922 * Function called when the service shuts down. Unloads our plugins
3923 * and cancels pending validations.
3925 * @param cls closure, unused
3926 * @param tc task context (unused)
3929 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3931 struct TransportPlugin *plug;
3932 struct OwnAddressList *al;
3933 struct CheckHelloValidatedContext *chvc;
3935 while (neighbours != NULL)
3936 disconnect_neighbour (neighbours, GNUNET_NO);
3938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3939 "Transport service is unloading plugins...\n");
3941 while (NULL != (plug = plugins))
3943 plugins = plug->next;
3944 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
3946 GNUNET_SCHEDULER_cancel (plug->env.sched,
3947 plug->address_update_task);
3948 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
3950 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3951 GNUNET_free (plug->lib_name);
3952 GNUNET_free (plug->short_name);
3953 while (NULL != (al = plug->addresses))
3955 plug->addresses = al->next;
3960 if (my_private_key != NULL)
3961 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3962 GNUNET_free_non_null (our_hello);
3964 /* free 'chvc' data structure */
3965 while (NULL != (chvc = chvc_head))
3967 chvc_head = chvc->next;
3968 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3973 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3976 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3977 validation_map = NULL;
3980 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3987 * Initiate transport service.
3989 * @param cls closure
3990 * @param s scheduler to use
3991 * @param serv the initialized server
3992 * @param c configuration to use
3996 struct GNUNET_SCHEDULER_Handle *s,
3997 struct GNUNET_SERVER_Handle *serv,
3998 const struct GNUNET_CONFIGURATION_Handle *c)
4003 unsigned long long tneigh;
4008 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4009 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4010 /* parse configuration */
4012 GNUNET_CONFIGURATION_get_value_number (c,
4017 GNUNET_CONFIGURATION_get_value_filename (c,
4019 "HOSTKEY", &keyfile)))
4021 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4023 ("Transport service is lacking key configuration settings. Exiting.\n"));
4024 GNUNET_SCHEDULER_shutdown (s);
4027 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4030 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4031 validation_map = NULL;
4034 max_connect_per_transport = (uint32_t) tneigh;
4035 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4036 GNUNET_free (keyfile);
4037 if (my_private_key == NULL)
4039 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4041 ("Transport service could not access hostkey. Exiting.\n"));
4042 GNUNET_SCHEDULER_shutdown (s);
4045 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4048 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4049 validation_map = NULL;
4052 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4053 GNUNET_CRYPTO_hash (&my_public_key,
4054 sizeof (my_public_key), &my_identity.hashPubKey);
4055 /* setup notification */
4057 GNUNET_SERVER_disconnect_notify (server,
4058 &client_disconnect_notification, NULL);
4059 /* load plugins... */
4062 GNUNET_CONFIGURATION_get_value_string (c,
4063 "TRANSPORT", "PLUGINS", &plugs))
4065 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4066 _("Starting transport plugins `%s'\n"), plugs);
4067 pos = strtok (plugs, " ");
4070 start_transport (server, pos);
4072 pos = strtok (NULL, " ");
4074 GNUNET_free (plugs);
4076 GNUNET_SCHEDULER_add_delayed (sched,
4077 GNUNET_TIME_UNIT_FOREVER_REL,
4078 &shutdown_task, NULL);
4083 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
4085 /* process client requests */
4086 GNUNET_SERVER_add_handlers (server, handlers);
4091 * The main function for the transport service.
4093 * @param argc number of arguments from the command line
4094 * @param argv command line arguments
4095 * @return 0 ok, 1 on error
4098 main (int argc, char *const *argv)
4100 return (GNUNET_OK ==
4101 GNUNET_SERVICE_run (argc,
4104 GNUNET_SERVICE_OPTION_NONE,
4105 &run, NULL)) ? 0 : 1;
4108 /* end of gnunet-service-transport.c */