2 This file is part of GNUnet.
3 (C) 2009, 2010 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 3, 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
28 #include "gnunet_client_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_peerinfo_service.h"
35 #include "gnunet_plugin_lib.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_service_lib.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
41 #include "transport_ats.h"
44 #define DEBUG_BLACKLIST GNUNET_NO
46 #define DEBUG_PING_PONG GNUNET_NO
48 #define DEBUG_TRANSPORT_HELLO GNUNET_NO
50 #define DEBUG_INBOUND GNUNET_YES
53 * Should we do some additional checks (to validate behavior
56 #define EXTRA_CHECKS GNUNET_YES
59 * How many messages can we have pending for a given client process
60 * before we start to drop incoming messages? We typically should
61 * have only one client and so this would be the primary buffer for
62 * messages, so the number should be chosen rather generously.
64 * The expectation here is that most of the time the queue is large
65 * enough so that a drop is virtually never required. Note that
66 * this value must be about as large as 'TOTAL_MSGS' in the
67 * 'test_transport_api_reliability.c', otherwise that testcase may
70 #define MAX_PENDING (128 * 1024)
73 * Size of the per-transport blacklist hash maps.
75 #define TRANSPORT_BLACKLIST_HT_SIZE 16
78 * How often should we try to reconnect to a peer using a particular
79 * transport plugin before giving up? Note that the plugin may be
80 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
82 #define MAX_CONNECT_RETRY 3
85 * Limit on the number of ready-to-run tasks when validating
86 * HELLOs. If more tasks are ready to run, we will drop
87 * HELLOs instead of validating them.
89 #define MAX_HELLO_LOAD 4
92 * How often must a peer violate bandwidth quotas before we start
93 * to simply drop its messages?
95 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
98 * How long until a HELLO verification attempt should time out?
99 * Must be rather small, otherwise a partially successful HELLO
100 * validation (some addresses working) might not be available
101 * before a client's request for a connection fails for good.
102 * Besides, if a single request to an address takes a long time,
103 * then the peer is unlikely worthwhile anyway.
105 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
108 * How long is a PONG signature valid? We'll recycle a signature until
109 * 1/4 of this time is remaining. PONGs should expire so that if our
110 * external addresses change an adversary cannot replay them indefinitely.
111 * OTOH, we don't want to spend too much time generating PONG signatures,
112 * so they must have some lifetime to reduce our CPU usage.
114 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
117 * Priority to use for PONG messages.
119 #define TRANSPORT_PONG_PRIORITY 4
122 * How often do we re-add (cheaper) plugins to our list of plugins
123 * to try for a given connected peer?
125 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
128 * After how long do we expire an address in a HELLO that we just
129 * validated? This value is also used for our own addresses when we
132 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
136 * How long before an existing address expires should we again try to
137 * validate it? Must be (significantly) smaller than
138 * HELLO_ADDRESS_EXPIRATION.
140 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
143 * List of addresses of other peers
145 struct ForeignAddressList
148 * This is a linked list.
150 struct ForeignAddressList *next;
153 * Which ready list does this entry belong to.
155 struct ReadyList *ready_list;
158 * How long until we auto-expire this address (unless it is
159 * re-confirmed by the transport)?
161 struct GNUNET_TIME_Absolute expires;
164 * Task used to re-validate addresses, updates latencies and
167 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
175 * Session (or NULL if no valid session currently exists or if the
176 * plugin does not use sessions).
178 struct Session *session;
180 struct ATS_ressource_entry * ressources;
182 struct ATS_quality_entry * quality;
185 * What was the last latency observed for this address, plugin and peer?
187 struct GNUNET_TIME_Relative latency;
190 * If we did not successfully transmit a message to the given peer
191 * via this connection during the specified time, we should consider
192 * the connection to be dead. This is used in the case that a TCP
193 * transport simply stalls writing to the stream but does not
194 * formerly get a signal that the other peer died.
196 struct GNUNET_TIME_Absolute timeout;
199 * How often have we tried to connect using this plugin? Used to
200 * discriminate against addresses that do not work well.
201 * FIXME: not yet used, but should be!
203 unsigned int connect_attempts;
206 * DV distance to this peer (1 if no DV is used).
207 * FIXME: need to set this from transport plugins!
217 * Have we ever estimated the latency of this address? Used to
218 * ensure that the first time we add an address, we immediately
224 * Are we currently connected via this address? The first time we
225 * successfully transmit or receive data to a peer via a particular
226 * address, we set this to GNUNET_YES. If we later get an error
227 * (disconnect notification, transmission failure, timeout), we set
228 * it back to GNUNET_NO.
233 * Is this plugin currently busy transmitting to the specific target?
234 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
235 * messages do not count as 'in transmit'.
240 * Has this address been validated yet?
248 * Entry in linked list of network addresses for ourselves. Also
249 * includes a cached signature for 'struct TransportPongMessage's.
251 struct OwnAddressList
254 * This is a linked list.
256 struct OwnAddressList *next;
259 * How long until the current signature expires? (ZERO if the
260 * signature was never created).
262 struct GNUNET_TIME_Absolute pong_sig_expires;
265 * Signature for a 'struct TransportPongMessage' for this address.
267 struct GNUNET_CRYPTO_RsaSignature pong_signature;
278 * Entry in linked list of all of our plugins.
280 struct TransportPlugin
283 * This is a linked list.
285 struct TransportPlugin *next;
288 * API of the transport as returned by the plugin's
289 * initialization function.
291 struct GNUNET_TRANSPORT_PluginFunctions *api;
294 * Short name for the plugin (i.e. "tcp").
299 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
304 * List of our known addresses for this transport.
306 struct OwnAddressList *addresses;
309 * Environment this transport service is using
312 struct GNUNET_TRANSPORT_PluginEnvironment env;
315 * ID of task that is used to clean up expired addresses.
317 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
320 * Set to GNUNET_YES if we need to scrap the existing list of
321 * "addresses" and start fresh when we receive the next address
322 * update from a transport. Set to GNUNET_NO if we should just add
323 * the new address to the list and wait for the commit call.
327 struct ATS_plugin * rc;
330 * Hashmap of blacklisted peers for this particular transport.
332 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
335 struct NeighbourList;
338 * For each neighbour we keep a list of messages
339 * that we still want to transmit to the neighbour.
345 * This is a doubly linked list.
347 struct MessageQueue *next;
350 * This is a doubly linked list.
352 struct MessageQueue *prev;
355 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
356 * stuck together in memory. Allocated at the end of this struct.
358 const char *message_buf;
361 * Size of the message buf
363 size_t message_buf_size;
366 * Client responsible for queueing the message;
367 * used to check that a client has no two messages
368 * pending for the same target. Can be NULL.
370 struct TransportClient *client;
373 * Using which specific address should we send this message?
375 struct ForeignAddressList *specific_address;
378 * Peer ID of the Neighbour this entry belongs to.
380 struct GNUNET_PeerIdentity neighbour_id;
383 * Plugin that we used for the transmission.
384 * NULL until we scheduled a transmission.
386 struct TransportPlugin *plugin;
389 * At what time should we fail?
391 struct GNUNET_TIME_Absolute timeout;
394 * Internal message of the transport system that should not be
395 * included in the usual SEND-SEND_OK transmission confirmation
396 * traffic management scheme. Typically, "internal_msg" will
397 * be set whenever "client" is NULL (but it is not strictly
403 * How important is the message?
405 unsigned int priority;
411 * For a given Neighbour, which plugins are available
412 * to talk to this peer and what are their costs?
417 * This is a linked list.
419 struct ReadyList *next;
422 * Which of our transport plugins does this entry
425 struct TransportPlugin *plugin;
428 * Transport addresses, latency, and readiness for
429 * this particular plugin.
431 struct ForeignAddressList *addresses;
434 * To which neighbour does this ready list belong to?
436 struct NeighbourList *neighbour;
441 * Entry in linked list of all of our current neighbours.
447 * This is a linked list.
449 struct NeighbourList *next;
452 * Which of our transports is connected to this peer
453 * and what is their status?
455 struct ReadyList *plugins;
458 * Head of list of messages we would like to send to this peer;
459 * must contain at most one message per client.
461 struct MessageQueue *messages_head;
464 * Tail of list of messages we would like to send to this peer; must
465 * contain at most one message per client.
467 struct MessageQueue *messages_tail;
470 * Head of list of messages of messages we expected the continuation
471 * to be called to destroy the message
473 struct MessageQueue *cont_head;
476 * Tail of list of messages of messages we expected the continuation
477 * to be called to destroy the message
479 struct MessageQueue *cont_tail;
482 * Buffer for at most one payload message used when we receive
483 * payload data before our PING-PONG has succeeded. We then
484 * store such messages in this intermediary buffer until the
485 * connection is fully up.
487 struct GNUNET_MessageHeader *pre_connect_message_buffer;
490 * Context for peerinfo iteration.
491 * NULL after we are done processing peerinfo's information.
493 struct GNUNET_PEERINFO_IteratorContext *piter;
496 * Public key for this peer. Valid only if the respective flag is set below.
498 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
501 * Identity of this neighbour.
503 struct GNUNET_PeerIdentity id;
506 * ID of task scheduled to run when this peer is about to
507 * time out (will free resources associated with the peer).
509 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
512 * ID of task scheduled to run when we should retry transmitting
513 * the head of the message queue. Actually triggered when the
514 * transmission is timing out (we trigger instantly when we have
515 * a chance of success).
517 GNUNET_SCHEDULER_TaskIdentifier retry_task;
520 * How long until we should consider this peer dead
521 * (if we don't receive another message in the
524 struct GNUNET_TIME_Absolute peer_timeout;
527 * Tracker for inbound bandwidth.
529 struct GNUNET_BANDWIDTH_Tracker in_tracker;
532 * The latency we have seen for this particular address for
533 * this particular peer. This latency may have been calculated
534 * over multiple transports. This value reflects how long it took
535 * us to receive a response when SENDING via this particular
536 * transport/neighbour/address combination!
538 * FIXME: we need to periodically send PINGs to update this
539 * latency (at least more often than the current "huge" (11h?)
542 struct GNUNET_TIME_Relative latency;
545 * How often has the other peer (recently) violated the
546 * inbound traffic limit? Incremented by 10 per violation,
547 * decremented by 1 per non-violation (for each
550 unsigned int quota_violation_count;
553 * DV distance to this peer (1 if no DV is used).
558 * Have we seen an PONG from this neighbour in the past (and
559 * not had a disconnect since)?
564 * Do we have a valid public key for this neighbour?
566 int public_key_valid;
569 * Performance data for the peer.
571 struct GNUNET_TRANSPORT_ATS_Information *ats;
575 * Message used to ask a peer to validate receipt (to check an address
576 * from a HELLO). Followed by the address we are trying to validate,
577 * or an empty address if we are just sending a PING to confirm that a
578 * connection which the receiver (of the PING) initiated is still valid.
580 struct TransportPingMessage
584 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
586 struct GNUNET_MessageHeader header;
589 * Challenge code (to ensure fresh reply).
591 uint32_t challenge GNUNET_PACKED;
594 * Who is the intended recipient?
596 struct GNUNET_PeerIdentity target;
602 * Message used to validate a HELLO. The challenge is included in the
603 * confirmation to make matching of replies to requests possible. The
604 * signature signs our public key, an expiration time and our address.<p>
606 * This message is followed by our transport address that the PING tried
607 * to confirm (if we liked it). The address can be empty (zero bytes)
608 * if the PING had not address either (and we received the request via
609 * a connection that we initiated).
611 struct TransportPongMessage
615 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
617 struct GNUNET_MessageHeader header;
620 * Challenge code from PING (showing freshness). Not part of what
621 * is signed so that we can re-use signatures.
623 uint32_t challenge GNUNET_PACKED;
628 struct GNUNET_CRYPTO_RsaSignature signature;
631 * What are we signing and why? Two possible reason codes can be here:
632 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
633 * plausible address for this peer (pid is set to identity of signer); or
634 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
635 * an address we used to connect to the peer with the given pid.
637 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
640 * When does this signature expire?
642 struct GNUNET_TIME_AbsoluteNBO expiration;
645 * Either the identity of the peer Who signed this message, or the
646 * identity of the peer that we're connected to using the given
647 * address (depending on purpose.type).
649 struct GNUNET_PeerIdentity pid;
652 * Size of address appended to this message (part of what is
653 * being signed, hence not redundant).
661 * Linked list of messages to be transmitted to the client. Each
662 * entry is followed by the actual message.
664 struct ClientMessageQueueEntry
667 * This is a doubly-linked list.
669 struct ClientMessageQueueEntry *next;
672 * This is a doubly-linked list.
674 struct ClientMessageQueueEntry *prev;
679 * Client connected to the transport service.
681 struct TransportClient
685 * This is a linked list.
687 struct TransportClient *next;
690 * Handle to the client.
692 struct GNUNET_SERVER_Client *client;
695 * Linked list of messages yet to be transmitted to
698 struct ClientMessageQueueEntry *message_queue_head;
701 * Tail of linked list of messages yet to be transmitted to the
704 struct ClientMessageQueueEntry *message_queue_tail;
707 * Current transmit request handle.
709 struct GNUNET_CONNECTION_TransmitHandle *th;
712 * Is a call to "transmit_send_continuation" pending? If so, we
713 * must not free this struct (even if the corresponding client
714 * disconnects) and instead only remove it from the linked list and
715 * set the "client" field to NULL.
720 * Length of the list of messages pending for this client.
722 unsigned int message_count;
728 * Context of currently active requests to peerinfo
729 * for validation of HELLOs.
731 struct CheckHelloValidatedContext;
735 * Entry in map of all HELLOs awaiting validation.
737 struct ValidationEntry
741 * NULL if this entry is not part of a larger HELLO validation.
743 struct CheckHelloValidatedContext *chvc;
746 * The address, actually a pointer to the end
747 * of this struct. Do not free!
752 * Name of the transport.
754 char *transport_name;
757 * The public key of the peer.
759 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
762 * ID of task that will clean up this entry if we don't succeed
763 * with the validation first.
765 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
768 * At what time did we send this validation?
770 struct GNUNET_TIME_Absolute send_time;
773 * Session being validated (or NULL for none).
775 struct Session *session;
778 * Challenge number we used.
791 * Context of currently active requests to peerinfo
792 * for validation of HELLOs.
794 struct CheckHelloValidatedContext
798 * This is a doubly-linked list.
800 struct CheckHelloValidatedContext *next;
803 * This is a doubly-linked list.
805 struct CheckHelloValidatedContext *prev;
808 * Hello that we are validating.
810 const struct GNUNET_HELLO_Message *hello;
813 * Context for peerinfo iteration.
814 * NULL after we are done processing peerinfo's information.
816 struct GNUNET_PEERINFO_IteratorContext *piter;
819 * Was a HELLO known for this peer to peerinfo?
824 * Number of validation entries currently referring to this
827 unsigned int ve_count;
832 * All zero hash for comparison.
834 static GNUNET_HashCode null_hash;
839 static struct GNUNET_HELLO_Message *our_hello;
844 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
849 static struct GNUNET_PeerIdentity my_identity;
854 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
859 const struct GNUNET_CONFIGURATION_Handle *cfg;
862 * Linked list of all clients to this service.
864 static struct TransportClient *clients;
867 * All loaded plugins.
869 static struct TransportPlugin *plugins;
872 * Handle to peerinfo service.
874 static struct GNUNET_PEERINFO_Handle *peerinfo;
877 * All known neighbours and their HELLOs.
879 static struct NeighbourList *neighbours;
882 * Number of neighbours we'd like to have.
884 static uint32_t max_connect_per_transport;
887 * Head of linked list.
889 static struct CheckHelloValidatedContext *chvc_head;
892 * Tail of linked list.
894 static struct CheckHelloValidatedContext *chvc_tail;
897 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
898 * of the given peer that we are currently validating).
900 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
903 * Handle for reporting statistics.
905 static struct GNUNET_STATISTICS_Handle *stats;
908 * Identifier of 'refresh_hello' task.
910 static GNUNET_SCHEDULER_TaskIdentifier hello_task;
913 * Identifier of ats scheduler task.
915 static GNUNET_SCHEDULER_TaskIdentifier ats_task;
918 * Is transport service shutting down ?
920 static int shutdown_in_progress;
923 * Handle for ats information
925 static struct ATS_Handle *ats;
928 * Time of last ats execution
930 struct GNUNET_TIME_Absolute last_ats_execution;
932 * Minimum interval between two ATS executions
934 struct GNUNET_TIME_Relative ats_minimum_interval;
936 * Regular interval when ATS execution is triggered
938 struct GNUNET_TIME_Relative ats_regular_interval;
941 * The peer specified by the given neighbour has timed-out or a plugin
942 * has disconnected. We may either need to do nothing (other plugins
943 * still up), or trigger a full disconnect and clean up. This
944 * function updates our state and do the necessary notifications.
945 * Also notifies our clients that the neighbour is now officially
948 * @param n the neighbour list entry for the peer
949 * @param check should we just check if all plugins
950 * disconnected or must we ask all plugins to
953 static void disconnect_neighbour (struct NeighbourList *n, int check);
956 * Check the ready list for the given neighbour and if a plugin is
957 * ready for transmission (and if we have a message), do so!
959 * @param nexi target peer for which to transmit
961 static void try_transmission_to_peer (struct NeighbourList *n);
963 struct ForeignAddressList * get_preferred_ats_address (
964 struct NeighbourList *n);
967 * Find an entry in the neighbour list for a particular peer.
969 * @return NULL if not found.
971 static struct NeighbourList *
972 find_neighbour (const struct GNUNET_PeerIdentity *key)
974 struct NeighbourList *head = neighbours;
976 while ((head != NULL) &&
977 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
982 static int update_addr_value (struct ForeignAddressList *fal, uint32_t value , int ats_index)
986 for (c=0; c<available_quality_metrics; c++)
988 if (ats_index == qm[c].atis_index)
990 fal->quality[c].values[0] = fal->quality[c].values[1];
991 fal->quality[c].values[1] = fal->quality[c].values[2];
992 fal->quality[c].values[2] = value;
994 ats_modify_problem_state (ats, ATS_QUALITY_UPDATED);
997 if (set == GNUNET_NO)
999 for (c=0; c<available_ressources; c++)
1001 if (ats_index == ressources[c].atis_index)
1003 fal->ressources[c].c = value;
1005 ats_modify_problem_state (ats, ATS_COST_UPDATED);
1013 update_addr_ats (struct ForeignAddressList *fal,
1014 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
1019 for (c1=0; c1<ats_count; c1++)
1021 set = update_addr_value(fal, ntohl(ats_data[c1].value), ntohl(ats_data[c1].type));
1027 * Find an entry in the transport list for a particular transport.
1029 * @return NULL if not found.
1031 static struct TransportPlugin *
1032 find_transport (const char *short_name)
1034 struct TransportPlugin *head = plugins;
1035 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
1041 * Is a particular peer blacklisted for a particular transport?
1043 * @param peer the peer to check for
1044 * @param plugin the plugin used to connect to the peer
1046 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
1049 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
1052 if (plugin->blacklist != NULL)
1054 if (GNUNET_CONTAINER_multihashmap_contains (plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
1057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1058 "Peer `%s:%s' is blacklisted!\n",
1059 plugin->short_name, GNUNET_i2s (peer));
1062 GNUNET_STATISTICS_update (stats, "# blacklisted peers refused", 1, GNUNET_NO);
1072 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer,
1073 char *transport_name)
1075 struct TransportPlugin *plugin;
1077 plugin = find_transport(transport_name);
1078 if (plugin == NULL) /* Nothing to do */
1081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082 "Adding peer `%s' with plugin `%s' to blacklist\n",
1086 if (plugin->blacklist == NULL)
1087 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
1088 GNUNET_assert(plugin->blacklist != NULL);
1089 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
1091 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1096 * Read the blacklist file, containing transport:peer entries.
1097 * Provided the transport is loaded, set up hashmap with these
1098 * entries to blacklist peers by transport.
1102 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1109 struct GNUNET_PeerIdentity pid;
1111 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1112 unsigned int entries_found;
1113 char *transport_name;
1116 GNUNET_CONFIGURATION_get_value_filename (cfg,
1122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123 "Option `%s' in section `%s' not specified!\n",
1129 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1130 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1131 | GNUNET_DISK_PERM_USER_WRITE);
1132 if (0 != STAT (fn, &frstat))
1134 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1135 _("Could not read blacklist file `%s'\n"), fn);
1139 if (frstat.st_size == 0)
1142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143 _("Blacklist file `%s' is empty.\n"),
1149 /* FIXME: use mmap */
1150 data = GNUNET_malloc_large (frstat.st_size);
1151 GNUNET_assert(data != NULL);
1152 if (frstat.st_size !=
1153 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1155 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1156 _("Failed to read blacklist from `%s'\n"), fn);
1163 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1165 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1166 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1169 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1172 if (colon_pos >= frstat.st_size)
1174 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1175 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1176 (unsigned long long) colon_pos);
1182 if (isspace( (unsigned char) data[colon_pos]))
1184 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1185 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1186 (unsigned long long) colon_pos);
1188 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1192 tsize = colon_pos - pos;
1193 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1195 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1196 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1197 (unsigned long long) colon_pos);
1206 transport_name = GNUNET_malloc(tsize + 1);
1207 memcpy(transport_name, &data[pos], tsize);
1208 pos = colon_pos + 1;
1210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1211 "Read transport name %s in blacklist file.\n",
1214 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1215 if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1217 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1218 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1219 (unsigned long long) pos);
1221 while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1223 GNUNET_free_non_null(transport_name);
1226 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1227 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1229 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1230 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1231 (unsigned long long) pos,
1236 if (0 != memcmp (&pid,
1238 sizeof (struct GNUNET_PeerIdentity)))
1241 add_peer_to_blacklist (&pid,
1246 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1251 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1252 GNUNET_free_non_null(transport_name);
1253 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1256 GNUNET_STATISTICS_update (stats, "# Transport entries blacklisted", entries_found, GNUNET_NO);
1263 * Function called to notify a client about the socket being ready to
1264 * queue more data. "buf" will be NULL and "size" zero if the socket
1265 * was closed for writing in the meantime.
1267 * @param cls closure
1268 * @param size number of bytes available in buf
1269 * @param buf where the callee should write the message
1270 * @return number of bytes written to buf
1273 transmit_to_client_callback (void *cls, size_t size, void *buf)
1275 struct TransportClient *client = cls;
1276 struct ClientMessageQueueEntry *q;
1279 const struct GNUNET_MessageHeader *msg;
1286 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1287 "Transmission to client failed, closing connection.\n");
1289 /* fatal error with client, free message queue! */
1290 while (NULL != (q = client->message_queue_head))
1292 GNUNET_STATISTICS_update (stats,
1293 gettext_noop ("# bytes discarded (could not transmit to client)"),
1294 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1296 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1297 client->message_queue_tail,
1301 client->message_count = 0;
1306 while (NULL != (q = client->message_queue_head))
1308 msg = (const struct GNUNET_MessageHeader *) &q[1];
1309 msize = ntohs (msg->size);
1310 if (msize + tsize > size)
1313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314 "Transmitting message of type %u to client.\n",
1317 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1318 client->message_queue_tail,
1320 memcpy (&cbuf[tsize], msg, msize);
1323 client->message_count--;
1327 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1328 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1330 GNUNET_TIME_UNIT_FOREVER_REL,
1331 &transmit_to_client_callback,
1333 GNUNET_assert (client->th != NULL);
1340 * Convert an address to a string.
1342 * @param plugin name of the plugin responsible for the address
1343 * @param addr binary address
1344 * @param addr_len number of bytes in addr
1345 * @return NULL on error, otherwise address string
1348 a2s (const char *plugin,
1352 struct TransportPlugin *p;
1356 p = find_transport (plugin);
1357 if ((p == NULL) || (addr_len == 0) || (addr == NULL))
1360 return p->api->address_to_string (NULL,
1370 * Iterator to free entries in the validation_map.
1372 * @param cls closure (unused)
1373 * @param key current key code
1374 * @param value value in the hash map (validation to abort)
1375 * @return GNUNET_YES (always)
1378 abort_validation (void *cls,
1379 const GNUNET_HashCode * key,
1382 struct ValidationEntry *va = value;
1384 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
1385 GNUNET_SCHEDULER_cancel (va->timeout_task);
1386 GNUNET_free (va->transport_name);
1387 if (va->chvc != NULL)
1389 va->chvc->ve_count--;
1390 if (va->chvc->ve_count == 0)
1392 GNUNET_CONTAINER_DLL_remove (chvc_head,
1395 GNUNET_free (va->chvc);
1405 * HELLO validation cleanup task (validation failed).
1407 * @param cls the 'struct ValidationEntry' that failed
1408 * @param tc scheduler context (unused)
1411 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1413 struct ValidationEntry *va = cls;
1414 struct GNUNET_PeerIdentity pid;
1416 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1417 GNUNET_STATISTICS_update (stats,
1418 gettext_noop ("# address validation timeouts"),
1421 GNUNET_CRYPTO_hash (&va->publicKey,
1423 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1425 GNUNET_break (GNUNET_OK ==
1426 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1429 abort_validation (NULL, NULL, va);
1435 * Send the specified message to the specified client. Since multiple
1436 * messages may be pending for the same client at a time, this code
1437 * makes sure that no message is lost.
1439 * @param client client to transmit the message to
1440 * @param msg the message to send
1441 * @param may_drop can this message be dropped if the
1442 * message queue for this client is getting far too large?
1445 transmit_to_client (struct TransportClient *client,
1446 const struct GNUNET_MessageHeader *msg, int may_drop)
1448 struct ClientMessageQueueEntry *q;
1451 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1453 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1455 ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1458 client->message_count,
1460 GNUNET_STATISTICS_update (stats,
1461 gettext_noop ("# messages dropped due to slow client"),
1466 msize = ntohs (msg->size);
1467 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1468 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1469 memcpy (&q[1], msg, msize);
1470 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1471 client->message_queue_tail,
1472 client->message_queue_tail,
1474 client->message_count++;
1475 if (client->th == NULL)
1477 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1479 GNUNET_TIME_UNIT_FOREVER_REL,
1480 &transmit_to_client_callback,
1482 GNUNET_assert (client->th != NULL);
1488 * Transmit a 'SEND_OK' notification to the given client for the
1491 * @param client who to notify
1492 * @param n neighbour to notify about, can be NULL (on failure)
1493 * @param target target of the transmission
1494 * @param result status code for the transmission request
1497 transmit_send_ok (struct TransportClient *client,
1498 struct NeighbourList *n,
1499 const struct GNUNET_PeerIdentity *target,
1502 struct SendOkMessage send_ok_msg;
1504 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1505 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1506 send_ok_msg.success = htonl (result);
1508 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1510 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1511 send_ok_msg.peer = *target;
1512 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1517 * Mark the given FAL entry as 'connected' (and hence preferred for
1518 * sending); also mark all others for the same peer as 'not connected'
1519 * (since only one can be preferred).
1521 * @param fal address to set to 'connected'
1524 mark_address_connected (struct ForeignAddressList *fal);
1529 * We should re-try transmitting to the given peer,
1530 * hopefully we've learned something in the meantime.
1533 retry_transmission_task (void *cls,
1534 const struct GNUNET_SCHEDULER_TaskContext *tc)
1536 struct NeighbourList *n = cls;
1538 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1539 try_transmission_to_peer (n);
1544 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1545 * upon "completion" of a send request. This tells the API
1546 * that it is now legal to send another message to the given
1549 * @param cls closure, identifies the entry on the
1550 * message queue that was transmitted and the
1551 * client responsible for queuing the message
1552 * @param target the peer receiving the message
1553 * @param result GNUNET_OK on success, if the transmission
1554 * failed, we should not tell the client to transmit
1558 transmit_send_continuation (void *cls,
1559 const struct GNUNET_PeerIdentity *target,
1562 struct MessageQueue *mq = cls;
1563 struct NeighbourList *n;
1565 GNUNET_STATISTICS_update (stats,
1566 gettext_noop ("# bytes pending with plugins"),
1567 - (int64_t) mq->message_buf_size,
1569 if (result == GNUNET_OK)
1571 GNUNET_STATISTICS_update (stats,
1572 gettext_noop ("# bytes successfully transmitted by plugins"),
1573 mq->message_buf_size,
1578 GNUNET_STATISTICS_update (stats,
1579 gettext_noop ("# bytes with transmission failure by plugins"),
1580 mq->message_buf_size,
1583 if (mq->specific_address != NULL)
1585 if (result == GNUNET_OK)
1587 mq->specific_address->timeout =
1588 GNUNET_TIME_relative_to_absolute
1589 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1590 if (mq->specific_address->validated == GNUNET_YES)
1591 mark_address_connected (mq->specific_address);
1595 if (mq->specific_address->connected != GNUNET_NO)
1598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1600 a2s (mq->specific_address->ready_list->plugin->short_name,
1601 mq->specific_address->addr,
1602 mq->specific_address->addrlen));
1604 GNUNET_STATISTICS_update (stats,
1605 gettext_noop ("# connected addresses"),
1608 mq->specific_address->connected = GNUNET_NO;
1611 if (! mq->internal_msg)
1612 mq->specific_address->in_transmit = GNUNET_NO;
1614 n = find_neighbour (&mq->neighbour_id);
1615 if (mq->client != NULL)
1616 transmit_send_ok (mq->client, n, target, result);
1619 GNUNET_CONTAINER_DLL_remove (n->cont_head,
1626 if (result == GNUNET_OK)
1627 try_transmission_to_peer (n);
1628 else if (GNUNET_SCHEDULER_NO_TASK == n->retry_task)
1629 n->retry_task = GNUNET_SCHEDULER_add_now (&retry_transmission_task,
1636 * Check the ready list for the given neighbour and if a plugin is
1637 * ready for transmission (and if we have a message), do so!
1639 * @param neighbour target peer for which to transmit
1642 try_transmission_to_peer (struct NeighbourList *n)
1644 struct ReadyList *rl;
1645 struct MessageQueue *mq;
1646 struct GNUNET_TIME_Relative timeout;
1650 if (n->messages_head == NULL)
1653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654 "Transmission queue for `%4s' is empty\n",
1655 GNUNET_i2s (&n->id));
1657 return; /* nothing to do */
1660 mq = n->messages_head;
1661 force_address = GNUNET_YES;
1662 if (mq->specific_address == NULL)
1665 mq->specific_address = get_preferred_ats_address(n);
1666 GNUNET_STATISTICS_update (stats,
1667 gettext_noop ("# transport selected peer address freely"),
1670 force_address = GNUNET_NO;
1672 if (mq->specific_address == NULL)
1674 GNUNET_STATISTICS_update (stats,
1675 gettext_noop ("# transport failed to selected peer address"),
1678 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1679 if (timeout.rel_value == 0)
1682 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1683 "No destination address available to transmit message of size %u to peer `%4s'\n",
1684 mq->message_buf_size,
1685 GNUNET_i2s (&mq->neighbour_id));
1687 GNUNET_STATISTICS_update (stats,
1688 gettext_noop ("# bytes in message queue for other peers"),
1689 - (int64_t) mq->message_buf_size,
1691 GNUNET_STATISTICS_update (stats,
1692 gettext_noop ("# bytes discarded (no destination address available)"),
1693 mq->message_buf_size,
1695 if (mq->client != NULL)
1696 transmit_send_ok (mq->client, n, &n->id, GNUNET_NO);
1697 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1701 return; /* nobody ready */
1703 GNUNET_STATISTICS_update (stats,
1704 gettext_noop ("# message delivery deferred (no address)"),
1707 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1708 GNUNET_SCHEDULER_cancel (n->retry_task);
1709 n->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
1710 &retry_transmission_task,
1713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1715 mq->message_buf_size,
1716 GNUNET_i2s (&mq->neighbour_id),
1719 /* FIXME: might want to trigger peerinfo lookup here
1720 (unless that's already pending...) */
1723 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1726 if (mq->specific_address->connected == GNUNET_NO)
1727 mq->specific_address->connect_attempts++;
1728 rl = mq->specific_address->ready_list;
1729 mq->plugin = rl->plugin;
1730 if (!mq->internal_msg)
1731 mq->specific_address->in_transmit = GNUNET_YES;
1733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1734 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1735 mq->message_buf_size,
1736 GNUNET_i2s (&n->id),
1737 (mq->specific_address->addr != NULL)
1738 ? a2s (mq->plugin->short_name,
1739 mq->specific_address->addr,
1740 mq->specific_address->addrlen)
1742 rl->plugin->short_name);
1744 GNUNET_STATISTICS_update (stats,
1745 gettext_noop ("# bytes in message queue for other peers"),
1746 - (int64_t) mq->message_buf_size,
1748 GNUNET_STATISTICS_update (stats,
1749 gettext_noop ("# bytes pending with plugins"),
1750 mq->message_buf_size,
1753 GNUNET_CONTAINER_DLL_insert (n->cont_head,
1757 ret = rl->plugin->api->send (rl->plugin->api->cls,
1760 mq->message_buf_size,
1762 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1763 mq->specific_address->session,
1764 mq->specific_address->addr,
1765 mq->specific_address->addrlen,
1767 &transmit_send_continuation, mq);
1770 /* failure, but 'send' would not call continuation in this case,
1771 so we need to do it here! */
1772 transmit_send_continuation (mq,
1780 * Send the specified message to the specified peer.
1782 * @param client source of the transmission request (can be NULL)
1783 * @param peer_address ForeignAddressList where we should send this message
1784 * @param priority how important is the message
1785 * @param timeout how long do we have to transmit?
1786 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1787 * @param message_buf_size total size of all messages in message_buf
1788 * @param is_internal is this an internal message; these are pre-pended and
1789 * also do not count for plugins being "ready" to transmit
1790 * @param neighbour handle to the neighbour for transmission
1793 transmit_to_peer (struct TransportClient *client,
1794 struct ForeignAddressList *peer_address,
1795 unsigned int priority,
1796 struct GNUNET_TIME_Relative timeout,
1797 const char *message_buf,
1798 size_t message_buf_size,
1799 int is_internal, struct NeighbourList *neighbour)
1801 struct MessageQueue *mq;
1806 /* check for duplicate submission */
1807 mq = neighbour->messages_head;
1810 if (mq->client == client)
1812 /* client transmitted to same peer twice
1813 before getting SEND_OK! */
1821 GNUNET_STATISTICS_update (stats,
1822 gettext_noop ("# bytes in message queue for other peers"),
1825 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1826 mq->specific_address = peer_address;
1827 mq->client = client;
1828 /* FIXME: this memcpy can be up to 7% of our total runtime! */
1829 memcpy (&mq[1], message_buf, message_buf_size);
1830 mq->message_buf = (const char*) &mq[1];
1831 mq->message_buf_size = message_buf_size;
1832 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1833 mq->internal_msg = is_internal;
1834 mq->priority = priority;
1835 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1837 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1838 neighbour->messages_tail,
1841 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1842 neighbour->messages_tail,
1843 neighbour->messages_tail,
1845 try_transmission_to_peer (neighbour);
1850 * Send a plain PING (without address or our HELLO) to the given
1851 * foreign address to try to establish a connection (and validate
1852 * that the other peer is really who he claimed he is).
1854 * @param n neighbour to PING
1857 transmit_plain_ping (struct NeighbourList *n)
1859 struct ValidationEntry *ve;
1860 struct TransportPingMessage ping;
1861 struct ReadyList *rl;
1862 struct TransportPlugin *plugin;
1863 struct ForeignAddressList *fal;
1865 if (! n->public_key_valid)
1867 /* This should not happen since the other peer
1868 should send us a HELLO prior to sending his
1870 GNUNET_break_op (0);
1871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1872 "Could not transmit plain PING to `%s': public key not known\n",
1873 GNUNET_i2s (&n->id));
1876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1877 "Looking for addresses to transmit plain PING to `%s'\n",
1878 GNUNET_i2s (&n->id));
1879 for (rl = n->plugins; rl != NULL; rl = rl->next)
1881 plugin = rl->plugin;
1882 for (fal = rl->addresses; fal != NULL; fal = fal->next)
1884 if (! fal->connected)
1886 ve = GNUNET_malloc (sizeof (struct ValidationEntry));
1887 ve->transport_name = GNUNET_strdup (plugin->short_name);
1888 ve->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1890 ve->send_time = GNUNET_TIME_absolute_get();
1891 ve->session = fal->session;
1892 memcpy(&ve->publicKey,
1894 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1895 ve->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
1896 &timeout_hello_validation,
1898 GNUNET_CONTAINER_multihashmap_put (validation_map,
1901 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1902 ping.header.size = htons(sizeof(struct TransportPingMessage));
1903 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
1904 ping.challenge = htonl(ve->challenge);
1905 memcpy(&ping.target, &n->id, sizeof(struct GNUNET_PeerIdentity));
1906 GNUNET_STATISTICS_update (stats,
1907 gettext_noop ("# PING without HELLO messages sent"),
1910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1911 "Transmitting plain PING to `%s'\n",
1912 GNUNET_i2s (&n->id));
1913 transmit_to_peer (NULL,
1915 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1916 HELLO_VERIFICATION_TIMEOUT,
1917 (const char*) &ping, sizeof (ping),
1925 * Mark the given FAL entry as 'connected' (and hence preferred for
1926 * sending); also mark all others for the same peer as 'not connected'
1927 * (since only one can be preferred).
1929 * @param fal address to set to 'connected'
1932 mark_address_connected(struct ForeignAddressList *fal)
1934 struct ForeignAddressList *pos;
1935 struct ForeignAddressList *inbound;
1936 struct ForeignAddressList *outbound;
1939 GNUNET_assert (GNUNET_YES == fal->validated);
1940 if (fal->connected == GNUNET_YES)
1941 return; /* nothing to do */
1946 pos = fal->ready_list->addresses;
1949 /* Already have inbound address, and this is also an inbound address, don't switch!! */
1950 if ((GNUNET_YES == pos->connected) && (0 == pos->addrlen) && (0
1953 else if ((0 == pos->addrlen) && (GNUNET_YES == pos->connected))
1958 pos = fal->ready_list->addresses;
1961 /* Already have outbound address, and this is also an outbound address, don't switch!! */
1962 if ((GNUNET_YES == pos->connected) && (0 < pos->addrlen) && (0
1965 else if ((0 < pos->addrlen) && (GNUNET_YES == pos->connected))
1971 if (inbound != NULL)
1972 fprintf(stderr, "Peer: %s, have inbound connection.\n", GNUNET_i2s(&my_identity));
1973 if (outbound != NULL)
1974 fprintf(stderr, "Peer: %s, have outbound connection.\n", GNUNET_i2s(&my_identity));
1977 /* Have an inbound connection to this peer which is valid; our id is lower, ignore outbound connection! */
1978 if ((inbound != NULL) && (0 != fal->addrlen) && (1
1979 == GNUNET_CRYPTO_hash_xorcmp (&inbound->ready_list->neighbour->id.hashPubKey,
1980 &my_identity.hashPubKey, &null_hash)))
1983 fprintf(stderr, "Peer: %s, had inbound connection, ignoring outbound!\n", GNUNET_i2s(&my_identity));
1987 else if ((outbound != NULL) && (0 == fal->addrlen) && ((-1
1988 == GNUNET_CRYPTO_hash_xorcmp (&outbound->ready_list->neighbour->id.hashPubKey,
1989 &my_identity.hashPubKey, &null_hash))))
1992 fprintf(stderr, "Peer: %s, have outbound connection, ignoring inbound!\n", GNUNET_i2s(&my_identity));
1997 pos = fal->ready_list->addresses;
2000 if ((GNUNET_YES == pos->connected) && (0 < pos->addrlen))
2004 GNUNET_ERROR_TYPE_DEBUG,
2005 "Marking address `%s' as no longer connected (due to connect on other address)\n",
2006 a2s (pos->ready_list->plugin->short_name, pos->addr,
2009 GNUNET_break (cnt == GNUNET_YES);
2012 fprintf(stderr, "Peer: %s, setting %s connection to disconnected.\n", GNUNET_i2s(&my_identity), (0 == pos->addrlen) ? "INBOUND" : "OUTBOUND");
2014 pos->connected = GNUNET_NO;
2015 GNUNET_STATISTICS_update (stats,
2016 gettext_noop ("# connected addresses"), -1,
2022 fal->connected = GNUNET_YES;
2023 if (GNUNET_YES == cnt)
2025 GNUNET_STATISTICS_update (stats, gettext_noop ("# connected addresses"),
2032 * Find an address in any of the available transports for
2033 * the given neighbour that would be good for message
2034 * transmission. This is essentially the transport selection
2037 * @param neighbour for whom to select an address
2038 * @return selected address, NULL if we have none
2040 struct ForeignAddressList *
2041 find_ready_address(struct NeighbourList *neighbour)
2043 struct ReadyList *head = neighbour->plugins;
2044 struct ForeignAddressList *addresses;
2045 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
2046 struct ForeignAddressList *best_address;
2048 /* Hack to prefer unix domain sockets */
2049 struct ForeignAddressList *unix_address = NULL;
2051 best_address = NULL;
2052 while (head != NULL)
2054 addresses = head->addresses;
2055 while (addresses != NULL)
2057 if ( (addresses->timeout.abs_value < now.abs_value) &&
2058 (addresses->connected == GNUNET_YES) )
2061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062 "Marking long-time inactive connection to `%4s' as down.\n",
2063 GNUNET_i2s (&neighbour->id));
2065 GNUNET_STATISTICS_update (stats,
2066 gettext_noop ("# connected addresses"),
2069 addresses->connected = GNUNET_NO;
2071 addresses = addresses->next;
2074 addresses = head->addresses;
2075 while (addresses != NULL)
2078 if (addresses->addr != NULL)
2079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2080 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
2081 a2s (head->plugin->short_name,
2083 addresses->addrlen),
2084 GNUNET_i2s (&neighbour->id),
2085 addresses->connected,
2086 addresses->in_transmit,
2087 addresses->validated,
2088 addresses->connect_attempts,
2089 (unsigned long long) addresses->timeout.abs_value,
2090 (unsigned int) addresses->distance);
2092 if (0==strcmp(head->plugin->short_name,"unix"))
2094 if ( (unix_address == NULL) ||
2095 ( (unix_address != NULL) &&
2096 (addresses->latency.rel_value < unix_address->latency.rel_value) ) )
2097 unix_address = addresses;
2099 if ( ( (best_address == NULL) ||
2100 (addresses->connected == GNUNET_YES) ||
2101 (best_address->connected == GNUNET_NO) ) &&
2102 (addresses->in_transmit == GNUNET_NO) &&
2103 ( (best_address == NULL) ||
2104 (addresses->latency.rel_value < best_address->latency.rel_value)) )
2105 best_address = addresses;
2106 /* FIXME: also give lower-latency addresses that are not
2107 connected a chance some times... */
2108 addresses = addresses->next;
2110 if (unix_address != NULL)
2114 if (unix_address != NULL)
2116 best_address = unix_address;
2118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2119 "Found UNIX address, forced this address\n");
2122 if (best_address != NULL)
2125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2126 "Best address found (`%s') has latency of %llu ms.\n",
2127 (best_address->addrlen > 0)
2128 ? a2s (best_address->ready_list->plugin->short_name,
2130 best_address->addrlen)
2132 best_address->latency.rel_value);
2137 GNUNET_STATISTICS_update (stats,
2138 gettext_noop ("# transmission attempts failed (no address)"),
2143 return best_address;
2150 struct GeneratorContext
2152 struct TransportPlugin *plug_pos;
2153 struct OwnAddressList *addr_pos;
2154 struct GNUNET_TIME_Absolute expiration;
2162 address_generator (void *cls, size_t max, void *buf)
2164 struct GeneratorContext *gc = cls;
2167 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
2169 gc->plug_pos = gc->plug_pos->next;
2170 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
2172 if (NULL == gc->plug_pos)
2177 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
2180 gc->addr_pos->addrlen, buf, max);
2181 gc->addr_pos = gc->addr_pos->next;
2187 * Construct our HELLO message from all of the addresses of
2188 * all of the transports.
2191 * @param tc scheduler context
2194 refresh_hello_task (void *cls,
2195 const struct GNUNET_SCHEDULER_TaskContext *tc)
2197 struct GNUNET_HELLO_Message *hello;
2198 struct TransportClient *cpos;
2199 struct NeighbourList *npos;
2200 struct GeneratorContext gc;
2202 hello_task = GNUNET_SCHEDULER_NO_TASK;
2203 gc.plug_pos = plugins;
2204 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
2205 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2206 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
2208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2209 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
2211 GNUNET_STATISTICS_update (stats,
2212 gettext_noop ("# refreshed my HELLO"),
2216 while (cpos != NULL)
2218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219 "Transmitting my HELLO to client!\n");
2220 transmit_to_client (cpos,
2221 (const struct GNUNET_MessageHeader *) hello,
2226 GNUNET_free_non_null (our_hello);
2228 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
2229 for (npos = neighbours; npos != NULL; npos = npos->next)
2231 if (! npos->received_pong)
2234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2235 "Transmitting updated `%s' to neighbour `%4s'\n",
2236 "HELLO", GNUNET_i2s (&npos->id));
2238 GNUNET_STATISTICS_update (stats,
2239 gettext_noop ("# transmitted my HELLO to other peers"),
2242 transmit_to_peer (NULL, NULL, 0,
2243 HELLO_ADDRESS_EXPIRATION,
2244 (const char *) our_hello,
2245 GNUNET_HELLO_size(our_hello),
2252 * Schedule task to refresh hello (unless such a
2253 * task exists already).
2258 #if DEBUG_TRANSPORT_HELLO
2259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2260 "refresh_hello() called!\n");
2262 if (hello_task != GNUNET_SCHEDULER_NO_TASK)
2265 = GNUNET_SCHEDULER_add_now (&refresh_hello_task,
2271 * Iterator over hash map entries that NULLs the session of validation
2272 * entries that match the given session.
2274 * @param cls closure (the 'struct Session*' to match against)
2275 * @param key current key code (peer ID, not used)
2276 * @param value value in the hash map ('struct ValidationEntry*')
2277 * @return GNUNET_YES (we should continue to iterate)
2280 remove_session_validations (void *cls,
2281 const GNUNET_HashCode * key,
2284 struct Session *session = cls;
2285 struct ValidationEntry *ve = value;
2287 if (session == ve->session)
2294 * We've been disconnected from the other peer (for some
2295 * connection-oriented transport). Either quickly
2296 * re-establish the connection or signal the disconnect
2299 * Only signal CORE level disconnect if ALL addresses
2300 * for the peer are exhausted.
2302 * @param p overall plugin context
2303 * @param nl neighbour that was disconnected
2306 try_fast_reconnect (struct TransportPlugin *p,
2307 struct NeighbourList *nl)
2309 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2310 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2311 "try_fast_reconnect not implemented!\n");
2312 /* Note: the idea here is to hide problems with transports (or
2313 switching between plugins) from the core to eliminate the need to
2314 re-negotiate session keys and the like; OTOH, we should tell core
2315 quickly (much faster than timeout) `if a connection was lost and
2316 could not be re-established (i.e. other peer went down or is
2317 unable / refuses to communicate);
2319 So we should consider:
2320 1) ideally: our own willingness / need to connect
2321 2) prior failures to connect to this peer (by plugin)
2322 3) ideally: reasons why other peer terminated (as far as knowable)
2324 Most importantly, it must be POSSIBLE for another peer to terminate
2325 a connection for a while (without us instantly re-establishing it).
2326 Similarly, if another peer is gone we should quickly notify CORE.
2327 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2328 on the other end), we should reconnect in such a way that BOTH CORE
2329 services never even notice.
2330 Furthermore, the same mechanism (or small variation) could be used
2331 to switch to a better-performing plugin (ATS).
2333 Finally, this needs to be tested throughly... */
2336 * GNUNET_NO in the call below makes transport disconnect the peer,
2337 * even if only a single address (out of say, six) went away. This
2338 * function must be careful to ONLY disconnect if the peer is gone,
2339 * not just a specific address.
2341 * More specifically, half the places it was used had it WRONG.
2344 /* No reconnect, signal disconnect instead! */
2347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2349 "try_fast_reconnect");
2351 GNUNET_STATISTICS_update (stats,
2352 gettext_noop ("# disconnects due to try_fast_reconnect"),
2356 disconnect_neighbour (nl, GNUNET_YES);
2362 * Function that will be called whenever the plugin internally
2363 * cleans up a session pointer and hence the service needs to
2364 * discard all of those sessions as well. Plugins that do not
2365 * use sessions can simply omit calling this function and always
2366 * use NULL wherever a session pointer is needed.
2368 * @param cls closure
2369 * @param peer which peer was the session for
2370 * @param session which session is being destoyed
2373 plugin_env_session_end (void *cls,
2374 const struct GNUNET_PeerIdentity *peer,
2375 struct Session *session)
2377 struct TransportPlugin *p = cls;
2378 struct NeighbourList *nl;
2379 struct ReadyList *rl;
2380 struct ForeignAddressList *pos;
2381 struct ForeignAddressList *prev;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Session ended with peer `%4s', %s\n",
2387 "plugin_env_session_end");
2389 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2390 &remove_session_validations,
2392 nl = find_neighbour (peer);
2396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397 "No neighbour record found for peer `%4s'\n",
2400 return; /* was never marked as connected */
2405 if (rl->plugin == p)
2412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2413 "Plugin was associated with peer `%4s'\n",
2416 GNUNET_STATISTICS_update (stats,
2417 gettext_noop ("# disconnects due to session end"),
2420 disconnect_neighbour (nl, GNUNET_YES);
2424 pos = rl->addresses;
2425 while ( (pos != NULL) &&
2426 (pos->session != session) )
2434 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2435 "Session was never marked as ready for peer `%4s'\n",
2439 int validations_pending = GNUNET_CONTAINER_multihashmap_contains (validation_map, &peer->hashPubKey);
2441 /* No session was marked as ready, but we have pending validations so do not disconnect from neighbour */
2442 if (validations_pending ==GNUNET_YES)
2445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2446 "Not disconnecting from peer `%4s due to pending address validations\n", GNUNET_i2s(peer));
2451 //FIXME: This conflicts with inbound tcp connections and tcp nat ... debugging in progress
2452 GNUNET_STATISTICS_update (stats,
2453 gettext_noop ("# disconnects due to unready session"),
2457 disconnect_neighbour (nl, GNUNET_YES);
2458 return; /* was never marked as connected */
2460 pos->session = NULL;
2461 pos->connected = GNUNET_NO;
2462 if (pos->addrlen != 0)
2464 if (nl->received_pong != GNUNET_NO)
2466 GNUNET_STATISTICS_update (stats,
2467 gettext_noop ("# try_fast_reconnect thanks to plugin_env_session_end"),
2470 if (GNUNET_YES == pos->connected)
2471 try_fast_reconnect (p, nl);
2475 GNUNET_STATISTICS_update (stats,
2476 gettext_noop ("# disconnects due to missing pong"),
2479 /* FIXME this is never true?! See: line 2416*/
2480 if (GNUNET_YES == pos->connected)
2481 disconnect_neighbour (nl, GNUNET_YES);
2486 GNUNET_STATISTICS_update (stats,
2487 gettext_noop ("# connected addresses"),
2491 /* was inbound connection, free 'pos' */
2493 rl->addresses = pos->next;
2495 prev->next = pos->next;
2496 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2498 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2499 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2501 GNUNET_free_non_null(pos->ressources);
2502 GNUNET_free_non_null(pos->quality);
2503 ats_modify_problem_state (ats, ATS_MODIFIED);
2505 if (GNUNET_YES != pos->connected)
2507 /* nothing else to do, connection was never up... */
2513 if (nl->received_pong == GNUNET_NO)
2515 GNUNET_STATISTICS_update (stats,
2516 gettext_noop ("# disconnects due to NO pong"),
2519 disconnect_neighbour (nl, GNUNET_YES);
2520 return; /* nothing to do, never connected... */
2522 /* check if we have any validated addresses left */
2523 pos = rl->addresses;
2526 if (GNUNET_YES == pos->validated)
2528 GNUNET_STATISTICS_update (stats,
2529 gettext_noop ("# try_fast_reconnect thanks to validated_address"),
2532 try_fast_reconnect (p, nl);
2537 /* no valid addresses left, signal disconnect! */
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Disconnecting peer `%4s', %s\n",
2543 "plugin_env_session_end");
2545 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2546 * it means there aren't any left for this PLUGIN/PEER combination! So
2547 * calling disconnect_neighbour here with GNUNET_NO forces disconnect
2548 * when it isn't necessary. Using GNUNET_YES at least checks to see
2549 * if there are any addresses that work first, so as not to overdo it.
2552 GNUNET_STATISTICS_update (stats,
2553 gettext_noop ("# disconnects due to plugin_env_session_end"),
2556 disconnect_neighbour (nl, GNUNET_YES);
2561 * Function that must be called by each plugin to notify the
2562 * transport service about the addresses under which the transport
2563 * provided by the plugin can be reached.
2565 * @param cls closure
2566 * @param add_remove GNUNET_YES to add, GNUNET_NO to remove the address
2567 * @param addr one of the addresses of the host, NULL for the last address
2568 * the specific address format depends on the transport
2569 * @param addrlen length of the address
2572 plugin_env_notify_address (void *cls,
2577 struct TransportPlugin *p = cls;
2578 struct OwnAddressList *al;
2579 struct OwnAddressList *prev;
2581 GNUNET_assert (p->api != NULL);
2583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2584 (add_remove == GNUNET_YES)
2585 ? "Adding `%s':%s to the set of our addresses\n"
2586 : "Removing `%s':%s from the set of our addresses\n",
2591 GNUNET_assert (addr != NULL);
2592 if (GNUNET_NO == add_remove)
2598 if ( (addrlen == al->addrlen) &&
2599 (0 == memcmp (addr, &al[1], addrlen)) )
2602 p->addresses = al->next;
2604 prev->next = al->next;
2615 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2616 al->next = p->addresses;
2618 al->addrlen = addrlen;
2619 memcpy (&al[1], addr, addrlen);
2625 * Notify all of our clients about a peer connecting.
2628 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2629 struct GNUNET_TIME_Relative latency,
2632 struct ConnectInfoMessage * cim;
2633 struct TransportClient *cpos;
2637 if (0 == memcmp (peer,
2639 sizeof (struct GNUNET_PeerIdentity)))
2645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2646 "Notifying clients about connection with `%s'\n",
2649 GNUNET_STATISTICS_update (stats,
2650 gettext_noop ("# peers connected"),
2655 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2656 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2660 cim = GNUNET_malloc (size);
2661 cim->header.size = htons (size);
2662 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2663 cim->ats_count = htonl(2);
2664 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2665 (&(cim->ats))[0].value = htonl (distance);
2666 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2667 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2668 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2669 (&(cim->ats))[2].value = htonl (0);
2670 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2672 /* notify ats about connecting peer */
2673 /* notify ats about connecting peer */
2674 if ((ats != NULL) && (shutdown_in_progress == GNUNET_NO))
2676 ats_modify_problem_state(ats, ATS_MODIFIED);
2677 ats_calculate_bandwidth_distribution (ats, stats);
2682 while (cpos != NULL)
2684 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2693 * Notify all of our clients about a peer disconnecting.
2696 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2698 struct DisconnectInfoMessage dim;
2699 struct TransportClient *cpos;
2701 if (0 == memcmp (peer,
2703 sizeof (struct GNUNET_PeerIdentity)))
2709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710 "Notifying clients about lost connection to `%s'\n",
2713 GNUNET_STATISTICS_update (stats,
2714 gettext_noop ("# peers connected"),
2717 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2718 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2719 dim.reserved = htonl (0);
2720 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2722 /* notify ats about connecting peer */
2723 if ((ats != NULL) && (shutdown_in_progress == GNUNET_NO))
2725 ats_modify_problem_state(ats, ATS_MODIFIED);
2726 ats_calculate_bandwidth_distribution (ats, stats);
2730 while (cpos != NULL)
2732 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2739 * Find a ForeignAddressList entry for the given neighbour
2740 * that matches the given address and transport.
2742 * @param neighbour which peer we care about
2743 * @param tname name of the transport plugin
2744 * @param session session to look for, NULL for 'any'; otherwise
2745 * can be used for the service to "learn" this session ID
2747 * @param addr binary address
2748 * @param addrlen length of addr
2749 * @return NULL if no such entry exists
2751 static struct ForeignAddressList *
2752 find_peer_address(struct NeighbourList *neighbour,
2754 struct Session *session,
2758 struct ReadyList *head;
2759 struct ForeignAddressList *pos;
2761 head = neighbour->plugins;
2762 while (head != NULL)
2764 if (0 == strcmp (tname, head->plugin->short_name))
2770 pos = head->addresses;
2771 while ( (pos != NULL) &&
2772 ( (pos->addrlen != addrlen) ||
2773 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2775 if ( (session != NULL) &&
2776 (pos->session == session) )
2780 if ( (session != NULL) && (pos != NULL) )
2781 pos->session = session; /* learn it! */
2787 * Get the peer address struct for the given neighbour and
2788 * address. If it doesn't yet exist, create it.
2790 * @param neighbour which peer we care about
2791 * @param tname name of the transport plugin
2792 * @param session session of the plugin, or NULL for none
2793 * @param addr binary address
2794 * @param addrlen length of addr
2795 * @return NULL if we do not have a transport plugin for 'tname'
2797 static struct ForeignAddressList *
2798 add_peer_address (struct NeighbourList *neighbour,
2800 struct Session *session,
2804 struct ReadyList *head;
2805 struct ForeignAddressList *ret;
2808 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2811 head = neighbour->plugins;
2813 while (head != NULL)
2815 if (0 == strcmp (tname, head->plugin->short_name))
2821 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2822 ret->session = session;
2823 if ((addrlen > 0) && (addr != NULL))
2825 ret->addr = (const char*) &ret[1];
2826 memcpy (&ret[1], addr, addrlen);
2833 ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
2834 for (c=0; c<available_ressources; c++)
2836 struct ATS_ressource_entry *r = ret->ressources;
2838 r[c].atis_index = ressources[c].atis_index;
2839 if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
2841 r[c].c = ressources[c].c_unix;
2843 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
2845 r[c].c = ressources[c].c_udp;
2847 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
2849 r[c].c = ressources[c].c_tcp;
2851 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
2853 r[c].c = ressources[c].c_http;
2855 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
2857 r[c].c = ressources[c].c_https;
2859 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
2861 r[c].c = ressources[c].c_wlan;
2865 r[c].c = ressources[c].c_default;
2866 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2867 "Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!\n",
2868 GNUNET_i2s(&neighbour->id),
2869 neighbour->plugins->plugin->short_name);
2873 ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
2874 ret->addrlen = addrlen;
2875 ret->expires = GNUNET_TIME_relative_to_absolute
2876 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2877 ret->latency = GNUNET_TIME_relative_get_forever();
2879 ret->timeout = GNUNET_TIME_relative_to_absolute
2880 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2881 ret->ready_list = head;
2882 ret->next = head->addresses;
2883 head->addresses = ret;
2889 * Closure for 'add_validated_address'.
2891 struct AddValidatedAddressContext
2894 * Entry that has been validated.
2896 const struct ValidationEntry *ve;
2899 * Flag set after we have added the address so
2900 * that we terminate the iteration next time.
2907 * Callback function used to fill a buffer of max bytes with a list of
2908 * addresses in the format used by HELLOs. Should use
2909 * "GNUNET_HELLO_add_address" as a helper function.
2911 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2912 * @param max maximum number of bytes that can be written to buf
2913 * @param buf where to write the address information
2914 * @return number of bytes written, 0 to signal the
2915 * end of the iteration.
2918 add_validated_address (void *cls,
2919 size_t max, void *buf)
2921 struct AddValidatedAddressContext *avac = cls;
2922 const struct ValidationEntry *ve = avac->ve;
2924 if (GNUNET_YES == avac->done)
2926 avac->done = GNUNET_YES;
2927 return GNUNET_HELLO_add_address (ve->transport_name,
2928 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2938 * Closure for 'check_address_exists'.
2940 struct CheckAddressExistsClosure
2943 * Address to check for.
2948 * Name of the transport.
2955 struct Session *session;
2958 * Set to GNUNET_YES if the address exists.
2971 * Iterator over hash map entries. Checks if the given
2972 * validation entry is for the same address as what is given
2975 * @param cls the 'struct CheckAddressExistsClosure*'
2976 * @param key current key code (ignored)
2977 * @param value value in the hash map ('struct ValidationEntry')
2978 * @return GNUNET_YES if we should continue to
2979 * iterate (mismatch), GNUNET_NO if not (entry matched)
2982 check_address_exists (void *cls,
2983 const GNUNET_HashCode * key,
2986 struct CheckAddressExistsClosure *caec = cls;
2987 struct ValidationEntry *ve = value;
2989 if ( (0 == strcmp (caec->tname,
2990 ve->transport_name)) &&
2991 (caec->addrlen == ve->addrlen) &&
2992 (0 == memcmp (caec->addr,
2996 caec->exists = GNUNET_YES;
2999 if ( (ve->session != NULL) &&
3000 (caec->session == ve->session) )
3002 caec->exists = GNUNET_YES;
3010 neighbour_timeout_task (void *cls,
3011 const struct GNUNET_SCHEDULER_TaskContext *tc)
3013 struct NeighbourList *n = cls;
3016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3017 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
3019 GNUNET_STATISTICS_update (stats,
3020 gettext_noop ("# disconnects due to timeout"),
3023 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3024 disconnect_neighbour (n, GNUNET_NO);
3029 * Schedule the job that will cause us to send a PING to the
3030 * foreign address to evaluate its validity and latency.
3032 * @param fal address to PING
3035 schedule_next_ping (struct ForeignAddressList *fal);
3039 * Add the given address to the list of foreign addresses
3040 * available for the given peer (check for duplicates).
3042 * @param cls the respective 'struct NeighbourList' to update
3043 * @param tname name of the transport
3044 * @param expiration expiration time
3045 * @param addr the address
3046 * @param addrlen length of the address
3047 * @return GNUNET_OK (always)
3050 add_to_foreign_address_list (void *cls,
3052 struct GNUNET_TIME_Absolute expiration,
3056 struct NeighbourList *n = cls;
3057 struct ForeignAddressList *fal;
3060 GNUNET_STATISTICS_update (stats,
3061 gettext_noop ("# valid peer addresses returned by PEERINFO"),
3065 fal = find_peer_address (n, tname, NULL, addr, addrlen);
3068 #if DEBUG_TRANSPORT_HELLO
3069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
3071 a2s (tname, addr, addrlen),
3073 GNUNET_i2s (&n->id),
3074 expiration.abs_value);
3076 fal = add_peer_address (n, tname, NULL, addr, addrlen);
3079 GNUNET_STATISTICS_update (stats,
3080 gettext_noop ("# previously validated addresses lacking transport"),
3086 fal->expires = GNUNET_TIME_absolute_max (expiration,
3088 schedule_next_ping (fal);
3094 fal->expires = GNUNET_TIME_absolute_max (expiration,
3100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3101 "Failed to add new address for `%4s'\n",
3102 GNUNET_i2s (&n->id));
3106 if (fal->validated == GNUNET_NO)
3108 fal->validated = GNUNET_YES;
3109 GNUNET_STATISTICS_update (stats,
3110 gettext_noop ("# peer addresses considered valid"),
3114 if (try == GNUNET_YES)
3117 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3118 "Have new addresses, will try to trigger transmissions.\n");
3120 try_transmission_to_peer (n);
3127 * Add addresses in validated HELLO "h" to the set of addresses
3128 * we have for this peer.
3130 * @param cls closure ('struct NeighbourList*')
3131 * @param peer id of the peer, NULL for last call
3132 * @param h hello message for the peer (can be NULL)
3133 * @param err_msg NULL if successful, otherwise contains error message
3136 add_hello_for_peer (void *cls,
3137 const struct GNUNET_PeerIdentity *peer,
3138 const struct GNUNET_HELLO_Message *h,
3139 const char *err_msg)
3141 struct NeighbourList *n = cls;
3143 if (err_msg != NULL)
3146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3147 _("Error in communication with PEERINFO service: %s\n"),
3154 GNUNET_STATISTICS_update (stats,
3155 gettext_noop ("# outstanding peerinfo iterate requests"),
3162 return; /* no HELLO available */
3164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3165 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
3169 if (GNUNET_YES != n->public_key_valid)
3171 GNUNET_HELLO_get_key (h, &n->publicKey);
3172 n->public_key_valid = GNUNET_YES;
3174 GNUNET_HELLO_iterate_addresses (h,
3176 &add_to_foreign_address_list,
3182 * Create a fresh entry in our neighbour list for the given peer.
3183 * Will try to transmit our current HELLO to the new neighbour.
3184 * Do not call this function directly, use 'setup_peer_check_blacklist.
3186 * @param peer the peer for which we create the entry
3187 * @param do_hello should we schedule transmitting a HELLO
3188 * @return the new neighbour list entry
3190 static struct NeighbourList *
3191 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
3194 struct NeighbourList *n;
3195 struct TransportPlugin *tp;
3196 struct ReadyList *rl;
3198 GNUNET_assert (0 != memcmp (peer,
3200 sizeof (struct GNUNET_PeerIdentity)));
3202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3203 "Setting up state for neighbour `%4s'\n",
3206 GNUNET_STATISTICS_update (stats,
3207 gettext_noop ("# active neighbours"),
3210 n = GNUNET_malloc (sizeof (struct NeighbourList));
3211 n->next = neighbours;
3215 GNUNET_TIME_relative_to_absolute
3216 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3217 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
3218 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
3219 MAX_BANDWIDTH_CARRY_S);
3223 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
3225 rl = GNUNET_malloc (sizeof (struct ReadyList));
3227 rl->next = n->plugins;
3230 rl->addresses = NULL;
3234 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
3236 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3237 &neighbour_timeout_task, n);
3240 GNUNET_STATISTICS_update (stats,
3241 gettext_noop ("# peerinfo new neighbor iterate requests"),
3244 GNUNET_STATISTICS_update (stats,
3245 gettext_noop ("# outstanding peerinfo iterate requests"),
3248 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
3249 GNUNET_TIME_UNIT_FOREVER_REL,
3250 &add_hello_for_peer, n);
3252 GNUNET_STATISTICS_update (stats,
3253 gettext_noop ("# HELLO's sent to new neighbors"),
3256 if (NULL != our_hello)
3257 transmit_to_peer (NULL, NULL, 0,
3258 HELLO_ADDRESS_EXPIRATION,
3259 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
3267 * Function called after we have checked if communicating
3268 * with a given peer is acceptable.
3270 * @param cls closure
3271 * @param n NULL if communication is not acceptable
3273 typedef void (*SetupContinuation)(void *cls,
3274 struct NeighbourList *n);
3278 * Information kept for each client registered to perform
3284 * This is a linked list.
3286 struct Blacklisters *next;
3289 * This is a linked list.
3291 struct Blacklisters *prev;
3294 * Client responsible for this entry.
3296 struct GNUNET_SERVER_Client *client;
3299 * Blacklist check that we're currently performing.
3301 struct BlacklistCheck *bc;
3307 * Head of DLL of blacklisting clients.
3309 static struct Blacklisters *bl_head;
3312 * Tail of DLL of blacklisting clients.
3314 static struct Blacklisters *bl_tail;
3318 * Context we use when performing a blacklist check.
3320 struct BlacklistCheck
3324 * This is a linked list.
3326 struct BlacklistCheck *next;
3329 * This is a linked list.
3331 struct BlacklistCheck *prev;
3334 * Peer being checked.
3336 struct GNUNET_PeerIdentity peer;
3339 * Option for setup neighbour afterwards.
3344 * Continuation to call with the result.
3346 SetupContinuation cont;
3354 * Current transmission request handle for this client, or NULL if no
3355 * request is pending.
3357 struct GNUNET_CONNECTION_TransmitHandle *th;
3360 * Our current position in the blacklisters list.
3362 struct Blacklisters *bl_pos;
3365 * Current task performing the check.
3367 GNUNET_SCHEDULER_TaskIdentifier task;
3372 * Head of DLL of active blacklisting queries.
3374 static struct BlacklistCheck *bc_head;
3377 * Tail of DLL of active blacklisting queries.
3379 static struct BlacklistCheck *bc_tail;
3383 * Perform next action in the blacklist check.
3385 * @param cls the 'struct BlacklistCheck*'
3389 do_blacklist_check (void *cls,
3390 const struct GNUNET_SCHEDULER_TaskContext *tc);
3393 * Transmit blacklist query to the client.
3395 * @param cls the 'struct BlacklistCheck'
3396 * @param size number of bytes allowed
3397 * @param buf where to copy the message
3398 * @return number of bytes copied to buf
3401 transmit_blacklist_message (void *cls,
3405 struct BlacklistCheck *bc = cls;
3406 struct Blacklisters *bl;
3407 struct BlacklistMessage bm;
3412 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3413 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3415 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3416 "Failed to send blacklist test for peer `%s' to client\n",
3417 GNUNET_i2s (&bc->peer));
3421 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3422 "Sending blacklist test for peer `%s' to client\n",
3423 GNUNET_i2s (&bc->peer));
3426 bm.header.size = htons (sizeof (struct BlacklistMessage));
3427 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3428 bm.is_allowed = htonl (0);
3430 memcpy (buf, &bm, sizeof (bm));
3431 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3437 * Perform next action in the blacklist check.
3439 * @param cls the 'struct BlacklistCheck*'
3443 do_blacklist_check (void *cls,
3444 const struct GNUNET_SCHEDULER_TaskContext *tc)
3446 struct BlacklistCheck *bc = cls;
3447 struct Blacklisters *bl;
3449 bc->task = GNUNET_SCHEDULER_NO_TASK;
3454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3455 "No blacklist clients active, will now setup neighbour record for peer `%s'\n",
3456 GNUNET_i2s (&bc->peer));
3458 bc->cont (bc->cont_cls,
3459 setup_new_neighbour (&bc->peer, bc->do_hello));
3466 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3467 sizeof (struct BlacklistMessage),
3468 GNUNET_TIME_UNIT_FOREVER_REL,
3469 &transmit_blacklist_message,
3476 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3477 * does not yet exist, check the blacklist. If the blacklist says creating
3478 * one is acceptable, create one and call the continuation; otherwise
3479 * call the continuation with NULL.
3481 * @param peer peer to setup or look up a struct NeighbourList for
3482 * @param do_hello should we also schedule sending our HELLO to the peer
3483 * if this is a new record
3484 * @param cont function to call with the 'struct NeigbhbourList*'
3485 * @param cont_cls closure for cont
3488 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3490 SetupContinuation cont,
3493 struct NeighbourList *n;
3494 struct BlacklistCheck *bc;
3496 n = find_neighbour(peer);
3500 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3501 "Neighbour record exists for peer `%s'\n",
3508 if (bl_head == NULL)
3511 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3513 setup_new_neighbour(peer, do_hello);
3516 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3517 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3519 bc->do_hello = do_hello;
3521 bc->cont_cls = cont_cls;
3522 bc->bl_pos = bl_head;
3523 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3529 * Function called with the result of querying a new blacklister about
3530 * it being allowed (or not) to continue to talk to an existing neighbour.
3532 * @param cls the original 'struct NeighbourList'
3533 * @param n NULL if we need to disconnect
3536 confirm_or_drop_neighbour (void *cls,
3537 struct NeighbourList *n)
3539 struct NeighbourList * orig = cls;
3544 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3545 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3546 "confirm_or_drop_neighboUr");
3548 GNUNET_STATISTICS_update (stats,
3549 gettext_noop ("# disconnects due to blacklist"),
3552 disconnect_neighbour (orig, GNUNET_NO);
3558 * Handle a request to start a blacklist.
3560 * @param cls closure (always NULL)
3561 * @param client identification of the client
3562 * @param message the actual message
3565 handle_blacklist_init (void *cls,
3566 struct GNUNET_SERVER_Client *client,
3567 const struct GNUNET_MessageHeader *message)
3569 struct Blacklisters *bl;
3570 struct BlacklistCheck *bc;
3571 struct NeighbourList *n;
3576 if (bl->client == client)
3579 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3584 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3585 bl->client = client;
3586 GNUNET_SERVER_client_keep (client);
3587 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3588 /* confirm that all existing connections are OK! */
3592 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3593 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3595 bc->do_hello = GNUNET_NO;
3596 bc->cont = &confirm_or_drop_neighbour;
3599 if (n == neighbours) /* all would wait for the same client, no need to
3600 create more than just the first task right now */
3601 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3609 * Handle a request to blacklist a peer.
3611 * @param cls closure (always NULL)
3612 * @param client identification of the client
3613 * @param message the actual message
3616 handle_blacklist_reply (void *cls,
3617 struct GNUNET_SERVER_Client *client,
3618 const struct GNUNET_MessageHeader *message)
3620 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3621 struct Blacklisters *bl;
3622 struct BlacklistCheck *bc;
3625 while ( (bl != NULL) &&
3626 (bl->client != client) )
3631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3632 "Blacklist client disconnected\n");
3634 /* FIXME: other error handling here!? */
3635 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3640 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3644 "Blacklist check failed, peer not allowed\n");
3646 bc->cont (bc->cont_cls, NULL);
3647 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3654 "Blacklist check succeeded, continuing with checks\n");
3656 bc->bl_pos = bc->bl_pos->next;
3657 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3660 /* check if any other bc's are waiting for this blacklister */
3664 if ( (bc->bl_pos == bl) &&
3665 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3666 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3674 * Send periodic PING messages to a given foreign address.
3676 * @param cls our 'struct PeriodicValidationContext*'
3677 * @param tc task context
3680 send_periodic_ping (void *cls,
3681 const struct GNUNET_SCHEDULER_TaskContext *tc)
3683 struct ForeignAddressList *peer_address = cls;
3684 struct TransportPlugin *tp;
3685 struct ValidationEntry *va;
3686 struct NeighbourList *neighbour;
3687 struct TransportPingMessage ping;
3688 struct CheckAddressExistsClosure caec;
3690 uint16_t hello_size;
3694 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3695 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3697 tp = peer_address->ready_list->plugin;
3698 neighbour = peer_address->ready_list->neighbour;
3699 if (GNUNET_YES != neighbour->public_key_valid)
3701 /* no public key yet, try again later */
3702 schedule_next_ping (peer_address);
3705 caec.addr = peer_address->addr;
3706 caec.addrlen = peer_address->addrlen;
3707 caec.tname = tp->short_name;
3708 caec.session = peer_address->session;
3709 caec.exists = GNUNET_NO;
3711 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3712 &check_address_exists,
3714 if (caec.exists == GNUNET_YES)
3716 /* During validation attempts we will likely trigger the other
3717 peer trying to validate our address which in turn will cause
3718 it to send us its HELLO, so we expect to hit this case rather
3719 frequently. Only print something if we are very verbose. */
3720 #if DEBUG_TRANSPORT > 1
3721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3722 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3723 (peer_address->addr != NULL)
3724 ? a2s (tp->short_name,
3726 peer_address->addrlen)
3729 GNUNET_i2s (&neighbour->id));
3731 schedule_next_ping (peer_address);
3734 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3735 va->transport_name = GNUNET_strdup (tp->short_name);
3736 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3738 va->send_time = GNUNET_TIME_absolute_get();
3739 va->session = peer_address->session;
3740 if (peer_address->addr != NULL)
3742 va->addr = (const void*) &va[1];
3743 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3744 va->addrlen = peer_address->addrlen;
3746 memcpy(&va->publicKey,
3747 &neighbour->publicKey,
3748 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3750 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3751 &timeout_hello_validation,
3753 GNUNET_CONTAINER_multihashmap_put (validation_map,
3754 &neighbour->id.hashPubKey,
3756 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3758 if (peer_address->validated != GNUNET_YES)
3759 hello_size = GNUNET_HELLO_size(our_hello);
3763 tsize = sizeof(struct TransportPingMessage) + hello_size;
3765 if (peer_address->addr != NULL)
3767 slen = strlen (tp->short_name) + 1;
3768 tsize += slen + peer_address->addrlen;
3772 slen = 0; /* make gcc happy */
3774 message_buf = GNUNET_malloc(tsize);
3775 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3776 ping.challenge = htonl(va->challenge);
3777 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3778 if (peer_address->validated != GNUNET_YES)
3780 memcpy(message_buf, our_hello, hello_size);
3783 if (peer_address->addr != NULL)
3785 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3786 peer_address->addrlen +
3788 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3791 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3793 peer_address->addrlen);
3797 ping.header.size = htons(sizeof(struct TransportPingMessage));
3800 memcpy(&message_buf[hello_size],
3802 sizeof(struct TransportPingMessage));
3804 #if DEBUG_TRANSPORT_REVALIDATION
3805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3806 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3807 (peer_address->addr != NULL)
3808 ? a2s (peer_address->plugin->short_name,
3810 peer_address->addrlen)
3813 GNUNET_i2s (&neighbour->id),
3814 "HELLO", hello_size,
3817 if (peer_address->validated != GNUNET_YES)
3818 GNUNET_STATISTICS_update (stats,
3819 gettext_noop ("# PING with HELLO messages sent"),
3823 GNUNET_STATISTICS_update (stats,
3824 gettext_noop ("# PING without HELLO messages sent"),
3827 GNUNET_STATISTICS_update (stats,
3828 gettext_noop ("# PING messages sent for re-validation"),
3831 transmit_to_peer (NULL, peer_address,
3832 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3833 HELLO_VERIFICATION_TIMEOUT,
3835 GNUNET_YES, neighbour);
3836 GNUNET_free(message_buf);
3837 schedule_next_ping (peer_address);
3842 * Schedule the job that will cause us to send a PING to the
3843 * foreign address to evaluate its validity and latency.
3845 * @param fal address to PING
3848 schedule_next_ping (struct ForeignAddressList *fal)
3850 struct GNUNET_TIME_Relative delay;
3852 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3854 GNUNET_SCHEDULER_cancel(fal->revalidate_task);
3855 fal->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3857 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3858 delay.rel_value /= 2; /* do before expiration */
3859 delay = GNUNET_TIME_relative_min (delay,
3860 LATENCY_EVALUATION_MAX_DELAY);
3861 if (GNUNET_YES != fal->estimated)
3863 delay = GNUNET_TIME_UNIT_ZERO;
3864 fal->estimated = GNUNET_YES;
3867 if (GNUNET_YES == fal->connected)
3869 delay = GNUNET_TIME_relative_min (delay,
3870 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3872 /* FIXME: also adjust delay based on how close the last
3873 observed latency is to the latency of the best alternative */
3874 /* bound how fast we can go */
3875 delay = GNUNET_TIME_relative_max (delay,
3876 GNUNET_TIME_UNIT_SECONDS);
3877 /* randomize a bit (to avoid doing all at the same time) */
3878 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3879 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3880 &send_periodic_ping,
3888 * Function that will be called if we receive some payload
3889 * from another peer.
3891 * @param message the payload
3892 * @param n peer who claimed to be the sender
3895 handle_payload_message (const struct GNUNET_MessageHeader *message,
3896 struct NeighbourList *n)
3898 struct InboundMessage *im;
3899 struct TransportClient *cpos;
3902 msize = ntohs (message->size);
3903 if (n->received_pong == GNUNET_NO)
3906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3907 "Received message of type %u and size %u from `%4s', but no pong yet!\n",
3908 ntohs (message->type),
3909 ntohs (message->size),
3910 GNUNET_i2s (&n->id));
3912 GNUNET_free_non_null (n->pre_connect_message_buffer);
3913 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3914 memcpy (n->pre_connect_message_buffer, message, msize);
3919 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3921 ntohs (message->type),
3922 ntohs (message->size),
3923 GNUNET_i2s (&n->id));
3925 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3928 n->quota_violation_count++;
3930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3931 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3932 n->in_tracker.available_bytes_per_s__,
3933 n->quota_violation_count);
3935 /* Discount 32k per violation */
3936 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3941 if (n->quota_violation_count > 0)
3943 /* try to add 32k back */
3944 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3946 n->quota_violation_count--;
3949 GNUNET_STATISTICS_update (stats,
3950 gettext_noop ("# payload received from other peers"),
3953 /* transmit message to all clients */
3954 uint32_t ats_count = 2;
3955 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
3956 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3959 im = GNUNET_malloc (size);
3960 im->header.size = htons (size);
3961 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3963 im->ats_count = htonl(ats_count);
3964 /* Setting ATS data */
3965 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
3966 (&(im->ats))[0].value = htonl (n->distance);
3967 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
3968 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
3969 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3970 (&(im->ats))[ats_count].value = htonl (0);
3972 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
3974 while (cpos != NULL)
3976 transmit_to_client (cpos, &im->header, GNUNET_YES);
3984 * Iterator over hash map entries. Checks if the given validation
3985 * entry is for the same challenge as what is given in the PONG.
3987 * @param cls the 'struct TransportPongMessage*'
3988 * @param key peer identity
3989 * @param value value in the hash map ('struct ValidationEntry')
3990 * @return GNUNET_YES if we should continue to
3991 * iterate (mismatch), GNUNET_NO if not (entry matched)
3994 check_pending_validation (void *cls,
3995 const GNUNET_HashCode * key,
3998 const struct TransportPongMessage *pong = cls;
3999 struct ValidationEntry *ve = value;
4000 struct AddValidatedAddressContext avac;
4001 unsigned int challenge = ntohl(pong->challenge);
4002 struct GNUNET_HELLO_Message *hello;
4003 struct GNUNET_PeerIdentity target;
4004 struct NeighbourList *n;
4005 struct ForeignAddressList *fal;
4006 struct OwnAddressList *oal;
4007 struct TransportPlugin *tp;
4008 struct GNUNET_MessageHeader *prem;
4014 ps = ntohs (pong->header.size);
4015 if (ps < sizeof (struct TransportPongMessage))
4017 GNUNET_break_op (0);
4020 addr = (const char*) &pong[1];
4021 slen = strlen (ve->transport_name) + 1;
4022 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
4023 (ve->challenge != challenge) ||
4024 (addr[slen-1] != '\0') ||
4025 (0 != strcmp (addr, ve->transport_name)) ||
4026 (ntohl (pong->purpose.size)
4027 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4029 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4030 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
4035 alen = ps - sizeof (struct TransportPongMessage) - slen;
4036 switch (ntohl (pong->purpose.purpose))
4038 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
4039 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
4040 (0 != memcmp (&addr[slen],
4044 return GNUNET_YES; /* different entry, keep trying! */
4046 if (0 != memcmp (&pong->pid,
4048 sizeof (struct GNUNET_PeerIdentity)))
4050 GNUNET_break_op (0);
4054 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
4059 GNUNET_break_op (0);
4064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4065 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
4067 a2s (ve->transport_name,
4068 (const struct sockaddr *) ve->addr,
4070 ve->transport_name);
4073 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
4074 if (0 != memcmp (&pong->pid,
4076 sizeof (struct GNUNET_PeerIdentity)))
4080 GNUNET_asprintf(&peer, "%s",GNUNET_i2s (&pong->pid));
4082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4083 "Received PONG for different identity: I am `%s', PONG identity: `%s'\n",
4084 GNUNET_i2s (&my_identity),
4090 if (ve->addrlen != 0)
4092 /* must have been for a different validation entry */
4095 tp = find_transport (ve->transport_name);
4101 oal = tp->addresses;
4104 if ( (oal->addrlen == alen) &&
4105 (0 == memcmp (&oal[1],
4113 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4114 _("Not accepting PONG from `%s' with address `%s' since I cannot confirm using this address.\n"),
4115 GNUNET_i2s (&pong->pid),
4116 a2s (ve->transport_name,
4119 /* FIXME: since the sender of the PONG currently uses the
4120 wrong address (see FIMXE there!), we cannot run a
4121 proper check here... */
4127 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
4132 GNUNET_break_op (0);
4137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4138 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
4140 a2s (ve->transport_name,
4143 ve->transport_name);
4147 GNUNET_break_op (0);
4150 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
4152 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4153 _("Received expired signature. Check system time.\n"));
4156 GNUNET_STATISTICS_update (stats,
4157 gettext_noop ("# address validation successes"),
4160 /* create the updated HELLO */
4161 GNUNET_CRYPTO_hash (&ve->publicKey,
4162 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4163 &target.hashPubKey);
4164 if (ve->addr != NULL)
4166 avac.done = GNUNET_NO;
4168 hello = GNUNET_HELLO_create (&ve->publicKey,
4169 &add_validated_address,
4171 GNUNET_PEERINFO_add_peer (peerinfo,
4173 GNUNET_free (hello);
4175 n = find_neighbour (&target);
4178 n->publicKey = ve->publicKey;
4179 n->public_key_valid = GNUNET_YES;
4180 fal = add_peer_address (n,
4185 GNUNET_assert (fal != NULL);
4186 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
4187 fal->validated = GNUNET_YES;
4188 mark_address_connected (fal);
4189 GNUNET_STATISTICS_update (stats,
4190 gettext_noop ("# peer addresses considered valid"),
4193 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
4194 update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4196 schedule_next_ping (fal);
4197 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
4198 n->latency = fal->latency;
4200 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
4202 n->distance = fal->distance;
4203 if (GNUNET_NO == n->received_pong)
4205 n->received_pong = GNUNET_YES;
4206 notify_clients_connect (&target, n->latency, n->distance);
4207 if (NULL != (prem = n->pre_connect_message_buffer))
4209 n->pre_connect_message_buffer = NULL;
4210 handle_payload_message (prem, n);
4214 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4216 GNUNET_SCHEDULER_cancel (n->retry_task);
4217 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4218 try_transmission_to_peer (n);
4222 /* clean up validation entry */
4223 GNUNET_assert (GNUNET_YES ==
4224 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4227 abort_validation (NULL, NULL, ve);
4233 * Function that will be called if we receive a validation
4234 * of an address challenge that we transmitted to another
4235 * peer. Note that the validation should only be considered
4236 * acceptable if the challenge matches AND if the sender
4237 * address is at least a plausible address for this peer
4238 * (otherwise we may be seeing a MiM attack).
4240 * @param cls closure
4241 * @param message the pong message
4242 * @param peer who responded to our challenge
4243 * @param sender_address string describing our sender address (as observed
4244 * by the other peer in binary format)
4245 * @param sender_address_len number of bytes in 'sender_address'
4248 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
4249 const struct GNUNET_PeerIdentity *peer,
4250 const char *sender_address,
4251 size_t sender_address_len)
4253 if (0 == memcmp (peer,
4255 sizeof (struct GNUNET_PeerIdentity)))
4257 /* PONG send to self, ignore */
4258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4259 "Receiving `%s' message from myself\n",
4263 #if DEBUG_TRANSPORT > 1
4264 /* we get tons of these that just get discarded, only log
4265 if we are quite verbose */
4266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4267 "Receiving `%s' message from `%4s'.\n", "PONG",
4270 GNUNET_STATISTICS_update (stats,
4271 gettext_noop ("# PONG messages received"),
4274 if (GNUNET_SYSERR !=
4275 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
4277 &check_pending_validation,
4280 /* This is *expected* to happen a lot since we send
4281 PONGs to *all* known addresses of the sender of
4282 the PING, so most likely we get multiple PONGs
4283 per PING, and all but the first PONG will end up
4284 here. So really we should not print anything here
4285 unless we want to be very, very verbose... */
4286 #if DEBUG_TRANSPORT > 2
4287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4288 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
4300 * Try to validate a neighbour's address by sending him our HELLO and a PING.
4302 * @param cls the 'struct ValidationEntry*'
4303 * @param neighbour neighbour to validate, NULL if validation failed
4306 transmit_hello_and_ping (void *cls,
4307 struct NeighbourList *neighbour)
4309 struct ValidationEntry *va = cls;
4310 struct ForeignAddressList *peer_address;
4311 struct TransportPingMessage ping;
4312 uint16_t hello_size;
4315 struct GNUNET_PeerIdentity id;
4318 GNUNET_CRYPTO_hash (&va->publicKey,
4319 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4321 if (neighbour == NULL)
4323 /* FIXME: stats... */
4324 GNUNET_break (GNUNET_OK ==
4325 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4328 abort_validation (NULL, NULL, va);
4331 neighbour->publicKey = va->publicKey;
4332 neighbour->public_key_valid = GNUNET_YES;
4333 peer_address = add_peer_address (neighbour,
4334 va->transport_name, NULL,
4335 (const void*) &va[1],
4337 if (peer_address == NULL)
4339 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4340 "Failed to add peer `%4s' for plugin `%s'\n",
4341 GNUNET_i2s (&neighbour->id),
4342 va->transport_name);
4343 GNUNET_break (GNUNET_OK ==
4344 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4347 abort_validation (NULL, NULL, va);
4350 if (NULL == our_hello)
4351 refresh_hello_task (NULL, NULL);
4352 hello_size = GNUNET_HELLO_size(our_hello);
4353 slen = strlen(va->transport_name) + 1;
4354 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
4355 message_buf = GNUNET_malloc(tsize);
4356 ping.challenge = htonl(va->challenge);
4357 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
4358 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4359 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4360 memcpy(message_buf, our_hello, hello_size);
4361 memcpy(&message_buf[hello_size],
4363 sizeof(struct TransportPingMessage));
4364 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4367 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4372 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
4375 : a2s (va->transport_name,
4376 (const void*) &va[1], va->addrlen),
4378 GNUNET_i2s (&neighbour->id),
4379 "HELLO", hello_size,
4380 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
4383 GNUNET_STATISTICS_update (stats,
4384 gettext_noop ("# PING messages sent for initial validation"),
4387 transmit_to_peer (NULL, peer_address,
4388 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4389 HELLO_VERIFICATION_TIMEOUT,
4391 GNUNET_YES, neighbour);
4392 GNUNET_free(message_buf);
4397 * Check if the given address is already being validated; if not,
4398 * append the given address to the list of entries that are being be
4399 * validated and initiate validation.
4401 * @param cls closure ('struct CheckHelloValidatedContext *')
4402 * @param tname name of the transport
4403 * @param expiration expiration time
4404 * @param addr the address
4405 * @param addrlen length of the address
4406 * @return GNUNET_OK (always)
4409 run_validation (void *cls,
4411 struct GNUNET_TIME_Absolute expiration,
4415 struct CheckHelloValidatedContext *chvc = cls;
4416 struct GNUNET_PeerIdentity id;
4417 struct TransportPlugin *tp;
4418 struct ValidationEntry *va;
4419 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4420 struct CheckAddressExistsClosure caec;
4421 struct OwnAddressList *oal;
4423 GNUNET_assert (addr != NULL);
4425 GNUNET_STATISTICS_update (stats,
4426 gettext_noop ("# peer addresses scheduled for validation"),
4429 tp = find_transport (tname);
4432 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
4433 GNUNET_ERROR_TYPE_BULK,
4435 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4437 GNUNET_STATISTICS_update (stats,
4438 gettext_noop ("# peer addresses not validated (plugin not available)"),
4443 /* check if this is one of our own addresses */
4444 oal = tp->addresses;
4447 if ( (oal->addrlen == addrlen) &&
4448 (0 == memcmp (&oal[1],
4452 /* not plausible, this address is equivalent to our own address! */
4453 GNUNET_STATISTICS_update (stats,
4454 gettext_noop ("# peer addresses not validated (loopback)"),
4461 GNUNET_HELLO_get_key (chvc->hello, &pk);
4462 GNUNET_CRYPTO_hash (&pk,
4464 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4467 if (is_blacklisted(&id, tp))
4470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4471 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4479 caec.addrlen = addrlen;
4480 caec.session = NULL;
4482 caec.exists = GNUNET_NO;
4483 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4484 &check_address_exists,
4486 if (caec.exists == GNUNET_YES)
4488 /* During validation attempts we will likely trigger the other
4489 peer trying to validate our address which in turn will cause
4490 it to send us its HELLO, so we expect to hit this case rather
4491 frequently. Only print something if we are very verbose. */
4492 #if DEBUG_TRANSPORT > 1
4493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4494 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4495 a2s (tname, addr, addrlen),
4499 GNUNET_STATISTICS_update (stats,
4500 gettext_noop ("# peer addresses not validated (in progress)"),
4505 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4508 va->transport_name = GNUNET_strdup (tname);
4509 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4511 va->send_time = GNUNET_TIME_absolute_get();
4512 va->addr = (const void*) &va[1];
4513 memcpy (&va[1], addr, addrlen);
4514 va->addrlen = addrlen;
4515 GNUNET_HELLO_get_key (chvc->hello,
4517 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4518 &timeout_hello_validation,
4520 GNUNET_CONTAINER_multihashmap_put (validation_map,
4523 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4524 setup_peer_check_blacklist (&id, GNUNET_NO,
4525 &transmit_hello_and_ping,
4532 * Check if addresses in validated hello "h" overlap with
4533 * those in "chvc->hello" and validate the rest.
4535 * @param cls closure
4536 * @param peer id of the peer, NULL for last call
4537 * @param h hello message for the peer (can be NULL)
4538 * @param err_msg NULL if successful, otherwise contains error message
4541 check_hello_validated (void *cls,
4542 const struct GNUNET_PeerIdentity *peer,
4543 const struct GNUNET_HELLO_Message *h,
4544 const char *err_msg)
4546 struct CheckHelloValidatedContext *chvc = cls;
4547 struct GNUNET_HELLO_Message *plain_hello;
4548 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4549 struct GNUNET_PeerIdentity target;
4550 struct NeighbourList *n;
4552 if (err_msg != NULL)
4555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4556 _("Error in communication with PEERINFO service: %s\n"),
4564 GNUNET_STATISTICS_update (stats,
4565 gettext_noop ("# outstanding peerinfo iterate requests"),
4569 if (GNUNET_NO == chvc->hello_known)
4571 /* notify PEERINFO about the peer now, so that we at least
4572 have the public key if some other component needs it */
4573 GNUNET_HELLO_get_key (chvc->hello, &pk);
4574 GNUNET_CRYPTO_hash (&pk,
4575 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4576 &target.hashPubKey);
4577 plain_hello = GNUNET_HELLO_create (&pk,
4580 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4581 GNUNET_free (plain_hello);
4582 #if DEBUG_TRANSPORT_HELLO
4583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4584 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4586 GNUNET_i2s (&target));
4588 GNUNET_STATISTICS_update (stats,
4589 gettext_noop ("# new HELLOs requiring full validation"),
4592 GNUNET_HELLO_iterate_addresses (chvc->hello,
4599 GNUNET_STATISTICS_update (stats,
4600 gettext_noop ("# duplicate HELLO (peer known)"),
4605 if (chvc->ve_count == 0)
4607 GNUNET_CONTAINER_DLL_remove (chvc_head,
4616 #if DEBUG_TRANSPORT_HELLO
4617 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4618 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4622 chvc->hello_known = GNUNET_YES;
4623 n = find_neighbour (peer);
4626 #if DEBUG_TRANSPORT_HELLO
4627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4628 "Calling hello_iterate_addresses for %s!\n",
4631 GNUNET_HELLO_iterate_addresses (h,
4633 &add_to_foreign_address_list,
4635 try_transmission_to_peer (n);
4639 #if DEBUG_TRANSPORT_HELLO
4640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4641 "No existing neighbor record for %s!\n",
4644 GNUNET_STATISTICS_update (stats,
4645 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4649 GNUNET_STATISTICS_update (stats,
4650 gettext_noop ("# HELLO validations (update case)"),
4653 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4655 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4662 * Process HELLO-message.
4664 * @param plugin transport involved, may be NULL
4665 * @param message the actual message
4666 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4669 process_hello (struct TransportPlugin *plugin,
4670 const struct GNUNET_MessageHeader *message)
4673 struct GNUNET_PeerIdentity target;
4674 const struct GNUNET_HELLO_Message *hello;
4675 struct CheckHelloValidatedContext *chvc;
4676 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4677 struct NeighbourList *n;
4678 #if DEBUG_TRANSPORT_HELLO > 2
4682 hsize = ntohs (message->size);
4683 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4684 (hsize < sizeof (struct GNUNET_MessageHeader)))
4687 return GNUNET_SYSERR;
4689 GNUNET_STATISTICS_update (stats,
4690 gettext_noop ("# HELLOs received for validation"),
4694 hello = (const struct GNUNET_HELLO_Message *) message;
4695 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4697 #if DEBUG_TRANSPORT_HELLO
4698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4699 "Unable to get public key from `%s' for `%4s'!\n",
4701 GNUNET_i2s (&target));
4703 GNUNET_break_op (0);
4704 return GNUNET_SYSERR;
4706 GNUNET_CRYPTO_hash (&publicKey,
4707 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4708 &target.hashPubKey);
4710 #if DEBUG_TRANSPORT_HELLO
4711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4712 "Received `%s' message for `%4s'\n",
4714 GNUNET_i2s (&target));
4716 if (0 == memcmp (&my_identity,
4718 sizeof (struct GNUNET_PeerIdentity)))
4720 GNUNET_STATISTICS_update (stats,
4721 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4726 n = find_neighbour (&target);
4728 (! n->public_key_valid) )
4730 GNUNET_HELLO_get_key (hello, &n->publicKey);
4731 n->public_key_valid = GNUNET_YES;
4734 /* check if load is too high before doing expensive stuff */
4735 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4737 GNUNET_STATISTICS_update (stats,
4738 gettext_noop ("# HELLOs ignored due to high load"),
4741 #if DEBUG_TRANSPORT_HELLO
4742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4743 "Ignoring `%s' for `%4s', load too high.\n",
4745 GNUNET_i2s (&target));
4752 while (NULL != chvc)
4754 if (GNUNET_HELLO_equals (hello,
4756 GNUNET_TIME_absolute_get ()).abs_value > 0)
4758 #if DEBUG_TRANSPORT_HELLO > 2
4759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4760 "Received duplicate `%s' message for `%4s'; ignored\n",
4762 GNUNET_i2s (&target));
4764 return GNUNET_OK; /* validation already pending */
4766 if (GNUNET_HELLO_size (hello) == GNUNET_HELLO_size (chvc->hello))
4767 GNUNET_break (0 != memcmp (hello, chvc->hello,
4768 GNUNET_HELLO_size(hello)));
4773 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4774 if ((NULL != temp_neighbor))
4776 fprintf(stderr, "Already know peer, ignoring hello\n");
4781 #if DEBUG_TRANSPORT_HELLO > 2
4784 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4787 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4790 GNUNET_i2s (&target),
4792 GNUNET_HELLO_size(hello));
4797 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4799 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4800 memcpy (&chvc[1], hello, hsize);
4801 GNUNET_CONTAINER_DLL_insert (chvc_head,
4804 /* finally, check if HELLO was previously validated
4805 (continuation will then schedule actual validation) */
4806 GNUNET_STATISTICS_update (stats,
4807 gettext_noop ("# peerinfo process hello iterate requests"),
4810 GNUNET_STATISTICS_update (stats,
4811 gettext_noop ("# outstanding peerinfo iterate requests"),
4814 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4816 HELLO_VERIFICATION_TIMEOUT,
4817 &check_hello_validated, chvc);
4823 * The peer specified by the given neighbour has timed-out or a plugin
4824 * has disconnected. We may either need to do nothing (other plugins
4825 * still up), or trigger a full disconnect and clean up. This
4826 * function updates our state and does the necessary notifications.
4827 * Also notifies our clients that the neighbour is now officially
4830 * @param n the neighbour list entry for the peer
4831 * @param check GNUNET_YES to check if ALL addresses for this peer
4832 * are gone, GNUNET_NO to force a disconnect of the peer
4833 * regardless of whether other addresses exist.
4836 disconnect_neighbour (struct NeighbourList *n, int check)
4838 struct ReadyList *rpos;
4839 struct NeighbourList *npos;
4840 struct NeighbourList *nprev;
4841 struct MessageQueue *mq;
4842 struct ForeignAddressList *peer_addresses;
4843 struct ForeignAddressList *peer_pos;
4845 if (GNUNET_YES == check)
4848 while (NULL != rpos)
4850 peer_addresses = rpos->addresses;
4851 while (peer_addresses != NULL)
4853 // Do not disconnect if: an address is connected or an inbound address exists
4854 if ((GNUNET_YES == peer_addresses->connected) || (peer_addresses->addrlen == 0))
4857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4858 "NOT Disconnecting from `%4s', still have live address `%s'!\n",
4859 GNUNET_i2s (&n->id),
4860 a2s (peer_addresses->ready_list->plugin->short_name,
4861 peer_addresses->addr,
4862 peer_addresses->addrlen));
4864 return; /* still connected */
4866 peer_addresses = peer_addresses->next;
4872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4873 "Disconnecting from `%4s'\n",
4874 GNUNET_i2s (&n->id));
4877 /* remove n from neighbours list */
4880 while ((npos != NULL) && (npos != n))
4885 GNUNET_assert (npos != NULL);
4887 neighbours = n->next;
4889 nprev->next = n->next;
4891 /* notify all clients about disconnect */
4892 if (GNUNET_YES == n->received_pong)
4893 notify_clients_disconnect (&n->id);
4895 ats_modify_problem_state(ats, ATS_MODIFIED);
4897 /* clean up all plugins, cancel connections and pending transmissions */
4898 while (NULL != (rpos = n->plugins))
4900 n->plugins = rpos->next;
4901 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4902 while (rpos->addresses != NULL)
4904 peer_pos = rpos->addresses;
4905 rpos->addresses = peer_pos->next;
4906 if (peer_pos->connected == GNUNET_YES)
4907 GNUNET_STATISTICS_update (stats,
4908 gettext_noop ("# connected addresses"),
4911 if (GNUNET_YES == peer_pos->validated)
4912 GNUNET_STATISTICS_update (stats,
4913 gettext_noop ("# peer addresses considered valid"),
4916 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4918 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4919 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4921 GNUNET_free(peer_pos->ressources);
4922 peer_pos->ressources = NULL;
4923 GNUNET_free(peer_pos->quality);
4924 peer_pos->ressources = NULL;
4925 GNUNET_free(peer_pos);
4930 /* free all messages on the queue */
4931 while (NULL != (mq = n->messages_head))
4933 GNUNET_STATISTICS_update (stats,
4934 gettext_noop ("# bytes in message queue for other peers"),
4935 - (int64_t) mq->message_buf_size,
4937 GNUNET_STATISTICS_update (stats,
4938 gettext_noop ("# bytes discarded due to disconnect"),
4939 mq->message_buf_size,
4941 GNUNET_CONTAINER_DLL_remove (n->messages_head,
4944 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4946 sizeof(struct GNUNET_PeerIdentity)));
4950 while (NULL != (mq = n->cont_head))
4953 GNUNET_CONTAINER_DLL_remove (n->cont_head,
4956 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4958 sizeof(struct GNUNET_PeerIdentity)));
4962 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4964 GNUNET_SCHEDULER_cancel (n->timeout_task);
4965 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4967 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4969 GNUNET_SCHEDULER_cancel (n->retry_task);
4970 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4972 if (n->piter != NULL)
4974 GNUNET_PEERINFO_iterate_cancel (n->piter);
4975 GNUNET_STATISTICS_update (stats,
4976 gettext_noop ("# outstanding peerinfo iterate requests"),
4981 /* finally, free n itself */
4982 GNUNET_STATISTICS_update (stats,
4983 gettext_noop ("# active neighbours"),
4986 GNUNET_free_non_null (n->pre_connect_message_buffer);
4992 * We have received a PING message from someone. Need to send a PONG message
4993 * in response to the peer by any means necessary.
4996 handle_ping (void *cls, const struct GNUNET_MessageHeader *message,
4997 const struct GNUNET_PeerIdentity *peer,
4998 struct Session *session,
4999 const char *sender_address,
5000 uint16_t sender_address_len)
5002 struct TransportPlugin *plugin = cls;
5003 struct SessionHeader *session_header = (struct SessionHeader*) session;
5004 struct TransportPingMessage *ping;
5005 struct TransportPongMessage *pong;
5006 struct NeighbourList *n;
5007 struct ReadyList *rl;
5008 struct ForeignAddressList *fal;
5009 struct OwnAddressList *oal;
5015 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
5017 GNUNET_break_op (0);
5018 return GNUNET_SYSERR;
5021 ping = (struct TransportPingMessage *) message;
5022 if (0 != memcmp (&ping->target,
5023 plugin->env.my_identity,
5024 sizeof (struct GNUNET_PeerIdentity)))
5027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5028 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
5030 (sender_address != NULL)
5031 ? a2s (plugin->short_name,
5032 (const struct sockaddr *)sender_address,
5035 GNUNET_i2s (&ping->target));
5037 return GNUNET_SYSERR;
5040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5041 "Processing `%s' from `%s'\n",
5043 (sender_address != NULL)
5044 ? a2s (plugin->short_name,
5045 (const struct sockaddr *)sender_address,
5049 GNUNET_STATISTICS_update (stats,
5050 gettext_noop ("# PING messages received"),
5053 addr = (const char*) &ping[1];
5054 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
5055 slen = strlen (plugin->short_name) + 1;
5058 /* peer wants to confirm that we have an outbound connection to him */
5059 if (session == NULL)
5061 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5062 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
5064 return GNUNET_SYSERR;
5066 /* FIXME-urg: the use of 'sender_address' in the code below is doubly-wrong:
5067 1) it is NULL when we need to have a real value
5068 2) it is documented to be the address of the sender (source-IP), where
5069 what we actually want is our LISTEN IP (what we 'bound' to); which we don't even
5072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5073 "Creating PONG indicating that we received a connection at our address `%s' from `%s'.\n",
5074 a2s (plugin->short_name,
5076 sender_address_len),
5079 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5080 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5081 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5082 pong->purpose.size =
5083 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5085 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5086 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
5087 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
5088 pong->challenge = ping->challenge;
5089 pong->addrlen = htonl(sender_address_len + slen);
5092 sizeof(struct GNUNET_PeerIdentity));
5096 if ((sender_address!=NULL) && (sender_address_len > 0))
5097 memcpy (&((char*)&pong[1])[slen],
5099 sender_address_len);
5100 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
5102 /* create / update cached sig */
5104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5105 "Creating PONG signature to indicate active connection.\n");
5107 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5108 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5109 GNUNET_assert (GNUNET_OK ==
5110 GNUNET_CRYPTO_rsa_sign (my_private_key,
5112 &session_header->pong_signature));
5116 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5118 memcpy (&pong->signature,
5119 &session_header->pong_signature,
5120 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5126 /* peer wants to confirm that this is one of our addresses */
5130 plugin->api->check_address (plugin->api->cls,
5134 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5135 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
5136 a2s (plugin->short_name,
5141 oal = plugin->addresses;
5144 if ( (oal->addrlen == alen) &&
5151 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
5152 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
5153 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5154 pong->purpose.size =
5155 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5157 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5158 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
5159 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
5160 pong->challenge = ping->challenge;
5161 pong->addrlen = htonl(alen + slen);
5164 sizeof(struct GNUNET_PeerIdentity));
5165 memcpy (&pong[1], plugin->short_name, slen);
5166 memcpy (&((char*)&pong[1])[slen], addr, alen);
5167 if ( (oal != NULL) &&
5168 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
5170 /* create / update cached sig */
5172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5173 "Creating PONG signature to indicate ownership.\n");
5175 oal->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5176 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5177 GNUNET_assert (GNUNET_OK ==
5178 GNUNET_CRYPTO_rsa_sign (my_private_key,
5180 &oal->pong_signature));
5181 memcpy (&pong->signature,
5182 &oal->pong_signature,
5183 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5185 else if (oal == NULL)
5187 /* not using cache (typically DV-only) */
5188 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
5189 GNUNET_assert (GNUNET_OK ==
5190 GNUNET_CRYPTO_rsa_sign (my_private_key,
5196 /* can used cached version */
5197 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5198 memcpy (&pong->signature,
5199 &oal->pong_signature,
5200 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5203 n = find_neighbour(peer);
5204 GNUNET_assert (n != NULL);
5205 did_pong = GNUNET_NO;
5206 /* first try reliable response transmission */
5210 fal = rl->addresses;
5213 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
5216 ntohs (pong->header.size),
5217 TRANSPORT_PONG_PRIORITY,
5218 HELLO_VERIFICATION_TIMEOUT,
5225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5226 "Transmitted PONG to `%s' via reliable mechanism\n",
5229 GNUNET_STATISTICS_update (stats,
5230 gettext_noop ("# PONGs unicast via reliable transport"),
5236 did_pong = GNUNET_YES;
5241 /* no reliable method found, do multicast */
5242 GNUNET_STATISTICS_update (stats,
5243 gettext_noop ("# PONGs multicast to all available addresses"),
5249 fal = rl->addresses;
5252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5253 "Transmitting PONG to `%s' via unreliable mechanism `%s':%s\n",
5255 a2s (rl->plugin->short_name,
5258 rl->plugin->short_name);
5259 transmit_to_peer(NULL, fal,
5260 TRANSPORT_PONG_PRIORITY,
5261 HELLO_VERIFICATION_TIMEOUT,
5263 ntohs(pong->header.size),
5266 did_pong = GNUNET_YES;
5272 if (GNUNET_YES != did_pong)
5273 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5274 _("Could not send PONG to `%s': no address available\n"),
5281 * Function called by the plugin for each received message. Update
5282 * data volumes, possibly notify plugins about reducing the rate at
5283 * which they read from the socket and generally forward to our
5286 * @param cls the "struct TransportPlugin *" we gave to the plugin
5287 * @param peer (claimed) identity of the other peer
5288 * @param message the message, NULL if we only care about
5289 * learning about the delay until we should receive again
5290 * @param ats_data information for automatic transport selection
5291 * @param ats_count number of elements in ats not including 0-terminator
5292 * @param session identifier used for this session (can be NULL)
5293 * @param sender_address binary address of the sender (if observed)
5294 * @param sender_address_len number of bytes in sender_address
5295 * @return how long in ms the plugin should wait until receiving more data
5296 * (plugins that do not support this, can ignore the return value)
5298 static struct GNUNET_TIME_Relative
5299 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
5300 const struct GNUNET_MessageHeader *message,
5301 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
5303 struct Session *session,
5304 const char *sender_address,
5305 uint16_t sender_address_len)
5307 struct TransportPlugin *plugin = cls;
5308 struct ReadyList *service_context;
5309 struct ForeignAddressList *peer_address;
5311 struct NeighbourList *n;
5312 struct GNUNET_TIME_Relative ret;
5316 if (0 == memcmp (peer,
5318 sizeof (struct GNUNET_PeerIdentity)))
5320 /* refuse to receive from myself */
5322 return GNUNET_TIME_UNIT_FOREVER_REL;
5324 if (is_blacklisted (peer, plugin))
5325 return GNUNET_TIME_UNIT_FOREVER_REL;
5326 n = find_neighbour (peer);
5328 n = setup_new_neighbour (peer, GNUNET_YES);
5329 service_context = n->plugins;
5330 while ((service_context != NULL) && (plugin != service_context->plugin))
5331 service_context = service_context->next;
5332 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
5333 peer_address = NULL;
5336 for (c=0; c<ats_count; c++)
5337 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
5338 distance = ntohl(ats_data[c].value);
5341 if (message != NULL)
5343 if ( (session != NULL) ||
5344 (sender_address != NULL) )
5345 peer_address = add_peer_address (n,
5349 sender_address_len);
5350 if (peer_address != NULL)
5352 update_addr_ats(peer_address, ats_data, ats_count);
5353 update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5355 peer_address->distance = distance;
5356 if (GNUNET_YES == peer_address->validated)
5357 mark_address_connected (peer_address);
5358 peer_address->timeout
5359 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5360 schedule_next_ping (peer_address);
5362 /* update traffic received amount ... */
5363 msize = ntohs (message->size);
5365 GNUNET_STATISTICS_update (stats,
5366 gettext_noop ("# bytes received from other peers"),
5369 n->distance = distance;
5371 GNUNET_TIME_relative_to_absolute
5372 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5373 GNUNET_SCHEDULER_cancel (n->timeout_task);
5375 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
5376 &neighbour_timeout_task, n);
5377 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
5379 /* dropping message due to frequent inbound volume violations! */
5380 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
5381 GNUNET_ERROR_TYPE_BULK,
5383 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
5384 n->in_tracker.available_bytes_per_s__,
5385 n->quota_violation_count);
5386 GNUNET_STATISTICS_update (stats,
5387 gettext_noop ("# bandwidth quota violations by other peers"),
5390 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
5392 if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
5393 (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
5395 uint32_t value = ntohl(*((uint32_t *) &message[1]));
5396 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
5397 /* Force ressource and quality update */
5398 if ((value == 4) && (ats != NULL))
5399 ats_modify_problem_state(ats, ATS_QUALITY_COST_UPDATED);
5400 /* Force cost update */
5401 if ((value == 3) && (ats != NULL))
5402 ats_modify_problem_state(ats, ATS_COST_UPDATED);
5403 /* Force quality update */
5404 if ((value == 2) && (ats != NULL))
5405 ats_modify_problem_state(ats, ATS_QUALITY_UPDATED);
5406 /* Force full rebuild */
5407 if ((value == 1) && (ats != NULL))
5408 ats_modify_problem_state(ats, ATS_MODIFIED);
5412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5413 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
5414 ntohs (message->type),
5415 ntohs (message->size),
5418 switch (ntohs (message->type))
5420 case GNUNET_MESSAGE_TYPE_HELLO:
5421 GNUNET_STATISTICS_update (stats,
5422 gettext_noop ("# HELLO messages received from other peers"),
5425 process_hello (plugin, message);
5427 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
5428 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
5429 if (! n->received_pong)
5430 transmit_plain_ping (n);
5432 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
5433 handle_pong (plugin, message, peer, sender_address, sender_address_len);
5435 case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
5438 handle_payload_message (message, n);
5442 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
5443 if (ret.rel_value > 0)
5446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5447 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
5448 (unsigned long long) n->in_tracker.consumption_since_last_update__,
5449 (unsigned int) n->in_tracker.available_bytes_per_s__,
5450 (unsigned long long) ret.rel_value);
5452 GNUNET_STATISTICS_update (stats,
5453 gettext_noop ("# ms throttling suggested"),
5454 (int64_t) ret.rel_value,
5461 * Handle START-message. This is the first message sent to us
5462 * by any client which causes us to add it to our list.
5464 * @param cls closure (always NULL)
5465 * @param client identification of the client
5466 * @param message the actual message
5469 handle_start (void *cls,
5470 struct GNUNET_SERVER_Client *client,
5471 const struct GNUNET_MessageHeader *message)
5473 const struct StartMessage *start;
5474 struct TransportClient *c;
5475 struct ConnectInfoMessage * cim;
5476 struct NeighbourList *n;
5480 start = (const struct StartMessage*) message;
5482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5483 "Received `%s' request from client\n", "START");
5488 if (c->client == client)
5490 /* client already on our list! */
5492 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5497 if ( (GNUNET_NO != ntohl (start->do_check)) &&
5498 (0 != memcmp (&start->self,
5500 sizeof (struct GNUNET_PeerIdentity))) )
5502 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5503 _("Rejecting control connection from peer `%s', which is not me!\n"),
5504 GNUNET_i2s (&start->self));
5505 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5508 c = GNUNET_malloc (sizeof (struct TransportClient));
5512 if (our_hello != NULL)
5515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5516 "Sending our own `%s' to new client\n", "HELLO");
5518 transmit_to_client (c,
5519 (const struct GNUNET_MessageHeader *) our_hello,
5521 /* tell new client about all existing connections */
5523 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
5524 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
5528 cim = GNUNET_malloc (size);
5529 cim->header.size = htons (size);
5530 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
5531 cim->ats_count = htonl(ats_count);
5532 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
5533 (&(cim->ats))[2].value = htonl (0);
5537 if (GNUNET_YES == n->received_pong)
5539 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5540 (&(cim->ats))[0].value = htonl (n->distance);
5541 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5542 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
5544 transmit_to_client (c, &cim->header, GNUNET_NO);
5552 #if DEBUG_TRANSPORT_HELLO
5553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5554 "No HELLO created yet, will transmit HELLO to client later!\n");
5558 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5563 * Handle HELLO-message.
5565 * @param cls closure (always NULL)
5566 * @param client identification of the client
5567 * @param message the actual message
5570 handle_hello (void *cls,
5571 struct GNUNET_SERVER_Client *client,
5572 const struct GNUNET_MessageHeader *message)
5576 GNUNET_STATISTICS_update (stats,
5577 gettext_noop ("# HELLOs received from clients"),
5580 ret = process_hello (NULL, message);
5581 GNUNET_SERVER_receive_done (client, ret);
5586 * Closure for 'transmit_client_message'; followed by
5587 * 'msize' bytes of the actual message.
5589 struct TransmitClientMessageContext
5592 * Client on whom's behalf we are sending.
5594 struct GNUNET_SERVER_Client *client;
5597 * Timeout for the transmission.
5599 struct GNUNET_TIME_Absolute timeout;
5607 * Size of the message in bytes.
5614 * Schedule transmission of a message we got from a client to a peer.
5616 * @param cls the 'struct TransmitClientMessageContext*'
5617 * @param n destination, or NULL on error (in that case, drop the message)
5620 transmit_client_message (void *cls,
5621 struct NeighbourList *n)
5623 struct TransmitClientMessageContext *tcmc = cls;
5624 struct TransportClient *tc;
5627 while ((tc != NULL) && (tc->client != tcmc->client))
5632 transmit_to_peer (tc, NULL, tcmc->priority,
5633 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5635 tcmc->msize, GNUNET_NO, n);
5637 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5638 GNUNET_SERVER_client_drop (tcmc->client);
5644 * Handle SEND-message.
5646 * @param cls closure (always NULL)
5647 * @param client identification of the client
5648 * @param message the actual message
5651 handle_send (void *cls,
5652 struct GNUNET_SERVER_Client *client,
5653 const struct GNUNET_MessageHeader *message)
5655 const struct OutboundMessage *obm;
5656 const struct GNUNET_MessageHeader *obmm;
5657 struct TransmitClientMessageContext *tcmc;
5661 size = ntohs (message->size);
5663 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5666 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5669 GNUNET_STATISTICS_update (stats,
5670 gettext_noop ("# payload received for other peers"),
5673 obm = (const struct OutboundMessage *) message;
5674 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5675 msize = size - sizeof (struct OutboundMessage);
5677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5678 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5679 "SEND", GNUNET_i2s (&obm->peer),
5683 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5684 tcmc->client = client;
5685 tcmc->priority = ntohl (obm->priority);
5686 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5687 tcmc->msize = msize;
5688 /* FIXME: this memcpy can be up to 7% of our total runtime */
5689 memcpy (&tcmc[1], obmm, msize);
5690 GNUNET_SERVER_client_keep (client);
5691 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5692 &transmit_client_message,
5698 * Handle request connect message
5700 * @param cls closure (always NULL)
5701 * @param client identification of the client
5702 * @param message the actual message
5705 handle_request_connect (void *cls,
5706 struct GNUNET_SERVER_Client *client,
5707 const struct GNUNET_MessageHeader *message)
5709 const struct TransportRequestConnectMessage *trcm =
5710 (const struct TransportRequestConnectMessage *) message;
5712 GNUNET_STATISTICS_update (stats,
5713 gettext_noop ("# REQUEST CONNECT messages received"),
5717 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
5718 "Received a request connect message for peer `%s'\n",
5719 GNUNET_i2s(&trcm->peer));
5721 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5723 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5728 * Handle SET_QUOTA-message.
5730 * @param cls closure (always NULL)
5731 * @param client identification of the client
5732 * @param message the actual message
5735 handle_set_quota (void *cls,
5736 struct GNUNET_SERVER_Client *client,
5737 const struct GNUNET_MessageHeader *message)
5739 const struct QuotaSetMessage *qsm =
5740 (const struct QuotaSetMessage *) message;
5741 struct NeighbourList *n;
5743 GNUNET_STATISTICS_update (stats,
5744 gettext_noop ("# SET QUOTA messages received"),
5747 n = find_neighbour (&qsm->peer);
5750 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5751 GNUNET_STATISTICS_update (stats,
5752 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5759 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5761 (unsigned int) ntohl (qsm->quota.value__),
5762 (unsigned int) n->in_tracker.available_bytes_per_s__,
5763 GNUNET_i2s (&qsm->peer));
5765 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5767 if (0 == ntohl (qsm->quota.value__))
5770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5771 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5774 GNUNET_STATISTICS_update (stats,
5775 gettext_noop ("# disconnects due to quota of 0"),
5778 disconnect_neighbour (n, GNUNET_NO);
5780 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5785 * Take the given address and append it to the set of results sent back to
5788 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5789 * @param address the resolved name, NULL to indicate the last response
5792 transmit_address_to_client (void *cls, const char *address)
5794 struct GNUNET_SERVER_TransmitContext *tc = cls;
5797 if (NULL != address)
5799 slen = strlen (address) + 1;
5800 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5801 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5805 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5811 * Handle AddressLookup-message.
5813 * @param cls closure (always NULL)
5814 * @param client identification of the client
5815 * @param message the actual message
5818 handle_address_lookup (void *cls,
5819 struct GNUNET_SERVER_Client *client,
5820 const struct GNUNET_MessageHeader *message)
5822 const struct AddressLookupMessage *alum;
5823 struct TransportPlugin *lsPlugin;
5824 const char *nameTransport;
5825 const char *address;
5827 struct GNUNET_SERVER_TransmitContext *tc;
5828 struct GNUNET_TIME_Absolute timeout;
5829 struct GNUNET_TIME_Relative rtimeout;
5832 size = ntohs (message->size);
5833 if (size < sizeof (struct AddressLookupMessage))
5835 GNUNET_break_op (0);
5836 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5839 alum = (const struct AddressLookupMessage *) message;
5840 uint32_t addressLen = ntohl (alum->addrlen);
5841 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5843 GNUNET_break_op (0);
5844 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5847 address = (const char *) &alum[1];
5848 nameTransport = (const char *) &address[addressLen];
5850 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5852 GNUNET_break_op (0);
5853 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5856 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5857 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5858 numeric = ntohl (alum->numeric_only);
5859 lsPlugin = find_transport (nameTransport);
5860 if (NULL == lsPlugin)
5862 tc = GNUNET_SERVER_transmit_context_create (client);
5863 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5864 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5865 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5868 GNUNET_SERVER_disable_receive_done_warning (client);
5869 tc = GNUNET_SERVER_transmit_context_create (client);
5870 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5872 address, addressLen,
5875 &transmit_address_to_client, tc);
5879 * Handle PeerAddressLookupMessage.
5881 * @param cls closure (always NULL)
5882 * @param client identification of the client
5883 * @param message the actual message
5886 handle_peer_address_lookup (void *cls,
5887 struct GNUNET_SERVER_Client *client,
5888 const struct GNUNET_MessageHeader *message)
5890 const struct PeerAddressLookupMessage *peer_address_lookup;
5891 struct NeighbourList *neighbor_iterator;
5892 struct ReadyList *ready_iterator;
5893 struct ForeignAddressList *foreign_address_iterator;
5894 struct TransportPlugin *transport_plugin;
5897 struct GNUNET_SERVER_TransmitContext *tc;
5898 struct GNUNET_TIME_Absolute timeout;
5899 struct GNUNET_TIME_Relative rtimeout;
5902 size = ntohs (message->size);
5903 if (size < sizeof (struct PeerAddressLookupMessage))
5905 GNUNET_break_op (0);
5906 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5909 peer_address_lookup = (const struct PeerAddressLookupMessage *) message;
5911 timeout = GNUNET_TIME_absolute_ntoh (peer_address_lookup->timeout);
5912 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5914 neighbor_iterator = neighbours;
5915 while (neighbor_iterator != NULL)
5917 if (0 == memcmp(&neighbor_iterator->id, &peer_address_lookup->peer, sizeof(struct GNUNET_PeerIdentity)))
5919 neighbor_iterator = neighbor_iterator->next;
5922 /* Found no neighbor matching this peer id (shouldn't be possible, but...) */
5923 if (neighbor_iterator == NULL)
5926 tc = GNUNET_SERVER_transmit_context_create (client);
5927 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5928 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5929 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5933 ready_iterator = neighbor_iterator->plugins;
5934 GNUNET_SERVER_disable_receive_done_warning (client);
5935 tc = GNUNET_SERVER_transmit_context_create (client);
5936 while(ready_iterator != NULL)
5938 foreign_address_iterator = ready_iterator->addresses;
5939 while (foreign_address_iterator != NULL)
5941 transport_plugin = foreign_address_iterator->ready_list->plugin;
5942 if (foreign_address_iterator->addr != NULL)
5944 GNUNET_asprintf (&addr_buf, "%s --- %s",
5945 a2s (transport_plugin->short_name,
5946 foreign_address_iterator->addr,
5947 foreign_address_iterator->addrlen),
5948 (foreign_address_iterator->connected
5949 == GNUNET_YES) ? "CONNECTED"
5951 (foreign_address_iterator->validated
5952 == GNUNET_YES) ? "VALIDATED"
5954 transmit_address_to_client(tc, addr_buf);
5955 GNUNET_free(addr_buf);
5957 else if (foreign_address_iterator->addrlen == 0)
5959 GNUNET_asprintf (&addr_buf, "%s --- %s, %s", "<inbound>",
5960 (foreign_address_iterator->connected
5961 == GNUNET_YES) ? "CONNECTED"
5963 (foreign_address_iterator->validated
5964 == GNUNET_YES) ? "VALIDATED"
5966 transmit_address_to_client (tc, addr_buf);
5967 GNUNET_free(addr_buf);
5970 foreign_address_iterator = foreign_address_iterator->next;
5972 ready_iterator = ready_iterator->next;
5974 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5975 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5976 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5980 * Handle AddressIterateMessage
5982 * @param cls closure (always NULL)
5983 * @param client identification of the client
5984 * @param message the actual message
5987 handle_address_iterate (void *cls,
5988 struct GNUNET_SERVER_Client *client,
5989 const struct GNUNET_MessageHeader *message)
5991 const struct AddressIterateMessage *address_iterate;
5992 struct NeighbourList *neighbor_iterator;
5993 struct ReadyList *ready_iterator;
5994 struct ForeignAddressList *foreign_address_iterator;
5995 struct TransportPlugin *transport_plugin;
5998 struct GNUNET_SERVER_TransmitContext *tc;
5999 struct GNUNET_TIME_Absolute timeout;
6000 struct GNUNET_TIME_Relative rtimeout;
6003 size = ntohs (message->size);
6004 if (size < sizeof (struct AddressIterateMessage))
6006 GNUNET_break_op (0);
6007 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6010 address_iterate = (const struct AddressIterateMessage *) message;
6012 timeout = GNUNET_TIME_absolute_ntoh (address_iterate->timeout);
6013 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
6015 GNUNET_SERVER_disable_receive_done_warning (client);
6016 tc = GNUNET_SERVER_transmit_context_create (client);
6018 neighbor_iterator = neighbours;
6019 while (neighbor_iterator != NULL)
6021 ready_iterator = neighbor_iterator->plugins;
6022 while (ready_iterator != NULL)
6024 foreign_address_iterator = ready_iterator->addresses;
6025 while (foreign_address_iterator != NULL)
6027 transport_plugin = foreign_address_iterator->ready_list->plugin;
6028 if (foreign_address_iterator->addr != NULL)
6030 GNUNET_asprintf (&addr_buf, "%s:%s --- %s, %s",
6031 GNUNET_i2s(&neighbor_iterator->id),
6032 a2s (transport_plugin->short_name,
6033 foreign_address_iterator->addr,
6034 foreign_address_iterator->addrlen),
6035 (foreign_address_iterator->connected
6036 == GNUNET_YES) ? "CONNECTED"
6038 (foreign_address_iterator->validated
6039 == GNUNET_YES) ? "VALIDATED"
6041 transmit_address_to_client (tc, addr_buf);
6042 GNUNET_free(addr_buf);
6044 else if (foreign_address_iterator->addrlen == 0)
6046 GNUNET_asprintf (&addr_buf, "%s:%s --- %s, %s",
6047 GNUNET_i2s (&neighbor_iterator->id),
6049 (foreign_address_iterator->connected
6050 == GNUNET_YES) ? "CONNECTED"
6052 (foreign_address_iterator->validated
6053 == GNUNET_YES) ? "VALIDATED"
6055 transmit_address_to_client (tc, addr_buf);
6056 GNUNET_free(addr_buf);
6059 foreign_address_iterator = foreign_address_iterator->next;
6061 ready_iterator = ready_iterator->next;
6063 neighbor_iterator = neighbor_iterator->next;
6066 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6067 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6068 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6073 * Setup the environment for this plugin.
6076 create_environment (struct TransportPlugin *plug)
6078 plug->env.cfg = cfg;
6079 plug->env.my_identity = &my_identity;
6080 plug->env.our_hello = &our_hello;
6081 plug->env.cls = plug;
6082 plug->env.receive = &plugin_env_receive;
6083 plug->env.notify_address = &plugin_env_notify_address;
6084 plug->env.session_end = &plugin_env_session_end;
6085 plug->env.max_connections = max_connect_per_transport;
6086 plug->env.stats = stats;
6091 * Start the specified transport (load the plugin).
6094 start_transport (struct GNUNET_SERVER_Handle *server,
6097 struct TransportPlugin *plug;
6100 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6101 _("Loading `%s' transport plugin\n"), name);
6102 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
6103 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
6104 create_environment (plug);
6105 plug->short_name = GNUNET_strdup (name);
6106 plug->lib_name = libname;
6107 plug->next = plugins;
6109 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
6110 if (plug->api == NULL)
6112 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6113 _("Failed to load transport plugin for `%s'\n"), name);
6114 GNUNET_free (plug->short_name);
6115 plugins = plug->next;
6116 GNUNET_free (libname);
6123 * Called whenever a client is disconnected. Frees our
6124 * resources associated with that client.
6126 * @param cls closure
6127 * @param client identification of the client
6130 client_disconnect_notification (void *cls,
6131 struct GNUNET_SERVER_Client *client)
6133 struct TransportClient *pos;
6134 struct TransportClient *prev;
6135 struct ClientMessageQueueEntry *mqe;
6136 struct Blacklisters *bl;
6137 struct BlacklistCheck *bc;
6142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
6143 "Client disconnected, cleaning up.\n");
6145 /* clean up blacklister */
6149 if (bl->client == client)
6154 if (bc->bl_pos == bl)
6156 bc->bl_pos = bl->next;
6159 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
6162 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
6163 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
6169 GNUNET_CONTAINER_DLL_remove (bl_head,
6172 GNUNET_SERVER_client_drop (bl->client);
6178 /* clean up 'normal' clients */
6181 while ((pos != NULL) && (pos->client != client))
6188 while (NULL != (mqe = pos->message_queue_head))
6190 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
6191 pos->message_queue_tail,
6193 pos->message_count--;
6197 clients = pos->next;
6199 prev->next = pos->next;
6200 if (GNUNET_YES == pos->tcs_pending)
6205 if (pos->th != NULL)
6207 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
6210 GNUNET_break (0 == pos->message_count);
6216 * Function called when the service shuts down. Unloads our plugins
6217 * and cancels pending validations.
6219 * @param cls closure, unused
6220 * @param tc task context (unused)
6223 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6225 struct TransportPlugin *plug;
6226 struct TransportPlugin *tmp;
6227 struct OwnAddressList *al;
6228 struct CheckHelloValidatedContext *chvc;
6230 shutdown_in_progress = GNUNET_YES;
6231 while (neighbours != NULL)
6234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6235 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
6238 disconnect_neighbour (neighbours, GNUNET_NO);
6241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6242 "Transport service is unloading plugins...\n");
6245 while (plug != NULL)
6247 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
6249 GNUNET_SCHEDULER_cancel (plug->address_update_task);
6250 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
6252 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
6253 GNUNET_free (plug->lib_name);
6254 GNUNET_free (plug->short_name);
6255 while (NULL != (al = plug->addresses))
6257 plug->addresses = al->next;
6264 if (my_private_key != NULL)
6265 GNUNET_CRYPTO_rsa_key_free (my_private_key);
6266 GNUNET_free_non_null (our_hello);
6268 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
6271 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6272 validation_map = NULL;
6275 if (ats_task != GNUNET_SCHEDULER_NO_TASK)
6277 GNUNET_SCHEDULER_cancel(ats_task);
6278 ats_task = GNUNET_SCHEDULER_NO_TASK;
6283 /* free 'chvc' data structure */
6284 while (NULL != (chvc = chvc_head))
6286 chvc_head = chvc->next;
6287 if (chvc->piter != NULL)
6289 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
6290 GNUNET_STATISTICS_update (stats,
6291 gettext_noop ("# outstanding peerinfo iterate requests"),
6298 GNUNET_assert (chvc->ve_count == 0);
6305 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6308 if (peerinfo != NULL)
6310 GNUNET_PEERINFO_disconnect (peerinfo);
6313 if (GNUNET_SCHEDULER_NO_TASK != hello_task)
6315 GNUNET_SCHEDULER_cancel (hello_task);
6316 hello_task = GNUNET_SCHEDULER_NO_TASK;
6318 /* Can we assume those are gone by now, or do we need to clean up
6320 GNUNET_break (bl_head == NULL);
6321 GNUNET_break (bc_head == NULL);
6325 void ats_result_cb ()
6327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6328 "ATS Result callback\n");
6332 void create_ats_information ( struct ATS_peer **p,
6334 struct ATS_mechanism ** m,
6338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6339 "ATS requires clean address information\n");
6341 struct ATS_mechanism * mechanisms;
6342 struct ATS_peer *peers;
6344 int connected_addresses = 0;
6347 struct NeighbourList *next = neighbours;
6351 int found_addresses = GNUNET_NO;
6352 struct ReadyList *r_next = next->plugins;
6353 while (r_next != NULL)
6355 struct ForeignAddressList * a_next = r_next->addresses;
6356 while (a_next != NULL)
6359 found_addresses = GNUNET_YES;
6360 a_next = a_next->next;
6362 r_next = r_next->next;
6364 if (found_addresses) c_peers++;
6369 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6370 "Found %u peers with % u transport mechanisms\n", c_peers, c_mechs);
6373 if ((c_peers == 0) && (c_mechs == 0))
6382 mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
6383 peers = GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
6391 int found_addresses = GNUNET_NO;
6392 struct ReadyList *r_next = next->plugins;
6393 while (r_next != NULL)
6395 struct ForeignAddressList * a_next = r_next->addresses;
6396 while (a_next != NULL)
6398 if (a_next->connected == GNUNET_YES)
6399 connected_addresses ++;
6400 if (found_addresses == GNUNET_NO)
6402 peers[c_peers].peer = next->id;
6403 peers[c_peers].m_head = NULL;
6404 peers[c_peers].m_tail = NULL;
6405 peers[c_peers].f = 1.0 / c_mechs;
6408 mechanisms[c_mechs].addr = a_next;
6409 mechanisms[c_mechs].col_index = c_mechs;
6410 mechanisms[c_mechs].peer = &peers[c_peers];
6411 mechanisms[c_mechs].next = NULL;
6412 mechanisms[c_mechs].plugin = r_next->plugin;
6413 mechanisms[c_mechs].ressources = a_next->ressources;
6414 mechanisms[c_mechs].quality = a_next->quality;
6416 GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head,
6417 peers[c_peers].m_tail,
6418 &mechanisms[c_mechs]);
6419 found_addresses = GNUNET_YES;
6422 a_next = a_next->next;
6424 r_next = r_next->next;
6426 if (found_addresses == GNUNET_YES)
6437 GNUNET_STATISTICS_set(stats,
6438 gettext_noop ("# connected addresses"),
6439 connected_addresses,
6444 schedule_ats (void *cls,
6445 const struct GNUNET_SCHEDULER_TaskContext *tc)
6447 struct ATS_Handle *ats = (struct ATS_Handle *) cls;
6451 ats_task = GNUNET_SCHEDULER_NO_TASK;
6452 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
6455 if (shutdown_in_progress == GNUNET_YES)
6458 struct GNUNET_TIME_Relative delta =
6459 GNUNET_TIME_absolute_get_difference (last_ats_execution, GNUNET_TIME_absolute_get());
6460 if (delta.rel_value < ats_minimum_interval.rel_value)
6463 GNUNET_log (GNUNET_ERROR_TYPE_BULK,
6464 "Minimum time between cycles not reached\n");
6470 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
6472 ats_calculate_bandwidth_distribution (ats, stats);
6473 last_ats_execution = GNUNET_TIME_absolute_get();
6475 ats_task = GNUNET_SCHEDULER_add_delayed (ats_regular_interval,
6476 &schedule_ats, ats);
6479 struct ForeignAddressList * get_preferred_ats_address (
6480 struct NeighbourList *n)
6482 // TODO get ATS prefered address
6483 return find_ready_address(n);
6487 * Initiate transport service.
6489 * @param cls closure
6490 * @param server the initialized server
6491 * @param c configuration to use
6495 struct GNUNET_SERVER_Handle *server,
6496 const struct GNUNET_CONFIGURATION_Handle *c)
6498 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
6499 {&handle_start, NULL,
6500 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
6501 {&handle_hello, NULL,
6502 GNUNET_MESSAGE_TYPE_HELLO, 0},
6503 {&handle_send, NULL,
6504 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
6505 {&handle_request_connect, NULL,
6506 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
6507 {&handle_set_quota, NULL,
6508 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
6509 {&handle_address_lookup, NULL,
6510 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
6512 {&handle_peer_address_lookup, NULL,
6513 GNUNET_MESSAGE_TYPE_TRANSPORT_PEER_ADDRESS_LOOKUP,
6515 {&handle_address_iterate, NULL,
6516 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE,
6518 {&handle_blacklist_init, NULL,
6519 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
6520 {&handle_blacklist_reply, NULL,
6521 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
6527 unsigned long long tneigh;
6530 shutdown_in_progress = GNUNET_NO;
6532 stats = GNUNET_STATISTICS_create ("transport", cfg);
6533 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
6534 /* parse configuration */
6536 GNUNET_CONFIGURATION_get_value_number (c,
6541 GNUNET_CONFIGURATION_get_value_filename (c,
6543 "HOSTKEY", &keyfile)))
6545 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6547 ("Transport service is lacking key configuration settings. Exiting.\n"));
6548 GNUNET_SCHEDULER_shutdown ();
6551 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6554 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6555 validation_map = NULL;
6559 max_connect_per_transport = (uint32_t) tneigh;
6560 peerinfo = GNUNET_PEERINFO_connect (cfg);
6561 if (peerinfo == NULL)
6563 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6564 _("Could not access PEERINFO service. Exiting.\n"));
6565 GNUNET_SCHEDULER_shutdown ();
6568 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6571 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6572 validation_map = NULL;
6573 GNUNET_free (keyfile);
6576 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
6577 GNUNET_free (keyfile);
6578 if (my_private_key == NULL)
6580 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6582 ("Transport service could not access hostkey. Exiting.\n"));
6583 GNUNET_SCHEDULER_shutdown ();
6586 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6589 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6590 validation_map = NULL;
6593 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
6594 GNUNET_CRYPTO_hash (&my_public_key,
6595 sizeof (my_public_key), &my_identity.hashPubKey);
6596 /* setup notification */
6597 GNUNET_SERVER_disconnect_notify (server,
6598 &client_disconnect_notification, NULL);
6599 /* load plugins... */
6602 GNUNET_CONFIGURATION_get_value_string (c,
6603 "TRANSPORT", "PLUGINS", &plugs))
6605 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6606 _("Starting transport plugins `%s'\n"), plugs);
6607 pos = strtok (plugs, " ");
6610 start_transport (server, pos);
6612 pos = strtok (NULL, " ");
6614 GNUNET_free (plugs);
6616 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
6617 &shutdown_task, NULL);
6621 /* Initializing ATS */
6624 unsigned long long value;
6629 int v_b_min = 64000;
6632 ats_minimum_interval = ATS_MIN_INTERVAL;
6633 ats_regular_interval = ATS_EXEC_INTERVAL;
6635 /* loading cost ressources */
6636 for (co=0; co<available_ressources; co++)
6638 GNUNET_asprintf(§ion,"%s_UP",ressources[co].cfg_param);
6639 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
6641 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg,
6647 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6648 "Found ressource cost: [%s] = %llu\n",
6651 ressources[co].c_max = value;
6654 GNUNET_free (section);
6655 GNUNET_asprintf(§ion,"%s_DOWN",ressources[co].cfg_param);
6656 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
6658 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg,
6664 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6665 "Found ressource cost: [%s] = %llu\n",
6668 ressources[co].c_min = value;
6671 GNUNET_free (section);
6674 ats = ats_init (D, U, R, v_b_min, v_n_min,
6675 ATS_MAX_ITERATIONS, ATS_MAX_EXEC_DURATION,
6676 create_ats_information,
6679 int log_problem = GNUNET_NO;
6680 int log_solution = GNUNET_NO;
6681 int overwrite_dump = GNUNET_NO;
6682 int minimum_peers = 0;
6683 int minimum_addresses = 0;
6685 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MLP"))
6686 log_problem = GNUNET_CONFIGURATION_get_value_yesno (cfg,
6687 "transport","DUMP_MLP");
6689 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_SOLUTION"))
6690 log_solution = GNUNET_CONFIGURATION_get_value_yesno (cfg,
6691 "transport","DUMP_SOLUTION");
6692 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
6693 overwrite_dump = GNUNET_CONFIGURATION_get_value_yesno (cfg,
6694 "transport","DUMP_OVERWRITE");
6695 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_PEERS"))
6697 GNUNET_CONFIGURATION_get_value_number(cfg,
6698 "transport","DUMP_MIN_PEERS", &value);
6699 minimum_peers = value;
6701 if (GNUNET_CONFIGURATION_have_value(cfg,
6702 "transport", "DUMP_MIN_ADDRS"))
6704 GNUNET_CONFIGURATION_get_value_number(cfg,
6705 "transport","DUMP_MIN_ADDRS", &value);
6706 minimum_addresses= value;
6708 if (GNUNET_CONFIGURATION_have_value(cfg,
6709 "transport", "DUMP_OVERWRITE"))
6711 GNUNET_CONFIGURATION_get_value_number(cfg,
6712 "transport","DUMP_OVERWRITE", &value);
6713 overwrite_dump = value;
6716 if (GNUNET_CONFIGURATION_have_value(cfg,
6717 "transport", "ATS_MIN_INTERVAL"))
6719 GNUNET_CONFIGURATION_get_value_number(cfg,
6720 "transport","ATS_MIN_INTERVAL", &value);
6721 ats_minimum_interval.rel_value = value;
6724 if (GNUNET_CONFIGURATION_have_value(cfg,
6725 "transport", "ATS_EXEC_INTERVAL"))
6727 GNUNET_CONFIGURATION_get_value_number(cfg,
6728 "transport","ATS_EXEC_INTERVAL", &value);
6729 ats_regular_interval.rel_value = value;
6731 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
6733 GNUNET_CONFIGURATION_get_value_number(cfg,
6734 "transport","ATS_MIN_INTERVAL", &value);
6735 ats_minimum_interval.rel_value = value;
6738 ats_set_logging_options (ats,
6746 ats_task = GNUNET_SCHEDULER_add_now (&schedule_ats, ats);
6752 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6753 _("Transport service ready.\n"));
6755 /* If we have a blacklist file, read from it */
6756 read_blacklist_file(cfg);
6757 /* process client requests */
6758 GNUNET_SERVER_add_handlers (server, handlers);
6763 * The main function for the transport service.
6765 * @param argc number of arguments from the command line
6766 * @param argv command line arguments
6767 * @return 0 ok, 1 on error
6770 main (int argc, char *const *argv)
6772 a2s (NULL, NULL, 0); /* make compiler happy */
6773 return (GNUNET_OK ==
6774 GNUNET_SERVICE_run (argc,
6777 GNUNET_SERVICE_OPTION_NONE,
6778 &run, NULL)) ? 0 : 1;
6781 /* end of gnunet-service-transport.c */