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 "gnunet-service-transport_ats.h"
41 #include "transport.h"
45 #define DEBUG_BLACKLIST GNUNET_NO
47 #define DEBUG_PING_PONG GNUNET_NO
49 #define DEBUG_TRANSPORT_HELLO GNUNET_NO
51 #define DEBUG_INBOUND GNUNET_NO
54 * Should we do some additional checks (to validate behavior
57 #define EXTRA_CHECKS GNUNET_YES
60 * How many messages can we have pending for a given client process
61 * before we start to drop incoming messages? We typically should
62 * have only one client and so this would be the primary buffer for
63 * messages, so the number should be chosen rather generously.
65 * The expectation here is that most of the time the queue is large
66 * enough so that a drop is virtually never required. Note that
67 * this value must be about as large as 'TOTAL_MSGS' in the
68 * 'test_transport_api_reliability.c', otherwise that testcase may
71 #define MAX_PENDING (128 * 1024)
74 * Size of the per-transport blacklist hash maps.
76 #define TRANSPORT_BLACKLIST_HT_SIZE 16
79 * How often should we try to reconnect to a peer using a particular
80 * transport plugin before giving up? Note that the plugin may be
81 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
83 #define MAX_CONNECT_RETRY 3
86 * Limit on the number of ready-to-run tasks when validating
87 * HELLOs. If more tasks are ready to run, we will drop
88 * HELLOs instead of validating them.
90 #define MAX_HELLO_LOAD 4
93 * How often must a peer violate bandwidth quotas before we start
94 * to simply drop its messages?
96 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
99 * How long until a HELLO verification attempt should time out?
100 * Must be rather small, otherwise a partially successful HELLO
101 * validation (some addresses working) might not be available
102 * before a client's request for a connection fails for good.
103 * Besides, if a single request to an address takes a long time,
104 * then the peer is unlikely worthwhile anyway.
106 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
109 * How long is a PONG signature valid? We'll recycle a signature until
110 * 1/4 of this time is remaining. PONGs should expire so that if our
111 * external addresses change an adversary cannot replay them indefinitely.
112 * OTOH, we don't want to spend too much time generating PONG signatures,
113 * so they must have some lifetime to reduce our CPU usage.
115 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
118 * Priority to use for PONG messages.
120 #define TRANSPORT_PONG_PRIORITY 4
123 * How often do we re-add (cheaper) plugins to our list of plugins
124 * to try for a given connected peer?
126 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
129 * After how long do we expire an address in a HELLO that we just
130 * validated? This value is also used for our own addresses when we
133 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
137 * How long before an existing address expires should we again try to
138 * validate it? Must be (significantly) smaller than
139 * HELLO_ADDRESS_EXPIRATION.
141 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
144 * List of addresses of other peers
146 struct ForeignAddressList
149 * This is a linked list.
151 struct ForeignAddressList *next;
154 * Which ready list does this entry belong to.
156 struct ReadyList *ready_list;
159 * How long until we auto-expire this address (unless it is
160 * re-confirmed by the transport)?
162 struct GNUNET_TIME_Absolute expires;
165 * Task used to re-validate addresses, updates latencies and
168 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
176 * Session (or NULL if no valid session currently exists or if the
177 * plugin does not use sessions).
179 struct Session *session;
181 struct ATS_ressource_entry * ressources;
183 struct ATS_quality_entry * quality;
186 * What was the last latency observed for this address, plugin and peer?
188 struct GNUNET_TIME_Relative latency;
191 * If we did not successfully transmit a message to the given peer
192 * via this connection during the specified time, we should consider
193 * the connection to be dead. This is used in the case that a TCP
194 * transport simply stalls writing to the stream but does not
195 * formerly get a signal that the other peer died.
197 struct GNUNET_TIME_Absolute timeout;
200 * How often have we tried to connect using this plugin? Used to
201 * discriminate against addresses that do not work well.
202 * FIXME: not yet used, but should be!
204 unsigned int connect_attempts;
207 * DV distance to this peer (1 if no DV is used).
208 * FIXME: need to set this from transport plugins!
218 * Have we ever estimated the latency of this address? Used to
219 * ensure that the first time we add an address, we immediately
225 * Are we currently connected via this address? The first time we
226 * successfully transmit or receive data to a peer via a particular
227 * address, we set this to GNUNET_YES. If we later get an error
228 * (disconnect notification, transmission failure, timeout), we set
229 * it back to GNUNET_NO.
234 * Is this plugin currently busy transmitting to the specific target?
235 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
236 * messages do not count as 'in transmit'.
241 * Has this address been validated yet?
249 * Entry in linked list of network addresses for ourselves. Also
250 * includes a cached signature for 'struct TransportPongMessage's.
252 struct OwnAddressList
255 * This is a linked list.
257 struct OwnAddressList *next;
260 * How long until the current signature expires? (ZERO if the
261 * signature was never created).
263 struct GNUNET_TIME_Absolute pong_sig_expires;
266 * Signature for a 'struct TransportPongMessage' for this address.
268 struct GNUNET_CRYPTO_RsaSignature pong_signature;
279 * Entry in linked list of all of our plugins.
281 struct TransportPlugin
284 * This is a linked list.
286 struct TransportPlugin *next;
289 * API of the transport as returned by the plugin's
290 * initialization function.
292 struct GNUNET_TRANSPORT_PluginFunctions *api;
295 * Short name for the plugin (i.e. "tcp").
300 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
305 * List of our known addresses for this transport.
307 struct OwnAddressList *addresses;
310 * Environment this transport service is using
313 struct GNUNET_TRANSPORT_PluginEnvironment env;
316 * ID of task that is used to clean up expired addresses.
318 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
321 * Set to GNUNET_YES if we need to scrap the existing list of
322 * "addresses" and start fresh when we receive the next address
323 * update from a transport. Set to GNUNET_NO if we should just add
324 * the new address to the list and wait for the commit call.
328 struct ATS_plugin * rc;
331 * Hashmap of blacklisted peers for this particular transport.
333 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
336 struct NeighbourMapEntry;
339 * For each neighbour we keep a list of messages
340 * that we still want to transmit to the neighbour.
346 * This is a doubly linked list.
348 struct MessageQueue *next;
351 * This is a doubly linked list.
353 struct MessageQueue *prev;
356 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
357 * stuck together in memory. Allocated at the end of this struct.
359 const char *message_buf;
362 * Size of the message buf
364 size_t message_buf_size;
367 * Client responsible for queueing the message;
368 * used to check that a client has no two messages
369 * pending for the same target. Can be NULL.
371 struct TransportClient *client;
374 * Using which specific address should we send this message?
376 struct ForeignAddressList *specific_address;
379 * Peer ID of the Neighbour this entry belongs to.
381 struct GNUNET_PeerIdentity neighbour_id;
384 * Plugin that we used for the transmission.
385 * NULL until we scheduled a transmission.
387 struct TransportPlugin *plugin;
390 * At what time should we fail?
392 struct GNUNET_TIME_Absolute timeout;
395 * Internal message of the transport system that should not be
396 * included in the usual SEND-SEND_OK transmission confirmation
397 * traffic management scheme. Typically, "internal_msg" will
398 * be set whenever "client" is NULL (but it is not strictly
404 * How important is the message?
406 unsigned int priority;
412 * For a given Neighbour, which plugins are available
413 * to talk to this peer and what are their costs?
418 * This is a linked list.
420 struct ReadyList *next;
423 * Which of our transport plugins does this entry
426 struct TransportPlugin *plugin;
429 * Transport addresses, latency, and readiness for
430 * this particular plugin.
432 struct ForeignAddressList *addresses;
435 * To which neighbour does this ready list belong to?
437 struct NeighbourMapEntry *neighbour;
442 * Entry in neighbours.
444 struct NeighbourMapEntry
448 * Which of our transports is connected to this peer
449 * and what is their status?
451 struct ReadyList *plugins;
454 * Head of list of messages we would like to send to this peer;
455 * must contain at most one message per client.
457 struct MessageQueue *messages_head;
460 * Tail of list of messages we would like to send to this peer; must
461 * contain at most one message per client.
463 struct MessageQueue *messages_tail;
466 * Head of list of messages of messages we expected the continuation
467 * to be called to destroy the message
469 struct MessageQueue *cont_head;
472 * Tail of list of messages of messages we expected the continuation
473 * to be called to destroy the message
475 struct MessageQueue *cont_tail;
478 * Buffer for at most one payload message used when we receive
479 * payload data before our PING-PONG has succeeded. We then
480 * store such messages in this intermediary buffer until the
481 * connection is fully up.
483 struct GNUNET_MessageHeader *pre_connect_message_buffer;
486 * Context for peerinfo iteration.
487 * NULL after we are done processing peerinfo's information.
489 struct GNUNET_PEERINFO_IteratorContext *piter;
492 * Public key for this peer. Valid only if the respective flag is set below.
494 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
497 * Identity of this neighbour.
499 struct GNUNET_PeerIdentity id;
502 * ID of task scheduled to run when this peer is about to
503 * time out (will free resources associated with the peer).
505 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
508 * ID of task scheduled to run when we should retry transmitting
509 * the head of the message queue. Actually triggered when the
510 * transmission is timing out (we trigger instantly when we have
511 * a chance of success).
513 GNUNET_SCHEDULER_TaskIdentifier retry_task;
516 * How long until we should consider this peer dead
517 * (if we don't receive another message in the
520 struct GNUNET_TIME_Absolute peer_timeout;
523 * Tracker for inbound bandwidth.
525 struct GNUNET_BANDWIDTH_Tracker in_tracker;
528 * The latency we have seen for this particular address for
529 * this particular peer. This latency may have been calculated
530 * over multiple transports. This value reflects how long it took
531 * us to receive a response when SENDING via this particular
532 * transport/neighbour/address combination!
534 * FIXME: we need to periodically send PINGs to update this
535 * latency (at least more often than the current "huge" (11h?)
538 struct GNUNET_TIME_Relative latency;
541 * How often has the other peer (recently) violated the
542 * inbound traffic limit? Incremented by 10 per violation,
543 * decremented by 1 per non-violation (for each
546 unsigned int quota_violation_count;
549 * DV distance to this peer (1 if no DV is used).
554 * Have we seen an PONG from this neighbour in the past (and
555 * not had a disconnect since)?
560 * Do we have a valid public key for this neighbour?
562 int public_key_valid;
565 * Are we already in the process of disconnecting this neighbour?
570 * Performance data for the peer.
572 struct GNUNET_TRANSPORT_ATS_Information *ats;
576 * Message used to ask a peer to validate receipt (to check an address
577 * from a HELLO). Followed by the address we are trying to validate,
578 * or an empty address if we are just sending a PING to confirm that a
579 * connection which the receiver (of the PING) initiated is still valid.
581 struct TransportPingMessage
585 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
587 struct GNUNET_MessageHeader header;
590 * Challenge code (to ensure fresh reply).
592 uint32_t challenge GNUNET_PACKED;
595 * Who is the intended recipient?
597 struct GNUNET_PeerIdentity target;
603 * Message used to validate a HELLO. The challenge is included in the
604 * confirmation to make matching of replies to requests possible. The
605 * signature signs our public key, an expiration time and our address.<p>
607 * This message is followed by our transport address that the PING tried
608 * to confirm (if we liked it). The address can be empty (zero bytes)
609 * if the PING had not address either (and we received the request via
610 * a connection that we initiated).
612 struct TransportPongMessage
616 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
618 struct GNUNET_MessageHeader header;
621 * Challenge code from PING (showing freshness). Not part of what
622 * is signed so that we can re-use signatures.
624 uint32_t challenge GNUNET_PACKED;
629 struct GNUNET_CRYPTO_RsaSignature signature;
632 * What are we signing and why? Two possible reason codes can be here:
633 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
634 * plausible address for this peer (pid is set to identity of signer); or
635 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
636 * an address we used to connect to the peer with the given pid.
638 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
641 * When does this signature expire?
643 struct GNUNET_TIME_AbsoluteNBO expiration;
646 * Either the identity of the peer Who signed this message, or the
647 * identity of the peer that we're connected to using the given
648 * address (depending on purpose.type).
650 struct GNUNET_PeerIdentity pid;
653 * Size of address appended to this message (part of what is
654 * being signed, hence not redundant).
662 * Linked list of messages to be transmitted to the client. Each
663 * entry is followed by the actual message.
665 struct ClientMessageQueueEntry
668 * This is a doubly-linked list.
670 struct ClientMessageQueueEntry *next;
673 * This is a doubly-linked list.
675 struct ClientMessageQueueEntry *prev;
680 * Client connected to the transport service.
682 struct TransportClient
686 * This is a linked list.
688 struct TransportClient *next;
691 * Handle to the client.
693 struct GNUNET_SERVER_Client *client;
696 * Linked list of messages yet to be transmitted to
699 struct ClientMessageQueueEntry *message_queue_head;
702 * Tail of linked list of messages yet to be transmitted to the
705 struct ClientMessageQueueEntry *message_queue_tail;
708 * Current transmit request handle.
710 struct GNUNET_CONNECTION_TransmitHandle *th;
713 * Is a call to "transmit_send_continuation" pending? If so, we
714 * must not free this struct (even if the corresponding client
715 * disconnects) and instead only remove it from the linked list and
716 * set the "client" field to NULL.
721 * Length of the list of messages pending for this client.
723 unsigned int message_count;
729 * Context of currently active requests to peerinfo
730 * for validation of HELLOs.
732 struct CheckHelloValidatedContext;
736 * Entry in map of all HELLOs awaiting validation.
738 struct ValidationEntry
742 * NULL if this entry is not part of a larger HELLO validation.
744 struct CheckHelloValidatedContext *chvc;
747 * The address, actually a pointer to the end
748 * of this struct. Do not free!
753 * Name of the transport.
755 char *transport_name;
758 * The public key of the peer.
760 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
763 * ID of task that will clean up this entry if we don't succeed
764 * with the validation first.
766 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
769 * At what time did we send this validation?
771 struct GNUNET_TIME_Absolute send_time;
774 * Session being validated (or NULL for none).
776 struct Session *session;
779 * Challenge number we used.
792 * Context of currently active requests to peerinfo
793 * for validation of HELLOs.
795 struct CheckHelloValidatedContext
799 * This is a doubly-linked list.
801 struct CheckHelloValidatedContext *next;
804 * This is a doubly-linked list.
806 struct CheckHelloValidatedContext *prev;
809 * Hello that we are validating.
811 const struct GNUNET_HELLO_Message *hello;
814 * Context for peerinfo iteration.
815 * NULL after we are done processing peerinfo's information.
817 struct GNUNET_PEERINFO_IteratorContext *piter;
820 * Was a HELLO known for this peer to peerinfo?
825 * Number of validation entries currently referring to this
828 unsigned int ve_count;
833 * All zero hash for comparison.
835 static GNUNET_HashCode null_hash;
840 static struct GNUNET_HELLO_Message *our_hello;
845 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
850 static struct GNUNET_PeerIdentity my_identity;
855 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
860 const struct GNUNET_CONFIGURATION_Handle *cfg;
863 * Linked list of all clients to this service.
865 static struct TransportClient *clients;
868 * All loaded plugins.
870 static struct TransportPlugin *plugins;
873 * Handle to peerinfo service.
875 static struct GNUNET_PEERINFO_Handle *peerinfo;
878 * All known neighbours and their HELLOs.
880 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
883 * Number of neighbours we'd like to have.
885 static uint32_t max_connect_per_transport;
888 * Head of linked list.
890 static struct CheckHelloValidatedContext *chvc_head;
893 * Tail of linked list.
895 static struct CheckHelloValidatedContext *chvc_tail;
898 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
899 * of the given peer that we are currently validating).
901 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
904 * Handle for reporting statistics.
906 static struct GNUNET_STATISTICS_Handle *stats;
909 * Identifier of 'refresh_hello' task.
911 static GNUNET_SCHEDULER_TaskIdentifier hello_task;
914 * Identifier of ats scheduler task.
916 static GNUNET_SCHEDULER_TaskIdentifier ats_task;
919 * Is transport service shutting down ?
921 static int shutdown_in_progress;
924 * Handle for ats information
926 static struct ATS_Handle *ats;
929 * Time of last ats execution
931 struct GNUNET_TIME_Absolute last_ats_execution;
933 * Minimum interval between two ATS executions
935 struct GNUNET_TIME_Relative ats_minimum_interval;
937 * Regular interval when ATS execution is triggered
939 struct GNUNET_TIME_Relative ats_regular_interval;
942 * The peer specified by the given neighbour has timed-out or a plugin
943 * has disconnected. We may either need to do nothing (other plugins
944 * still up), or trigger a full disconnect and clean up. This
945 * function updates our state and do the necessary notifications.
946 * Also notifies our clients that the neighbour is now officially
949 * @param n the neighbour list entry for the peer
950 * @param check should we just check if all plugins
951 * disconnected or must we ask all plugins to
954 static void disconnect_neighbour (struct NeighbourMapEntry *n, int check);
957 * Check the ready list for the given neighbour and if a plugin is
958 * ready for transmission (and if we have a message), do so!
960 * @param nexi target peer for which to transmit
962 static void try_transmission_to_peer (struct NeighbourMapEntry *n);
964 struct ForeignAddressList * get_preferred_ats_address (
965 struct NeighbourMapEntry *n);
968 * Find an entry in the neighbour list for a particular peer.
970 * @return NULL if not found.
972 static struct NeighbourMapEntry *
973 find_neighbour (const struct GNUNET_PeerIdentity *key)
975 return GNUNET_CONTAINER_multihashmap_get (neighbours, &key->hashPubKey);
978 static int update_addr_value (struct ForeignAddressList *fal, uint32_t value , int ats_index)
982 for (c=0; c<available_quality_metrics; c++)
984 if (ats_index == qm[c].atis_index)
986 fal->quality[c].values[0] = fal->quality[c].values[1];
987 fal->quality[c].values[1] = fal->quality[c].values[2];
988 fal->quality[c].values[2] = value;
991 ats_modify_problem_state (ats, ATS_QUALITY_UPDATED);
995 if (set == GNUNET_NO)
997 for (c=0; c<available_ressources; c++)
999 if (ats_index == ressources[c].atis_index)
1001 fal->ressources[c].c = value;
1004 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_tail (client->message_queue_head,
1471 client->message_queue_tail,
1473 client->message_count++;
1474 if (client->th == NULL)
1476 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1478 GNUNET_TIME_UNIT_FOREVER_REL,
1479 &transmit_to_client_callback,
1481 GNUNET_assert (client->th != NULL);
1487 * Transmit a 'SEND_OK' notification to the given client for the
1490 * @param client who to notify
1491 * @param n neighbour to notify about, can be NULL (on failure)
1492 * @param target target of the transmission
1493 * @param result status code for the transmission request
1496 transmit_send_ok (struct TransportClient *client,
1497 struct NeighbourMapEntry *n,
1498 const struct GNUNET_PeerIdentity *target,
1501 struct SendOkMessage send_ok_msg;
1503 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1504 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1505 send_ok_msg.success = htonl (result);
1507 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1509 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1510 send_ok_msg.peer = *target;
1511 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1516 * Mark the given FAL entry as 'connected' (and hence preferred for
1517 * sending); also mark all others for the same peer as 'not connected'
1518 * (since only one can be preferred).
1520 * @param fal address to set to 'connected'
1523 mark_address_connected (struct ForeignAddressList *fal);
1528 * We should re-try transmitting to the given peer,
1529 * hopefully we've learned something in the meantime.
1532 retry_transmission_task (void *cls,
1533 const struct GNUNET_SCHEDULER_TaskContext *tc)
1535 struct NeighbourMapEntry *n = cls;
1537 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1538 try_transmission_to_peer (n);
1543 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1544 * upon "completion" of a send request. This tells the API
1545 * that it is now legal to send another message to the given
1548 * @param cls closure, identifies the entry on the
1549 * message queue that was transmitted and the
1550 * client responsible for queuing the message
1551 * @param target the peer receiving the message
1552 * @param result GNUNET_OK on success, if the transmission
1553 * failed, we should not tell the client to transmit
1557 transmit_send_continuation (void *cls,
1558 const struct GNUNET_PeerIdentity *target,
1561 struct MessageQueue *mq = cls;
1562 struct NeighbourMapEntry *n;
1564 GNUNET_STATISTICS_update (stats,
1565 gettext_noop ("# bytes pending with plugins"),
1566 - (int64_t) mq->message_buf_size,
1568 if (result == GNUNET_OK)
1570 GNUNET_STATISTICS_update (stats,
1571 gettext_noop ("# bytes successfully transmitted by plugins"),
1572 mq->message_buf_size,
1577 GNUNET_STATISTICS_update (stats,
1578 gettext_noop ("# bytes with transmission failure by plugins"),
1579 mq->message_buf_size,
1582 if (mq->specific_address != NULL)
1584 if (result == GNUNET_OK)
1586 mq->specific_address->timeout =
1587 GNUNET_TIME_relative_to_absolute
1588 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1589 if (mq->specific_address->validated == GNUNET_YES)
1590 mark_address_connected (mq->specific_address);
1594 if (mq->specific_address->connected == GNUNET_YES)
1597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1599 a2s (mq->specific_address->ready_list->plugin->short_name,
1600 mq->specific_address->addr,
1601 mq->specific_address->addrlen));
1603 GNUNET_STATISTICS_update (stats,
1604 gettext_noop ("# connected addresses"),
1607 mq->specific_address->connected = GNUNET_NO;
1610 if (! mq->internal_msg)
1611 mq->specific_address->in_transmit = GNUNET_NO;
1613 n = find_neighbour (&mq->neighbour_id);
1614 if (mq->client != NULL)
1615 transmit_send_ok (mq->client, n, target, result);
1616 GNUNET_assert (n != NULL);
1617 GNUNET_CONTAINER_DLL_remove (n->cont_head,
1621 if (result == GNUNET_OK)
1622 try_transmission_to_peer (n);
1623 else if (GNUNET_SCHEDULER_NO_TASK == n->retry_task)
1624 n->retry_task = GNUNET_SCHEDULER_add_now (&retry_transmission_task,
1630 * Check the ready list for the given neighbour and if a plugin is
1631 * ready for transmission (and if we have a message), do so!
1633 * @param neighbour target peer for which to transmit
1636 try_transmission_to_peer (struct NeighbourMapEntry *n)
1638 struct ReadyList *rl;
1639 struct MessageQueue *mq;
1640 struct GNUNET_TIME_Relative timeout;
1644 if (n->messages_head == NULL)
1647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1648 "Transmission queue for `%4s' is empty\n",
1649 GNUNET_i2s (&n->id));
1651 return; /* nothing to do */
1654 mq = n->messages_head;
1655 force_address = GNUNET_YES;
1656 if (mq->specific_address == NULL)
1659 mq->specific_address = get_preferred_ats_address(n);
1660 GNUNET_STATISTICS_update (stats,
1661 gettext_noop ("# transport selected peer address freely"),
1664 force_address = GNUNET_NO;
1666 if (mq->specific_address == NULL)
1668 GNUNET_STATISTICS_update (stats,
1669 gettext_noop ("# transport failed to selected peer address"),
1672 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1673 if (timeout.rel_value == 0)
1676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1677 "No destination address available to transmit message of size %u to peer `%4s'\n",
1678 mq->message_buf_size,
1679 GNUNET_i2s (&mq->neighbour_id));
1681 GNUNET_STATISTICS_update (stats,
1682 gettext_noop ("# bytes in message queue for other peers"),
1683 - (int64_t) mq->message_buf_size,
1685 GNUNET_STATISTICS_update (stats,
1686 gettext_noop ("# bytes discarded (no destination address available)"),
1687 mq->message_buf_size,
1689 if (mq->client != NULL)
1690 transmit_send_ok (mq->client, n, &n->id, GNUNET_NO);
1691 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1695 return; /* nobody ready */
1697 GNUNET_STATISTICS_update (stats,
1698 gettext_noop ("# message delivery deferred (no address)"),
1701 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1702 GNUNET_SCHEDULER_cancel (n->retry_task);
1703 n->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
1704 &retry_transmission_task,
1707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1708 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1709 mq->message_buf_size,
1710 GNUNET_i2s (&mq->neighbour_id),
1713 /* FIXME: might want to trigger peerinfo lookup here
1714 (unless that's already pending...) */
1717 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1720 if (mq->specific_address->connected == GNUNET_NO)
1721 mq->specific_address->connect_attempts++;
1722 rl = mq->specific_address->ready_list;
1723 mq->plugin = rl->plugin;
1724 if (!mq->internal_msg)
1725 mq->specific_address->in_transmit = GNUNET_YES;
1727 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1728 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1729 mq->message_buf_size,
1730 GNUNET_i2s (&n->id),
1731 (mq->specific_address->addr != NULL)
1732 ? a2s (mq->plugin->short_name,
1733 mq->specific_address->addr,
1734 mq->specific_address->addrlen)
1736 rl->plugin->short_name);
1738 GNUNET_STATISTICS_update (stats,
1739 gettext_noop ("# bytes in message queue for other peers"),
1740 - (int64_t) mq->message_buf_size,
1742 GNUNET_STATISTICS_update (stats,
1743 gettext_noop ("# bytes pending with plugins"),
1744 mq->message_buf_size,
1747 GNUNET_CONTAINER_DLL_insert (n->cont_head,
1751 ret = rl->plugin->api->send (rl->plugin->api->cls,
1754 mq->message_buf_size,
1756 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1757 mq->specific_address->session,
1758 mq->specific_address->addr,
1759 mq->specific_address->addrlen,
1761 &transmit_send_continuation, mq);
1764 /* failure, but 'send' would not call continuation in this case,
1765 so we need to do it here! */
1766 transmit_send_continuation (mq,
1774 * Send the specified message to the specified peer.
1776 * @param client source of the transmission request (can be NULL)
1777 * @param peer_address ForeignAddressList where we should send this message
1778 * @param priority how important is the message
1779 * @param timeout how long do we have to transmit?
1780 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1781 * @param message_buf_size total size of all messages in message_buf
1782 * @param is_internal is this an internal message; these are pre-pended and
1783 * also do not count for plugins being "ready" to transmit
1784 * @param neighbour handle to the neighbour for transmission
1787 transmit_to_peer (struct TransportClient *client,
1788 struct ForeignAddressList *peer_address,
1789 unsigned int priority,
1790 struct GNUNET_TIME_Relative timeout,
1791 const char *message_buf,
1792 size_t message_buf_size,
1793 int is_internal, struct NeighbourMapEntry *neighbour)
1795 struct MessageQueue *mq;
1800 /* check for duplicate submission */
1801 mq = neighbour->messages_head;
1804 if (mq->client == client)
1806 /* client transmitted to same peer twice
1807 before getting SEND_OK! */
1815 GNUNET_STATISTICS_update (stats,
1816 gettext_noop ("# bytes in message queue for other peers"),
1819 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1820 mq->specific_address = peer_address;
1821 mq->client = client;
1822 /* FIXME: this memcpy can be up to 7% of our total runtime! */
1823 memcpy (&mq[1], message_buf, message_buf_size);
1824 mq->message_buf = (const char*) &mq[1];
1825 mq->message_buf_size = message_buf_size;
1826 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1827 mq->internal_msg = is_internal;
1828 mq->priority = priority;
1829 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1831 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1832 neighbour->messages_tail,
1835 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1836 neighbour->messages_tail,
1837 neighbour->messages_tail,
1839 try_transmission_to_peer (neighbour);
1844 * Send a plain PING (without address or our HELLO) to the given
1845 * foreign address to try to establish a connection (and validate
1846 * that the other peer is really who he claimed he is).
1848 * @param n neighbour to PING
1851 transmit_plain_ping (struct NeighbourMapEntry *n)
1853 struct ValidationEntry *ve;
1854 struct TransportPingMessage ping;
1855 struct ReadyList *rl;
1856 struct TransportPlugin *plugin;
1857 struct ForeignAddressList *fal;
1859 if (! n->public_key_valid)
1861 /* This should not happen since the other peer
1862 should send us a HELLO prior to sending his
1864 GNUNET_break_op (0);
1865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1866 "Could not transmit plain PING to `%s': public key not known\n",
1867 GNUNET_i2s (&n->id));
1870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1871 "Looking for addresses to transmit plain PING to `%s'\n",
1872 GNUNET_i2s (&n->id));
1873 for (rl = n->plugins; rl != NULL; rl = rl->next)
1875 plugin = rl->plugin;
1876 for (fal = rl->addresses; fal != NULL; fal = fal->next)
1878 if (! fal->connected)
1880 ve = GNUNET_malloc (sizeof (struct ValidationEntry));
1881 ve->transport_name = GNUNET_strdup (plugin->short_name);
1882 ve->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1884 ve->send_time = GNUNET_TIME_absolute_get();
1885 ve->session = fal->session;
1886 memcpy(&ve->publicKey,
1888 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1889 ve->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
1890 &timeout_hello_validation,
1892 GNUNET_CONTAINER_multihashmap_put (validation_map,
1895 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1896 ping.header.size = htons(sizeof(struct TransportPingMessage));
1897 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
1898 ping.challenge = htonl(ve->challenge);
1899 memcpy(&ping.target, &n->id, sizeof(struct GNUNET_PeerIdentity));
1900 GNUNET_STATISTICS_update (stats,
1901 gettext_noop ("# PING without HELLO messages sent"),
1904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1905 "Transmitting plain PING to `%s'\n",
1906 GNUNET_i2s (&n->id));
1907 transmit_to_peer (NULL,
1909 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1910 HELLO_VERIFICATION_TIMEOUT,
1911 (const char*) &ping, sizeof (ping),
1919 * Mark the given FAL entry as 'connected' (and hence preferred for
1920 * sending); also mark all others for the same peer as 'not connected'
1921 * (since only one can be preferred).
1923 * @param fal address to set to 'connected'
1926 mark_address_connected(struct ForeignAddressList *fal)
1928 struct ForeignAddressList *pos;
1929 struct ForeignAddressList *inbound;
1930 struct ForeignAddressList *outbound;
1932 GNUNET_assert (GNUNET_YES == fal->validated);
1933 if (fal->connected == GNUNET_YES)
1934 return; /* nothing to do */
1938 pos = fal->ready_list->addresses;
1941 /* Already have inbound address, and this is also an inbound address, don't switch!! */
1942 if ( (GNUNET_YES == pos->connected) &&
1943 (0 == pos->addrlen) &&
1944 (0 == fal->addrlen) )
1946 if ( (0 == pos->addrlen) &&
1947 (GNUNET_YES == pos->connected) )
1952 pos = fal->ready_list->addresses;
1955 /* Already have outbound address, and this is also an outbound address, don't switch!! */
1956 if ( (GNUNET_YES == pos->connected) &&
1957 (0 < pos->addrlen) &&
1958 (0 < fal->addrlen) )
1960 if ( (0 < pos->addrlen) && (GNUNET_YES == pos->connected) )
1966 if (inbound != NULL)
1967 fprintf(stderr, "Peer: %s, have inbound connection.\n", GNUNET_i2s(&my_identity));
1968 if (outbound != NULL)
1969 fprintf(stderr, "Peer: %s, have outbound connection.\n", GNUNET_i2s(&my_identity));
1972 /* Have an inbound connection to this peer which is valid; our id is lower, ignore outbound connection! */
1973 if ((inbound != NULL) && (0 != fal->addrlen) && (1
1974 == GNUNET_CRYPTO_hash_xorcmp (&inbound->ready_list->neighbour->id.hashPubKey,
1975 &my_identity.hashPubKey, &null_hash)))
1978 fprintf(stderr, "Peer: %s, had inbound connection, ignoring outbound!\n", GNUNET_i2s(&my_identity));
1982 else if ((outbound != NULL) && (0 == fal->addrlen) && ((-1
1983 == GNUNET_CRYPTO_hash_xorcmp (&outbound->ready_list->neighbour->id.hashPubKey,
1984 &my_identity.hashPubKey, &null_hash))))
1987 fprintf(stderr, "Peer: %s, have outbound connection, ignoring inbound!\n", GNUNET_i2s(&my_identity));
1992 pos = fal->ready_list->addresses;
1995 if ((GNUNET_YES == pos->connected) && (0 < pos->addrlen))
1998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1999 "Marking address `%s' as no longer connected (due to connect on other address)\n",
2000 a2s (pos->ready_list->plugin->short_name, pos->addr,
2005 "Peer: %s, setting %s connection to disconnected.\n",
2006 GNUNET_i2s(&my_identity),
2007 (0 == pos->addrlen) ? "INBOUND" : "OUTBOUND");
2009 pos->connected = GNUNET_NO;
2010 GNUNET_STATISTICS_update (stats,
2011 gettext_noop ("# connected addresses"), -1,
2016 GNUNET_assert (GNUNET_NO == fal->connected);
2017 fal->connected = GNUNET_YES;
2018 GNUNET_STATISTICS_update (stats, gettext_noop ("# connected addresses"),
2024 * Find an address in any of the available transports for
2025 * the given neighbour that would be good for message
2026 * transmission. This is essentially the transport selection
2029 * @param neighbour for whom to select an address
2030 * @return selected address, NULL if we have none
2032 struct ForeignAddressList *
2033 find_ready_address(struct NeighbourMapEntry *neighbour)
2035 struct ReadyList *head = neighbour->plugins;
2036 struct ForeignAddressList *addresses;
2037 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
2038 struct ForeignAddressList *best_address;
2040 /* Hack to prefer unix domain sockets */
2041 struct ForeignAddressList *unix_address = NULL;
2043 best_address = NULL;
2044 while (head != NULL)
2046 addresses = head->addresses;
2047 while (addresses != NULL)
2049 if ( (addresses->timeout.abs_value < now.abs_value) &&
2050 (addresses->connected == GNUNET_YES) )
2053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054 "Marking long-time inactive connection to `%4s' as down.\n",
2055 GNUNET_i2s (&neighbour->id));
2057 GNUNET_STATISTICS_update (stats,
2058 gettext_noop ("# connected addresses"),
2061 addresses->connected = GNUNET_NO;
2063 addresses = addresses->next;
2066 addresses = head->addresses;
2067 while (addresses != NULL)
2070 if (addresses->addr != NULL)
2071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2072 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
2073 a2s (head->plugin->short_name,
2075 addresses->addrlen),
2076 GNUNET_i2s (&neighbour->id),
2077 addresses->connected,
2078 addresses->in_transmit,
2079 addresses->validated,
2080 addresses->connect_attempts,
2081 (unsigned long long) addresses->timeout.abs_value,
2082 (unsigned int) addresses->distance);
2084 if (0==strcmp(head->plugin->short_name,"unix"))
2086 if ( (unix_address == NULL) ||
2087 ( (unix_address != NULL) &&
2088 (addresses->latency.rel_value < unix_address->latency.rel_value) ) )
2089 unix_address = addresses;
2091 if ( ( (best_address == NULL) ||
2092 (addresses->connected == GNUNET_YES) ||
2093 (best_address->connected == GNUNET_NO) ) &&
2094 (addresses->in_transmit == GNUNET_NO) &&
2095 ( (best_address == NULL) ||
2096 (addresses->latency.rel_value < best_address->latency.rel_value)) )
2097 best_address = addresses;
2098 /* FIXME: also give lower-latency addresses that are not
2099 connected a chance some times... */
2100 addresses = addresses->next;
2102 if (unix_address != NULL)
2106 if (unix_address != NULL)
2108 best_address = unix_address;
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 "Found UNIX address, forced this address\n");
2114 if (best_address != NULL)
2117 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2118 "Best address found (`%s') has latency of %llu ms.\n",
2119 (best_address->addrlen > 0)
2120 ? a2s (best_address->ready_list->plugin->short_name,
2122 best_address->addrlen)
2124 best_address->latency.rel_value);
2129 GNUNET_STATISTICS_update (stats,
2130 gettext_noop ("# transmission attempts failed (no address)"),
2135 return best_address;
2142 struct GeneratorContext
2144 struct TransportPlugin *plug_pos;
2145 struct OwnAddressList *addr_pos;
2146 struct GNUNET_TIME_Absolute expiration;
2154 address_generator (void *cls, size_t max, void *buf)
2156 struct GeneratorContext *gc = cls;
2159 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
2161 gc->plug_pos = gc->plug_pos->next;
2162 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
2164 if (NULL == gc->plug_pos)
2169 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
2172 gc->addr_pos->addrlen, buf, max);
2173 gc->addr_pos = gc->addr_pos->next;
2180 transmit_our_hello_if_pong (void *cls,
2181 const GNUNET_HashCode *key,
2184 struct NeighbourMapEntry *npos = value;
2186 if (GNUNET_YES != npos->received_pong)
2189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2190 "Transmitting updated `%s' to neighbour `%4s'\n",
2191 "HELLO", GNUNET_i2s (&npos->id));
2193 GNUNET_STATISTICS_update (stats,
2194 gettext_noop ("# transmitted my HELLO to other peers"),
2197 transmit_to_peer (NULL, NULL, 0,
2198 HELLO_ADDRESS_EXPIRATION,
2199 (const char *) our_hello,
2200 GNUNET_HELLO_size(our_hello),
2207 * Construct our HELLO message from all of the addresses of
2208 * all of the transports.
2211 * @param tc scheduler context
2214 refresh_hello_task (void *cls,
2215 const struct GNUNET_SCHEDULER_TaskContext *tc)
2217 struct GNUNET_HELLO_Message *hello;
2218 struct TransportClient *cpos;
2219 struct GeneratorContext gc;
2221 hello_task = GNUNET_SCHEDULER_NO_TASK;
2222 gc.plug_pos = plugins;
2223 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
2224 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2225 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2228 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
2230 GNUNET_STATISTICS_update (stats,
2231 gettext_noop ("# refreshed my HELLO"),
2235 while (cpos != NULL)
2237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238 "Transmitting my HELLO to client!\n");
2239 transmit_to_client (cpos,
2240 (const struct GNUNET_MessageHeader *) hello,
2245 GNUNET_free_non_null (our_hello);
2247 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
2248 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
2249 &transmit_our_hello_if_pong,
2255 * Schedule task to refresh hello (unless such a
2256 * task exists already).
2261 #if DEBUG_TRANSPORT_HELLO
2262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2263 "refresh_hello() called!\n");
2265 if (hello_task != GNUNET_SCHEDULER_NO_TASK)
2268 = GNUNET_SCHEDULER_add_now (&refresh_hello_task,
2274 * Iterator over hash map entries that NULLs the session of validation
2275 * entries that match the given session.
2277 * @param cls closure (the 'struct Session*' to match against)
2278 * @param key current key code (peer ID, not used)
2279 * @param value value in the hash map ('struct ValidationEntry*')
2280 * @return GNUNET_YES (we should continue to iterate)
2283 remove_session_validations (void *cls,
2284 const GNUNET_HashCode * key,
2287 struct Session *session = cls;
2288 struct ValidationEntry *ve = value;
2290 if (session == ve->session)
2297 * We've been disconnected from the other peer (for some
2298 * connection-oriented transport). Either quickly
2299 * re-establish the connection or signal the disconnect
2302 * Only signal CORE level disconnect if ALL addresses
2303 * for the peer are exhausted.
2305 * @param p overall plugin context
2306 * @param nl neighbour that was disconnected
2309 try_fast_reconnect (struct TransportPlugin *p,
2310 struct NeighbourMapEntry *nl)
2312 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2313 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2314 "try_fast_reconnect not implemented!\n");
2315 /* Note: the idea here is to hide problems with transports (or
2316 switching between plugins) from the core to eliminate the need to
2317 re-negotiate session keys and the like; OTOH, we should tell core
2318 quickly (much faster than timeout) `if a connection was lost and
2319 could not be re-established (i.e. other peer went down or is
2320 unable / refuses to communicate);
2322 So we should consider:
2323 1) ideally: our own willingness / need to connect
2324 2) prior failures to connect to this peer (by plugin)
2325 3) ideally: reasons why other peer terminated (as far as knowable)
2327 Most importantly, it must be POSSIBLE for another peer to terminate
2328 a connection for a while (without us instantly re-establishing it).
2329 Similarly, if another peer is gone we should quickly notify CORE.
2330 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2331 on the other end), we should reconnect in such a way that BOTH CORE
2332 services never even notice.
2333 Furthermore, the same mechanism (or small variation) could be used
2334 to switch to a better-performing plugin (ATS).
2336 Finally, this needs to be tested throughly... */
2339 * GNUNET_NO in the call below makes transport disconnect the peer,
2340 * even if only a single address (out of say, six) went away. This
2341 * function must be careful to ONLY disconnect if the peer is gone,
2342 * not just a specific address.
2344 * More specifically, half the places it was used had it WRONG.
2347 /* No reconnect, signal disconnect instead! */
2350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2351 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2352 "try_fast_reconnect");
2354 GNUNET_STATISTICS_update (stats,
2355 gettext_noop ("# disconnects due to try_fast_reconnect"),
2359 disconnect_neighbour (nl, GNUNET_YES);
2365 * Function that will be called whenever the plugin internally
2366 * cleans up a session pointer and hence the service needs to
2367 * discard all of those sessions as well. Plugins that do not
2368 * use sessions can simply omit calling this function and always
2369 * use NULL wherever a session pointer is needed.
2371 * @param cls closure
2372 * @param peer which peer was the session for
2373 * @param session which session is being destoyed
2376 plugin_env_session_end (void *cls,
2377 const struct GNUNET_PeerIdentity *peer,
2378 struct Session *session)
2380 struct TransportPlugin *p = cls;
2381 struct NeighbourMapEntry *nl;
2382 struct ReadyList *rl;
2383 struct ForeignAddressList *pos;
2384 struct ForeignAddressList *prev;
2387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2388 "Session ended with peer `%4s', %s\n",
2390 "plugin_env_session_end");
2392 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2393 &remove_session_validations,
2395 nl = find_neighbour (peer);
2399 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400 "No neighbour record found for peer `%4s'\n",
2403 return; /* was never marked as connected */
2408 if (rl->plugin == p)
2415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416 "Plugin was associated with peer `%4s'\n",
2419 GNUNET_STATISTICS_update (stats,
2420 gettext_noop ("# disconnects due to session end"),
2423 disconnect_neighbour (nl, GNUNET_YES);
2427 pos = rl->addresses;
2428 while ( (pos != NULL) &&
2429 (pos->session != session) )
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2438 "Session was never marked as ready for peer `%4s'\n",
2442 int validations_pending = GNUNET_CONTAINER_multihashmap_contains (validation_map, &peer->hashPubKey);
2444 /* No session was marked as ready, but we have pending validations so do not disconnect from neighbour */
2445 if (validations_pending ==GNUNET_YES)
2448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449 "Not disconnecting from peer `%4s due to pending address validations\n", GNUNET_i2s(peer));
2454 //FIXME: This conflicts with inbound tcp connections and tcp nat ... debugging in progress
2455 GNUNET_STATISTICS_update (stats,
2456 gettext_noop ("# disconnects due to unready session"),
2460 disconnect_neighbour (nl, GNUNET_YES);
2461 return; /* was never marked as connected */
2463 pos->session = NULL;
2464 if (GNUNET_YES == pos->connected)
2466 pos->connected = GNUNET_NO;
2467 GNUNET_STATISTICS_update (stats,
2468 gettext_noop ("# connected addresses"),
2472 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2474 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2475 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2478 if (pos->addrlen != 0)
2480 if (nl->received_pong != GNUNET_NO)
2482 GNUNET_STATISTICS_update (stats,
2483 gettext_noop ("# try_fast_reconnect thanks to plugin_env_session_end"),
2486 if (GNUNET_YES == pos->connected)
2487 try_fast_reconnect (p, nl);
2491 GNUNET_STATISTICS_update (stats,
2492 gettext_noop ("# disconnects due to missing pong"),
2495 /* FIXME this is never true?! See: line 2416*/
2496 if (GNUNET_YES == pos->connected)
2497 disconnect_neighbour (nl, GNUNET_YES);
2502 /* was inbound connection, free 'pos' */
2504 rl->addresses = pos->next;
2506 prev->next = pos->next;
2507 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2509 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2510 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2512 GNUNET_free_non_null (pos->ressources);
2513 GNUNET_free_non_null (pos->quality);
2515 ats_modify_problem_state (ats, ATS_MODIFIED);
2517 if (GNUNET_YES != pos->connected)
2519 /* nothing else to do, connection was never up... */
2523 pos->connected = GNUNET_NO;
2524 GNUNET_STATISTICS_update (stats,
2525 gettext_noop ("# connected addresses"),
2530 if (nl->received_pong == GNUNET_NO)
2532 GNUNET_STATISTICS_update (stats,
2533 gettext_noop ("# disconnects due to NO pong"),
2536 disconnect_neighbour (nl, GNUNET_YES);
2537 return; /* nothing to do, never connected... */
2539 /* check if we have any validated addresses left */
2540 pos = rl->addresses;
2543 if (GNUNET_YES == pos->validated)
2545 GNUNET_STATISTICS_update (stats,
2546 gettext_noop ("# try_fast_reconnect thanks to validated_address"),
2549 try_fast_reconnect (p, nl);
2554 /* no valid addresses left, signal disconnect! */
2557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2558 "Disconnecting peer `%4s', %s\n",
2560 "plugin_env_session_end");
2562 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2563 * it means there aren't any left for this PLUGIN/PEER combination! So
2564 * calling disconnect_neighbour here with GNUNET_NO forces disconnect
2565 * when it isn't necessary. Using GNUNET_YES at least checks to see
2566 * if there are any addresses that work first, so as not to overdo it.
2569 GNUNET_STATISTICS_update (stats,
2570 gettext_noop ("# disconnects due to plugin_env_session_end"),
2573 disconnect_neighbour (nl, GNUNET_YES);
2578 * Function that must be called by each plugin to notify the
2579 * transport service about the addresses under which the transport
2580 * provided by the plugin can be reached.
2582 * @param cls closure
2583 * @param add_remove GNUNET_YES to add, GNUNET_NO to remove the address
2584 * @param addr one of the addresses of the host, NULL for the last address
2585 * the specific address format depends on the transport
2586 * @param addrlen length of the address
2589 plugin_env_notify_address (void *cls,
2594 struct TransportPlugin *p = cls;
2595 struct OwnAddressList *al;
2596 struct OwnAddressList *prev;
2598 GNUNET_assert (p->api != NULL);
2600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601 (add_remove == GNUNET_YES)
2602 ? "Adding `%s':%s to the set of our addresses\n"
2603 : "Removing `%s':%s from the set of our addresses\n",
2608 GNUNET_assert (addr != NULL);
2609 if (GNUNET_NO == add_remove)
2615 if ( (addrlen == al->addrlen) &&
2616 (0 == memcmp (addr, &al[1], addrlen)) )
2619 p->addresses = al->next;
2621 prev->next = al->next;
2632 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2633 al->next = p->addresses;
2635 al->addrlen = addrlen;
2636 memcpy (&al[1], addr, addrlen);
2642 * Notify all of our clients about a peer connecting.
2645 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2646 struct GNUNET_TIME_Relative latency,
2649 struct ConnectInfoMessage * cim;
2650 struct TransportClient *cpos;
2654 if (0 == memcmp (peer,
2656 sizeof (struct GNUNET_PeerIdentity)))
2662 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2663 "Notifying clients about connection with `%s'\n",
2666 GNUNET_STATISTICS_update (stats,
2667 gettext_noop ("# peers connected"),
2672 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2673 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2674 cim = GNUNET_malloc (size);
2675 cim->header.size = htons (size);
2676 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2677 cim->ats_count = htonl(2);
2678 (&cim->ats)[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2679 (&cim->ats)[0].value = htonl (distance);
2680 (&cim->ats)[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2681 (&cim->ats)[1].value = htonl ((uint32_t) latency.rel_value);
2682 (&cim->ats)[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2683 (&cim->ats)[2].value = htonl (0);
2684 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2686 /* notify ats about connecting peer */
2687 if ((ats != NULL) && (shutdown_in_progress == GNUNET_NO))
2690 ats_modify_problem_state(ats, ATS_MODIFIED);
2691 ats_calculate_bandwidth_distribution (ats);
2695 while (cpos != NULL)
2697 transmit_to_client (cpos, &cim->header, GNUNET_NO);
2705 * Notify all of our clients about a peer disconnecting.
2708 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2710 struct DisconnectInfoMessage dim;
2711 struct TransportClient *cpos;
2713 if (0 == memcmp (peer,
2715 sizeof (struct GNUNET_PeerIdentity)))
2721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2722 "Notifying clients about lost connection to `%s'\n",
2725 GNUNET_STATISTICS_update (stats,
2726 gettext_noop ("# peers connected"),
2729 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2730 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2731 dim.reserved = htonl (0);
2732 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2734 /* notify ats about connecting peer */
2735 if ((ats != NULL) && (shutdown_in_progress == GNUNET_NO))
2738 ats_modify_problem_state(ats, ATS_MODIFIED);
2739 ats_calculate_bandwidth_distribution (ats);
2744 while (cpos != NULL)
2746 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2753 * Find a ForeignAddressList entry for the given neighbour
2754 * that matches the given address and transport.
2756 * @param neighbour which peer we care about
2757 * @param tname name of the transport plugin
2758 * @param session session to look for, NULL for 'any'; otherwise
2759 * can be used for the service to "learn" this session ID
2761 * @param addr binary address
2762 * @param addrlen length of addr
2763 * @return NULL if no such entry exists
2765 static struct ForeignAddressList *
2766 find_peer_address(struct NeighbourMapEntry *neighbour,
2768 struct Session *session,
2772 struct ReadyList *head;
2773 struct ForeignAddressList *pos;
2775 head = neighbour->plugins;
2776 while (head != NULL)
2778 if (0 == strcmp (tname, head->plugin->short_name))
2784 pos = head->addresses;
2785 while ( (pos != NULL) &&
2786 ( (pos->addrlen != addrlen) ||
2787 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2789 if ( (session != NULL) &&
2790 (pos->session == session) )
2794 if ( (session != NULL) && (pos != NULL) )
2795 pos->session = session; /* learn it! */
2801 * Get the peer address struct for the given neighbour and
2802 * address. If it doesn't yet exist, create it.
2804 * @param neighbour which peer we care about
2805 * @param tname name of the transport plugin
2806 * @param session session of the plugin, or NULL for none
2807 * @param addr binary address
2808 * @param addrlen length of addr
2809 * @return NULL if we do not have a transport plugin for 'tname'
2811 static struct ForeignAddressList *
2812 add_peer_address (struct NeighbourMapEntry *neighbour,
2814 struct Session *session,
2818 struct ReadyList *head;
2819 struct ForeignAddressList *ret;
2822 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2825 head = neighbour->plugins;
2827 while (head != NULL)
2829 if (0 == strcmp (tname, head->plugin->short_name))
2835 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2836 ret->session = session;
2837 if ((addrlen > 0) && (addr != NULL))
2839 ret->addr = (const char*) &ret[1];
2840 memcpy (&ret[1], addr, addrlen);
2847 ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
2848 for (c=0; c<available_ressources; c++)
2850 struct ATS_ressource_entry *r = ret->ressources;
2852 r[c].atis_index = ressources[c].atis_index;
2853 if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
2855 r[c].c = ressources[c].c_unix;
2857 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
2859 r[c].c = ressources[c].c_udp;
2861 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
2863 r[c].c = ressources[c].c_tcp;
2865 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
2867 r[c].c = ressources[c].c_http;
2869 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
2871 r[c].c = ressources[c].c_https;
2873 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
2875 r[c].c = ressources[c].c_wlan;
2879 r[c].c = ressources[c].c_default;
2880 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2881 "Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!\n",
2882 GNUNET_i2s(&neighbour->id),
2883 neighbour->plugins->plugin->short_name);
2887 ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
2888 ret->addrlen = addrlen;
2889 ret->expires = GNUNET_TIME_relative_to_absolute
2890 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2891 ret->latency = GNUNET_TIME_relative_get_forever();
2893 ret->timeout = GNUNET_TIME_relative_to_absolute
2894 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2895 ret->ready_list = head;
2896 ret->next = head->addresses;
2897 head->addresses = ret;
2903 * Closure for 'add_validated_address'.
2905 struct AddValidatedAddressContext
2908 * Entry that has been validated.
2910 const struct ValidationEntry *ve;
2913 * Flag set after we have added the address so
2914 * that we terminate the iteration next time.
2921 * Callback function used to fill a buffer of max bytes with a list of
2922 * addresses in the format used by HELLOs. Should use
2923 * "GNUNET_HELLO_add_address" as a helper function.
2925 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2926 * @param max maximum number of bytes that can be written to buf
2927 * @param buf where to write the address information
2928 * @return number of bytes written, 0 to signal the
2929 * end of the iteration.
2932 add_validated_address (void *cls,
2933 size_t max, void *buf)
2935 struct AddValidatedAddressContext *avac = cls;
2936 const struct ValidationEntry *ve = avac->ve;
2938 if (GNUNET_YES == avac->done)
2940 avac->done = GNUNET_YES;
2941 return GNUNET_HELLO_add_address (ve->transport_name,
2942 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2952 * Closure for 'check_address_exists'.
2954 struct CheckAddressExistsClosure
2957 * Address to check for.
2962 * Name of the transport.
2969 struct Session *session;
2972 * Set to GNUNET_YES if the address exists.
2985 * Iterator over hash map entries. Checks if the given
2986 * validation entry is for the same address as what is given
2989 * @param cls the 'struct CheckAddressExistsClosure*'
2990 * @param key current key code (ignored)
2991 * @param value value in the hash map ('struct ValidationEntry')
2992 * @return GNUNET_YES if we should continue to
2993 * iterate (mismatch), GNUNET_NO if not (entry matched)
2996 check_address_exists (void *cls,
2997 const GNUNET_HashCode * key,
3000 struct CheckAddressExistsClosure *caec = cls;
3001 struct ValidationEntry *ve = value;
3003 if ( (0 == strcmp (caec->tname,
3004 ve->transport_name)) &&
3005 (caec->addrlen == ve->addrlen) &&
3006 (0 == memcmp (caec->addr,
3010 caec->exists = GNUNET_YES;
3013 if ( (ve->session != NULL) &&
3014 (caec->session == ve->session) )
3016 caec->exists = GNUNET_YES;
3024 neighbour_timeout_task (void *cls,
3025 const struct GNUNET_SCHEDULER_TaskContext *tc)
3027 struct NeighbourMapEntry *n = cls;
3030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3031 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
3033 GNUNET_STATISTICS_update (stats,
3034 gettext_noop ("# disconnects due to timeout"),
3037 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3038 disconnect_neighbour (n, GNUNET_NO);
3043 * Schedule the job that will cause us to send a PING to the
3044 * foreign address to evaluate its validity and latency.
3046 * @param fal address to PING
3049 schedule_next_ping (struct ForeignAddressList *fal);
3053 * Add the given address to the list of foreign addresses
3054 * available for the given peer (check for duplicates).
3056 * @param cls the respective 'struct NeighbourMapEntry' to update
3057 * @param tname name of the transport
3058 * @param expiration expiration time
3059 * @param addr the address
3060 * @param addrlen length of the address
3061 * @return GNUNET_OK (always)
3064 add_to_foreign_address_list (void *cls,
3066 struct GNUNET_TIME_Absolute expiration,
3070 struct NeighbourMapEntry *n = cls;
3071 struct ForeignAddressList *fal;
3074 GNUNET_STATISTICS_update (stats,
3075 gettext_noop ("# valid peer addresses returned by PEERINFO"),
3079 fal = find_peer_address (n, tname, NULL, addr, addrlen);
3082 #if DEBUG_TRANSPORT_HELLO
3083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3084 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
3085 a2s (tname, addr, addrlen),
3087 GNUNET_i2s (&n->id),
3088 expiration.abs_value);
3090 fal = add_peer_address (n, tname, NULL, addr, addrlen);
3093 GNUNET_STATISTICS_update (stats,
3094 gettext_noop ("# previously validated addresses lacking transport"),
3100 fal->expires = GNUNET_TIME_absolute_max (expiration,
3102 schedule_next_ping (fal);
3108 fal->expires = GNUNET_TIME_absolute_max (expiration,
3114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115 "Failed to add new address for `%4s'\n",
3116 GNUNET_i2s (&n->id));
3120 if (fal->validated == GNUNET_NO)
3122 fal->validated = GNUNET_YES;
3123 GNUNET_STATISTICS_update (stats,
3124 gettext_noop ("# peer addresses considered valid"),
3128 if (try == GNUNET_YES)
3131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3132 "Have new addresses, will try to trigger transmissions.\n");
3134 try_transmission_to_peer (n);
3141 * Add addresses in validated HELLO "h" to the set of addresses
3142 * we have for this peer.
3144 * @param cls closure ('struct NeighbourMapEntry*')
3145 * @param peer id of the peer, NULL for last call
3146 * @param h hello message for the peer (can be NULL)
3147 * @param err_msg NULL if successful, otherwise contains error message
3150 add_hello_for_peer (void *cls,
3151 const struct GNUNET_PeerIdentity *peer,
3152 const struct GNUNET_HELLO_Message *h,
3153 const char *err_msg)
3155 struct NeighbourMapEntry *n = cls;
3157 if (err_msg != NULL)
3160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161 _("Error in communication with PEERINFO service: %s\n"),
3168 GNUNET_STATISTICS_update (stats,
3169 gettext_noop ("# outstanding peerinfo iterate requests"),
3176 return; /* no HELLO available */
3178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3179 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
3183 if (GNUNET_YES != n->public_key_valid)
3185 GNUNET_HELLO_get_key (h, &n->publicKey);
3186 n->public_key_valid = GNUNET_YES;
3188 GNUNET_HELLO_iterate_addresses (h,
3190 &add_to_foreign_address_list,
3196 * Create a fresh entry in our neighbour list for the given peer.
3197 * Will try to transmit our current HELLO to the new neighbour.
3198 * Do not call this function directly, use 'setup_peer_check_blacklist.
3200 * @param peer the peer for which we create the entry
3201 * @param do_hello should we schedule transmitting a HELLO
3202 * @return the new neighbour list entry
3204 static struct NeighbourMapEntry *
3205 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
3208 struct NeighbourMapEntry *n;
3209 struct TransportPlugin *tp;
3210 struct ReadyList *rl;
3212 GNUNET_assert (0 != memcmp (peer,
3214 sizeof (struct GNUNET_PeerIdentity)));
3216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217 "Setting up state for neighbour `%4s'\n",
3220 GNUNET_STATISTICS_update (stats,
3221 gettext_noop ("# active neighbours"),
3224 n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
3227 GNUNET_TIME_relative_to_absolute
3228 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3229 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
3230 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
3231 MAX_BANDWIDTH_CARRY_S);
3235 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
3237 rl = GNUNET_malloc (sizeof (struct ReadyList));
3239 rl->next = n->plugins;
3242 rl->addresses = NULL;
3246 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
3248 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3249 &neighbour_timeout_task, n);
3250 GNUNET_CONTAINER_multihashmap_put (neighbours,
3253 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3256 GNUNET_STATISTICS_update (stats,
3257 gettext_noop ("# peerinfo new neighbor iterate requests"),
3260 GNUNET_STATISTICS_update (stats,
3261 gettext_noop ("# outstanding peerinfo iterate requests"),
3264 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
3265 GNUNET_TIME_UNIT_FOREVER_REL,
3266 &add_hello_for_peer, n);
3268 GNUNET_STATISTICS_update (stats,
3269 gettext_noop ("# HELLO's sent to new neighbors"),
3272 if (NULL != our_hello)
3273 transmit_to_peer (NULL, NULL, 0,
3274 HELLO_ADDRESS_EXPIRATION,
3275 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
3283 * Function called after we have checked if communicating
3284 * with a given peer is acceptable.
3286 * @param cls closure
3287 * @param n NULL if communication is not acceptable
3289 typedef void (*SetupContinuation)(void *cls,
3290 struct NeighbourMapEntry *n);
3294 * Information kept for each client registered to perform
3300 * This is a linked list.
3302 struct Blacklisters *next;
3305 * This is a linked list.
3307 struct Blacklisters *prev;
3310 * Client responsible for this entry.
3312 struct GNUNET_SERVER_Client *client;
3315 * Blacklist check that we're currently performing.
3317 struct BlacklistCheck *bc;
3323 * Head of DLL of blacklisting clients.
3325 static struct Blacklisters *bl_head;
3328 * Tail of DLL of blacklisting clients.
3330 static struct Blacklisters *bl_tail;
3334 * Context we use when performing a blacklist check.
3336 struct BlacklistCheck
3340 * This is a linked list.
3342 struct BlacklistCheck *next;
3345 * This is a linked list.
3347 struct BlacklistCheck *prev;
3350 * Peer being checked.
3352 struct GNUNET_PeerIdentity peer;
3355 * Option for setup neighbour afterwards.
3360 * Continuation to call with the result.
3362 SetupContinuation cont;
3370 * Current transmission request handle for this client, or NULL if no
3371 * request is pending.
3373 struct GNUNET_CONNECTION_TransmitHandle *th;
3376 * Our current position in the blacklisters list.
3378 struct Blacklisters *bl_pos;
3381 * Current task performing the check.
3383 GNUNET_SCHEDULER_TaskIdentifier task;
3388 * Head of DLL of active blacklisting queries.
3390 static struct BlacklistCheck *bc_head;
3393 * Tail of DLL of active blacklisting queries.
3395 static struct BlacklistCheck *bc_tail;
3399 * Perform next action in the blacklist check.
3401 * @param cls the 'struct BlacklistCheck*'
3405 do_blacklist_check (void *cls,
3406 const struct GNUNET_SCHEDULER_TaskContext *tc);
3409 * Transmit blacklist query to the client.
3411 * @param cls the 'struct BlacklistCheck'
3412 * @param size number of bytes allowed
3413 * @param buf where to copy the message
3414 * @return number of bytes copied to buf
3417 transmit_blacklist_message (void *cls,
3421 struct BlacklistCheck *bc = cls;
3422 struct Blacklisters *bl;
3423 struct BlacklistMessage bm;
3428 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3429 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3431 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3432 "Failed to send blacklist test for peer `%s' to client\n",
3433 GNUNET_i2s (&bc->peer));
3437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3438 "Sending blacklist test for peer `%s' to client\n",
3439 GNUNET_i2s (&bc->peer));
3442 bm.header.size = htons (sizeof (struct BlacklistMessage));
3443 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3444 bm.is_allowed = htonl (0);
3446 memcpy (buf, &bm, sizeof (bm));
3447 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3453 * Perform next action in the blacklist check.
3455 * @param cls the 'struct BlacklistCheck*'
3459 do_blacklist_check (void *cls,
3460 const struct GNUNET_SCHEDULER_TaskContext *tc)
3462 struct BlacklistCheck *bc = cls;
3463 struct Blacklisters *bl;
3465 bc->task = GNUNET_SCHEDULER_NO_TASK;
3470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3471 "No blacklist clients active, will now setup neighbour record for peer `%s'\n",
3472 GNUNET_i2s (&bc->peer));
3474 bc->cont (bc->cont_cls,
3475 setup_new_neighbour (&bc->peer, bc->do_hello));
3482 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3483 sizeof (struct BlacklistMessage),
3484 GNUNET_TIME_UNIT_FOREVER_REL,
3485 &transmit_blacklist_message,
3492 * Obtain a 'struct NeighbourMapEntry' for the given peer. If such an entry
3493 * does not yet exist, check the blacklist. If the blacklist says creating
3494 * one is acceptable, create one and call the continuation; otherwise
3495 * call the continuation with NULL.
3497 * @param peer peer to setup or look up a struct NeighbourMapEntry for
3498 * @param do_hello should we also schedule sending our HELLO to the peer
3499 * if this is a new record
3500 * @param cont function to call with the 'struct NeigbhbourList*'
3501 * @param cont_cls closure for cont
3504 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3506 SetupContinuation cont,
3509 struct NeighbourMapEntry *n;
3510 struct BlacklistCheck *bc;
3512 n = find_neighbour(peer);
3516 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3517 "Neighbour record exists for peer `%s'\n",
3524 if (bl_head == NULL)
3527 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3529 setup_new_neighbour(peer, do_hello);
3532 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3533 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3535 bc->do_hello = do_hello;
3537 bc->cont_cls = cont_cls;
3538 bc->bl_pos = bl_head;
3539 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3545 * Function called with the result of querying a new blacklister about
3546 * it being allowed (or not) to continue to talk to an existing neighbour.
3548 * @param cls the original 'struct NeighbourMapEntry'
3549 * @param n NULL if we need to disconnect
3552 confirm_or_drop_neighbour (void *cls,
3553 struct NeighbourMapEntry *n)
3555 struct NeighbourMapEntry * orig = cls;
3560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3561 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3562 "confirm_or_drop_neighboUr");
3564 GNUNET_STATISTICS_update (stats,
3565 gettext_noop ("# disconnects due to blacklist"),
3568 disconnect_neighbour (orig, GNUNET_NO);
3573 struct TestConnectionContext
3577 struct Blacklisters *bl;
3582 test_connection_ok (void *cls,
3583 const GNUNET_HashCode *key,
3586 struct TestConnectionContext *tcc = cls;
3587 struct NeighbourMapEntry *n = value;
3588 struct BlacklistCheck *bc;
3591 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3592 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3594 bc->do_hello = GNUNET_NO;
3595 bc->cont = &confirm_or_drop_neighbour;
3597 bc->bl_pos = tcc->bl;
3598 if (GNUNET_YES == tcc->first)
3600 /* all would wait for the same client, no need to
3601 create more than just the first task right now */
3602 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3604 tcc->first = GNUNET_NO;
3611 * Handle a request to start a blacklist.
3613 * @param cls closure (always NULL)
3614 * @param client identification of the client
3615 * @param message the actual message
3618 handle_blacklist_init (void *cls,
3619 struct GNUNET_SERVER_Client *client,
3620 const struct GNUNET_MessageHeader *message)
3622 struct Blacklisters *bl;
3623 struct TestConnectionContext tcc;
3628 if (bl->client == client)
3631 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3636 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3637 bl->client = client;
3638 GNUNET_SERVER_client_keep (client);
3639 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3640 /* confirm that all existing connections are OK! */
3642 tcc.first = GNUNET_YES;
3643 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
3644 &test_connection_ok,
3650 * Handle a request to blacklist a peer.
3652 * @param cls closure (always NULL)
3653 * @param client identification of the client
3654 * @param message the actual message
3657 handle_blacklist_reply (void *cls,
3658 struct GNUNET_SERVER_Client *client,
3659 const struct GNUNET_MessageHeader *message)
3661 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3662 struct Blacklisters *bl;
3663 struct BlacklistCheck *bc;
3666 while ( (bl != NULL) &&
3667 (bl->client != client) )
3672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3673 "Blacklist client disconnected\n");
3675 /* FIXME: other error handling here!? */
3676 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3681 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3685 "Blacklist check failed, peer not allowed\n");
3687 bc->cont (bc->cont_cls, NULL);
3688 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3695 "Blacklist check succeeded, continuing with checks\n");
3697 bc->bl_pos = bc->bl_pos->next;
3698 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3701 /* check if any other bc's are waiting for this blacklister */
3705 if ( (bc->bl_pos == bl) &&
3706 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3707 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3715 * Send periodic PING messages to a given foreign address.
3717 * @param cls our 'struct PeriodicValidationContext*'
3718 * @param tc task context
3721 send_periodic_ping (void *cls,
3722 const struct GNUNET_SCHEDULER_TaskContext *tc)
3724 struct ForeignAddressList *peer_address = cls;
3725 struct TransportPlugin *tp;
3726 struct ValidationEntry *va;
3727 struct NeighbourMapEntry *neighbour;
3728 struct TransportPingMessage ping;
3729 struct CheckAddressExistsClosure caec;
3731 uint16_t hello_size;
3735 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3736 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3738 GNUNET_assert (peer_address != NULL);
3739 tp = peer_address->ready_list->plugin;
3740 neighbour = peer_address->ready_list->neighbour;
3741 if (GNUNET_YES != neighbour->public_key_valid)
3743 /* no public key yet, try again later */
3744 schedule_next_ping (peer_address);
3747 caec.addr = peer_address->addr;
3748 caec.addrlen = peer_address->addrlen;
3749 caec.tname = tp->short_name;
3750 caec.session = peer_address->session;
3751 caec.exists = GNUNET_NO;
3753 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3754 &check_address_exists,
3756 if (caec.exists == GNUNET_YES)
3758 /* During validation attempts we will likely trigger the other
3759 peer trying to validate our address which in turn will cause
3760 it to send us its HELLO, so we expect to hit this case rather
3761 frequently. Only print something if we are very verbose. */
3762 #if DEBUG_TRANSPORT > 1
3763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3764 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3765 (peer_address->addr != NULL)
3766 ? a2s (tp->short_name,
3768 peer_address->addrlen)
3771 GNUNET_i2s (&neighbour->id));
3773 schedule_next_ping (peer_address);
3776 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3777 va->transport_name = GNUNET_strdup (tp->short_name);
3778 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3780 va->send_time = GNUNET_TIME_absolute_get();
3781 va->session = peer_address->session;
3782 if (peer_address->addr != NULL)
3784 va->addr = (const void*) &va[1];
3785 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3786 va->addrlen = peer_address->addrlen;
3788 memcpy(&va->publicKey,
3789 &neighbour->publicKey,
3790 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3792 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3793 &timeout_hello_validation,
3795 GNUNET_CONTAINER_multihashmap_put (validation_map,
3796 &neighbour->id.hashPubKey,
3798 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3800 if (peer_address->validated != GNUNET_YES)
3801 hello_size = GNUNET_HELLO_size(our_hello);
3805 tsize = sizeof(struct TransportPingMessage) + hello_size;
3807 if (peer_address->addr != NULL)
3809 slen = strlen (tp->short_name) + 1;
3810 tsize += slen + peer_address->addrlen;
3814 slen = 0; /* make gcc happy */
3816 message_buf = GNUNET_malloc(tsize);
3817 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3818 ping.challenge = htonl(va->challenge);
3819 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3820 if (peer_address->validated != GNUNET_YES)
3822 memcpy(message_buf, our_hello, hello_size);
3825 if (peer_address->addr != NULL)
3827 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3828 peer_address->addrlen +
3830 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3833 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3835 peer_address->addrlen);
3839 ping.header.size = htons(sizeof(struct TransportPingMessage));
3842 memcpy(&message_buf[hello_size],
3844 sizeof(struct TransportPingMessage));
3846 #if DEBUG_TRANSPORT_REVALIDATION
3847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3849 (peer_address->addr != NULL)
3850 ? a2s (peer_address->plugin->short_name,
3852 peer_address->addrlen)
3855 GNUNET_i2s (&neighbour->id),
3856 "HELLO", hello_size,
3859 if (peer_address->validated != GNUNET_YES)
3860 GNUNET_STATISTICS_update (stats,
3861 gettext_noop ("# PING with HELLO messages sent"),
3865 GNUNET_STATISTICS_update (stats,
3866 gettext_noop ("# PING without HELLO messages sent"),
3869 GNUNET_STATISTICS_update (stats,
3870 gettext_noop ("# PING messages sent for re-validation"),
3873 transmit_to_peer (NULL, peer_address,
3874 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3875 HELLO_VERIFICATION_TIMEOUT,
3877 GNUNET_YES, neighbour);
3878 GNUNET_free (message_buf);
3879 schedule_next_ping (peer_address);
3884 * Schedule the job that will cause us to send a PING to the
3885 * foreign address to evaluate its validity and latency.
3887 * @param fal address to PING
3890 schedule_next_ping (struct ForeignAddressList *fal)
3892 struct GNUNET_TIME_Relative delay;
3894 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3896 GNUNET_SCHEDULER_cancel(fal->revalidate_task);
3897 fal->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3899 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3900 delay.rel_value /= 2; /* do before expiration */
3901 delay = GNUNET_TIME_relative_min (delay,
3902 LATENCY_EVALUATION_MAX_DELAY);
3903 if (GNUNET_YES != fal->estimated)
3905 delay = GNUNET_TIME_UNIT_ZERO;
3906 fal->estimated = GNUNET_YES;
3909 if (GNUNET_YES == fal->connected)
3911 delay = GNUNET_TIME_relative_min (delay,
3912 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3914 /* FIXME: also adjust delay based on how close the last
3915 observed latency is to the latency of the best alternative */
3916 /* bound how fast we can go */
3917 delay = GNUNET_TIME_relative_max (delay,
3918 GNUNET_TIME_UNIT_SECONDS);
3919 /* randomize a bit (to avoid doing all at the same time) */
3920 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3922 GNUNET_assert (fal->revalidate_task == GNUNET_SCHEDULER_NO_TASK);
3923 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3924 &send_periodic_ping,
3932 * Function that will be called if we receive some payload
3933 * from another peer.
3935 * @param message the payload
3936 * @param n peer who claimed to be the sender
3939 handle_payload_message (const struct GNUNET_MessageHeader *message,
3940 struct NeighbourMapEntry *n)
3942 struct InboundMessage *im;
3943 struct TransportClient *cpos;
3946 msize = ntohs (message->size);
3947 if (n->received_pong == GNUNET_NO)
3950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3951 "Received message of type %u and size %u from `%4s', but no pong yet!\n",
3952 ntohs (message->type),
3953 ntohs (message->size),
3954 GNUNET_i2s (&n->id));
3956 GNUNET_free_non_null (n->pre_connect_message_buffer);
3957 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3958 memcpy (n->pre_connect_message_buffer, message, msize);
3963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3964 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3965 ntohs (message->type),
3966 ntohs (message->size),
3967 GNUNET_i2s (&n->id));
3969 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3972 n->quota_violation_count++;
3974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3975 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3976 n->in_tracker.available_bytes_per_s__,
3977 n->quota_violation_count);
3979 /* Discount 32k per violation */
3980 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3985 if (n->quota_violation_count > 0)
3987 /* try to add 32k back */
3988 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3990 n->quota_violation_count--;
3993 GNUNET_STATISTICS_update (stats,
3994 gettext_noop ("# payload received from other peers"),
3997 /* transmit message to all clients */
3998 uint32_t ats_count = 2;
3999 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
4000 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4003 im = GNUNET_malloc (size);
4004 im->header.size = htons (size);
4005 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
4007 im->ats_count = htonl(ats_count);
4008 /* Setting ATS data */
4009 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4010 (&(im->ats))[0].value = htonl (n->distance);
4011 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4012 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
4013 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4014 (&(im->ats))[ats_count].value = htonl (0);
4016 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
4018 while (cpos != NULL)
4020 transmit_to_client (cpos, &im->header, GNUNET_YES);
4028 * Iterator over hash map entries. Checks if the given validation
4029 * entry is for the same challenge as what is given in the PONG.
4031 * @param cls the 'struct TransportPongMessage*'
4032 * @param key peer identity
4033 * @param value value in the hash map ('struct ValidationEntry')
4034 * @return GNUNET_YES if we should continue to
4035 * iterate (mismatch), GNUNET_NO if not (entry matched)
4038 check_pending_validation (void *cls,
4039 const GNUNET_HashCode * key,
4042 const struct TransportPongMessage *pong = cls;
4043 struct ValidationEntry *ve = value;
4044 struct AddValidatedAddressContext avac;
4045 unsigned int challenge = ntohl(pong->challenge);
4046 struct GNUNET_HELLO_Message *hello;
4047 struct GNUNET_PeerIdentity target;
4048 struct NeighbourMapEntry *n;
4049 struct ForeignAddressList *fal;
4050 struct OwnAddressList *oal;
4051 struct TransportPlugin *tp;
4052 struct GNUNET_MessageHeader *prem;
4058 ps = ntohs (pong->header.size);
4059 if (ps < sizeof (struct TransportPongMessage))
4061 GNUNET_break_op (0);
4064 addr = (const char*) &pong[1];
4065 slen = strlen (ve->transport_name) + 1;
4066 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
4067 (ve->challenge != challenge) ||
4068 (addr[slen-1] != '\0') ||
4069 (0 != strcmp (addr, ve->transport_name)) ||
4070 (ntohl (pong->purpose.size)
4071 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4073 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4074 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
4079 alen = ps - sizeof (struct TransportPongMessage) - slen;
4080 switch (ntohl (pong->purpose.purpose))
4082 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
4083 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
4084 (0 != memcmp (&addr[slen],
4088 return GNUNET_YES; /* different entry, keep trying! */
4090 if (0 != memcmp (&pong->pid,
4092 sizeof (struct GNUNET_PeerIdentity)))
4094 GNUNET_break_op (0);
4098 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
4103 GNUNET_break_op (0);
4108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4109 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
4111 a2s (ve->transport_name,
4112 (const struct sockaddr *) ve->addr,
4114 ve->transport_name);
4117 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
4118 if (0 != memcmp (&pong->pid,
4120 sizeof (struct GNUNET_PeerIdentity)))
4124 GNUNET_asprintf(&peer, "%s",GNUNET_i2s (&pong->pid));
4126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4127 "Received PONG for different identity: I am `%s', PONG identity: `%s'\n",
4128 GNUNET_i2s (&my_identity),
4134 if (ve->addrlen != 0)
4136 /* must have been for a different validation entry */
4139 tp = find_transport (ve->transport_name);
4145 oal = tp->addresses;
4148 if ( (oal->addrlen == alen) &&
4149 (0 == memcmp (&oal[1],
4157 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4158 _("Not accepting PONG from `%s' with address `%s' since I cannot confirm using this address.\n"),
4159 GNUNET_i2s (&pong->pid),
4160 a2s (ve->transport_name,
4163 /* FIXME: since the sender of the PONG currently uses the
4164 wrong address (see FIMXE there!), we cannot run a
4165 proper check here... */
4171 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
4176 GNUNET_break_op (0);
4181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4182 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
4184 a2s (ve->transport_name,
4187 ve->transport_name);
4191 GNUNET_break_op (0);
4194 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
4196 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4197 _("Received expired signature. Check system time.\n"));
4200 GNUNET_STATISTICS_update (stats,
4201 gettext_noop ("# address validation successes"),
4204 /* create the updated HELLO */
4205 GNUNET_CRYPTO_hash (&ve->publicKey,
4206 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4207 &target.hashPubKey);
4208 if (ve->addr != NULL)
4210 avac.done = GNUNET_NO;
4212 hello = GNUNET_HELLO_create (&ve->publicKey,
4213 &add_validated_address,
4215 GNUNET_PEERINFO_add_peer (peerinfo,
4217 GNUNET_free (hello);
4219 n = find_neighbour (&target);
4222 n->publicKey = ve->publicKey;
4223 n->public_key_valid = GNUNET_YES;
4224 fal = add_peer_address (n,
4229 GNUNET_assert (fal != NULL);
4230 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
4231 fal->validated = GNUNET_YES;
4232 mark_address_connected (fal);
4233 GNUNET_STATISTICS_update (stats,
4234 gettext_noop ("# peer addresses considered valid"),
4237 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
4238 update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4240 schedule_next_ping (fal);
4241 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
4242 n->latency = fal->latency;
4244 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
4246 n->distance = fal->distance;
4247 if (GNUNET_NO == n->received_pong)
4249 n->received_pong = GNUNET_YES;
4250 notify_clients_connect (&target, n->latency, n->distance);
4251 if (NULL != (prem = n->pre_connect_message_buffer))
4253 n->pre_connect_message_buffer = NULL;
4254 handle_payload_message (prem, n);
4258 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4260 GNUNET_SCHEDULER_cancel (n->retry_task);
4261 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4262 try_transmission_to_peer (n);
4266 /* clean up validation entry */
4267 GNUNET_assert (GNUNET_YES ==
4268 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4271 abort_validation (NULL, NULL, ve);
4277 * Function that will be called if we receive a validation
4278 * of an address challenge that we transmitted to another
4279 * peer. Note that the validation should only be considered
4280 * acceptable if the challenge matches AND if the sender
4281 * address is at least a plausible address for this peer
4282 * (otherwise we may be seeing a MiM attack).
4284 * @param cls closure
4285 * @param message the pong message
4286 * @param peer who responded to our challenge
4287 * @param sender_address string describing our sender address (as observed
4288 * by the other peer in binary format)
4289 * @param sender_address_len number of bytes in 'sender_address'
4292 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
4293 const struct GNUNET_PeerIdentity *peer,
4294 const char *sender_address,
4295 size_t sender_address_len)
4297 if (0 == memcmp (peer,
4299 sizeof (struct GNUNET_PeerIdentity)))
4301 /* PONG send to self, ignore */
4302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4303 "Receiving `%s' message from myself\n",
4307 #if DEBUG_TRANSPORT > 1
4308 /* we get tons of these that just get discarded, only log
4309 if we are quite verbose */
4310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4311 "Receiving `%s' message from `%4s'.\n", "PONG",
4314 GNUNET_STATISTICS_update (stats,
4315 gettext_noop ("# PONG messages received"),
4318 if (GNUNET_SYSERR !=
4319 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
4321 &check_pending_validation,
4324 /* This is *expected* to happen a lot since we send
4325 PONGs to *all* known addresses of the sender of
4326 the PING, so most likely we get multiple PONGs
4327 per PING, and all but the first PONG will end up
4328 here. So really we should not print anything here
4329 unless we want to be very, very verbose... */
4330 #if DEBUG_TRANSPORT > 2
4331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
4344 * Try to validate a neighbour's address by sending him our HELLO and a PING.
4346 * @param cls the 'struct ValidationEntry*'
4347 * @param neighbour neighbour to validate, NULL if validation failed
4350 transmit_hello_and_ping (void *cls,
4351 struct NeighbourMapEntry *neighbour)
4353 struct ValidationEntry *va = cls;
4354 struct ForeignAddressList *peer_address;
4355 struct TransportPingMessage ping;
4356 uint16_t hello_size;
4359 struct GNUNET_PeerIdentity id;
4362 GNUNET_CRYPTO_hash (&va->publicKey,
4363 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4365 if (neighbour == NULL)
4367 /* FIXME: stats... */
4368 GNUNET_break (GNUNET_OK ==
4369 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4372 abort_validation (NULL, NULL, va);
4375 neighbour->publicKey = va->publicKey;
4376 neighbour->public_key_valid = GNUNET_YES;
4377 peer_address = add_peer_address (neighbour,
4378 va->transport_name, NULL,
4379 (const void*) &va[1],
4381 if (peer_address == NULL)
4383 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4384 "Failed to add peer `%4s' for plugin `%s'\n",
4385 GNUNET_i2s (&neighbour->id),
4386 va->transport_name);
4387 GNUNET_break (GNUNET_OK ==
4388 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4391 abort_validation (NULL, NULL, va);
4394 if (NULL == our_hello)
4395 refresh_hello_task (NULL, NULL);
4396 hello_size = GNUNET_HELLO_size(our_hello);
4397 slen = strlen(va->transport_name) + 1;
4398 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
4399 message_buf = GNUNET_malloc(tsize);
4400 ping.challenge = htonl(va->challenge);
4401 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
4402 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4403 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4404 memcpy(message_buf, our_hello, hello_size);
4405 memcpy(&message_buf[hello_size],
4407 sizeof(struct TransportPingMessage));
4408 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4411 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4416 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
4419 : a2s (va->transport_name,
4420 (const void*) &va[1], va->addrlen),
4422 GNUNET_i2s (&neighbour->id),
4423 "HELLO", hello_size,
4424 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
4427 GNUNET_STATISTICS_update (stats,
4428 gettext_noop ("# PING messages sent for initial validation"),
4431 transmit_to_peer (NULL, peer_address,
4432 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4433 HELLO_VERIFICATION_TIMEOUT,
4435 GNUNET_YES, neighbour);
4436 GNUNET_free (message_buf);
4441 * Check if the given address is already being validated; if not,
4442 * append the given address to the list of entries that are being be
4443 * validated and initiate validation.
4445 * @param cls closure ('struct CheckHelloValidatedContext *')
4446 * @param tname name of the transport
4447 * @param expiration expiration time
4448 * @param addr the address
4449 * @param addrlen length of the address
4450 * @return GNUNET_OK (always)
4453 run_validation (void *cls,
4455 struct GNUNET_TIME_Absolute expiration,
4459 struct CheckHelloValidatedContext *chvc = cls;
4460 struct GNUNET_PeerIdentity id;
4461 struct TransportPlugin *tp;
4462 struct ValidationEntry *va;
4463 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4464 struct CheckAddressExistsClosure caec;
4465 struct OwnAddressList *oal;
4467 GNUNET_assert (addr != NULL);
4469 GNUNET_STATISTICS_update (stats,
4470 gettext_noop ("# peer addresses scheduled for validation"),
4473 tp = find_transport (tname);
4476 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
4477 GNUNET_ERROR_TYPE_BULK,
4479 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4481 GNUNET_STATISTICS_update (stats,
4482 gettext_noop ("# peer addresses not validated (plugin not available)"),
4487 /* check if this is one of our own addresses */
4488 oal = tp->addresses;
4491 if ( (oal->addrlen == addrlen) &&
4492 (0 == memcmp (&oal[1],
4496 /* not plausible, this address is equivalent to our own address! */
4497 GNUNET_STATISTICS_update (stats,
4498 gettext_noop ("# peer addresses not validated (loopback)"),
4505 GNUNET_HELLO_get_key (chvc->hello, &pk);
4506 GNUNET_CRYPTO_hash (&pk,
4508 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4511 if (is_blacklisted(&id, tp))
4514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4515 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4523 caec.addrlen = addrlen;
4524 caec.session = NULL;
4526 caec.exists = GNUNET_NO;
4527 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4528 &check_address_exists,
4530 if (caec.exists == GNUNET_YES)
4532 /* During validation attempts we will likely trigger the other
4533 peer trying to validate our address which in turn will cause
4534 it to send us its HELLO, so we expect to hit this case rather
4535 frequently. Only print something if we are very verbose. */
4536 #if DEBUG_TRANSPORT > 1
4537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4538 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4539 a2s (tname, addr, addrlen),
4543 GNUNET_STATISTICS_update (stats,
4544 gettext_noop ("# peer addresses not validated (in progress)"),
4549 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4552 va->transport_name = GNUNET_strdup (tname);
4553 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4555 va->send_time = GNUNET_TIME_absolute_get();
4556 va->addr = (const void*) &va[1];
4557 memcpy (&va[1], addr, addrlen);
4558 va->addrlen = addrlen;
4559 GNUNET_HELLO_get_key (chvc->hello,
4561 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4562 &timeout_hello_validation,
4564 GNUNET_CONTAINER_multihashmap_put (validation_map,
4567 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4568 setup_peer_check_blacklist (&id, GNUNET_NO,
4569 &transmit_hello_and_ping,
4576 * Check if addresses in validated hello "h" overlap with
4577 * those in "chvc->hello" and validate the rest.
4579 * @param cls closure
4580 * @param peer id of the peer, NULL for last call
4581 * @param h hello message for the peer (can be NULL)
4582 * @param err_msg NULL if successful, otherwise contains error message
4585 check_hello_validated (void *cls,
4586 const struct GNUNET_PeerIdentity *peer,
4587 const struct GNUNET_HELLO_Message *h,
4588 const char *err_msg)
4590 struct CheckHelloValidatedContext *chvc = cls;
4591 struct GNUNET_HELLO_Message *plain_hello;
4592 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4593 struct GNUNET_PeerIdentity target;
4594 struct NeighbourMapEntry *n;
4596 if (err_msg != NULL)
4599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4600 _("Error in communication with PEERINFO service: %s\n"),
4608 GNUNET_STATISTICS_update (stats,
4609 gettext_noop ("# outstanding peerinfo iterate requests"),
4613 if (GNUNET_NO == chvc->hello_known)
4615 /* notify PEERINFO about the peer now, so that we at least
4616 have the public key if some other component needs it */
4617 GNUNET_HELLO_get_key (chvc->hello, &pk);
4618 GNUNET_CRYPTO_hash (&pk,
4619 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4620 &target.hashPubKey);
4621 plain_hello = GNUNET_HELLO_create (&pk,
4624 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4625 GNUNET_free (plain_hello);
4626 #if DEBUG_TRANSPORT_HELLO
4627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4628 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4630 GNUNET_i2s (&target));
4632 GNUNET_STATISTICS_update (stats,
4633 gettext_noop ("# new HELLOs requiring full validation"),
4636 GNUNET_HELLO_iterate_addresses (chvc->hello,
4643 GNUNET_STATISTICS_update (stats,
4644 gettext_noop ("# duplicate HELLO (peer known)"),
4649 if (chvc->ve_count == 0)
4651 GNUNET_CONTAINER_DLL_remove (chvc_head,
4660 #if DEBUG_TRANSPORT_HELLO
4661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4662 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4666 chvc->hello_known = GNUNET_YES;
4667 n = find_neighbour (peer);
4670 #if DEBUG_TRANSPORT_HELLO
4671 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4672 "Calling hello_iterate_addresses for %s!\n",
4675 GNUNET_HELLO_iterate_addresses (h,
4677 &add_to_foreign_address_list,
4679 try_transmission_to_peer (n);
4683 #if DEBUG_TRANSPORT_HELLO
4684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4685 "No existing neighbor record for %s!\n",
4688 GNUNET_STATISTICS_update (stats,
4689 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4693 GNUNET_STATISTICS_update (stats,
4694 gettext_noop ("# HELLO validations (update case)"),
4697 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4699 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4706 * Process HELLO-message.
4708 * @param plugin transport involved, may be NULL
4709 * @param message the actual message
4710 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4713 process_hello (struct TransportPlugin *plugin,
4714 const struct GNUNET_MessageHeader *message)
4717 struct GNUNET_PeerIdentity target;
4718 const struct GNUNET_HELLO_Message *hello;
4719 struct CheckHelloValidatedContext *chvc;
4720 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4721 struct NeighbourMapEntry *n;
4722 #if DEBUG_TRANSPORT_HELLO > 2
4726 hsize = ntohs (message->size);
4727 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4728 (hsize < sizeof (struct GNUNET_MessageHeader)))
4731 return GNUNET_SYSERR;
4733 GNUNET_STATISTICS_update (stats,
4734 gettext_noop ("# HELLOs received for validation"),
4738 hello = (const struct GNUNET_HELLO_Message *) message;
4739 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4741 #if DEBUG_TRANSPORT_HELLO
4742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4743 "Unable to get public key from `%s' for `%4s'!\n",
4745 GNUNET_i2s (&target));
4747 GNUNET_break_op (0);
4748 return GNUNET_SYSERR;
4750 GNUNET_CRYPTO_hash (&publicKey,
4751 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4752 &target.hashPubKey);
4754 #if DEBUG_TRANSPORT_HELLO
4755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4756 "Received `%s' message for `%4s'\n",
4758 GNUNET_i2s (&target));
4760 if (0 == memcmp (&my_identity,
4762 sizeof (struct GNUNET_PeerIdentity)))
4764 GNUNET_STATISTICS_update (stats,
4765 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4770 n = find_neighbour (&target);
4772 (! n->public_key_valid) )
4774 GNUNET_HELLO_get_key (hello, &n->publicKey);
4775 n->public_key_valid = GNUNET_YES;
4778 /* check if load is too high before doing expensive stuff */
4779 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4781 GNUNET_STATISTICS_update (stats,
4782 gettext_noop ("# HELLOs ignored due to high load"),
4785 #if DEBUG_TRANSPORT_HELLO
4786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4787 "Ignoring `%s' for `%4s', load too high.\n",
4789 GNUNET_i2s (&target));
4796 while (NULL != chvc)
4798 if (GNUNET_HELLO_equals (hello,
4800 GNUNET_TIME_absolute_get ()).abs_value > 0)
4802 #if DEBUG_TRANSPORT_HELLO > 2
4803 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4804 "Received duplicate `%s' message for `%4s'; ignored\n",
4806 GNUNET_i2s (&target));
4808 return GNUNET_OK; /* validation already pending */
4810 if (GNUNET_HELLO_size (hello) == GNUNET_HELLO_size (chvc->hello))
4811 GNUNET_break (0 != memcmp (hello, chvc->hello,
4812 GNUNET_HELLO_size(hello)));
4817 struct NeighbourMapEntry *temp_neighbor = find_neighbour(&target);
4818 if ((NULL != temp_neighbor))
4820 fprintf(stderr, "Already know peer, ignoring hello\n");
4825 #if DEBUG_TRANSPORT_HELLO > 2
4829 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4831 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4834 GNUNET_i2s (&target),
4836 GNUNET_HELLO_size(hello));
4837 GNUNET_free (my_id);
4841 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4843 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4844 memcpy (&chvc[1], hello, hsize);
4845 GNUNET_CONTAINER_DLL_insert (chvc_head,
4848 /* finally, check if HELLO was previously validated
4849 (continuation will then schedule actual validation) */
4850 GNUNET_STATISTICS_update (stats,
4851 gettext_noop ("# peerinfo process hello iterate requests"),
4854 GNUNET_STATISTICS_update (stats,
4855 gettext_noop ("# outstanding peerinfo iterate requests"),
4858 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4860 HELLO_VERIFICATION_TIMEOUT,
4861 &check_hello_validated, chvc);
4867 * The peer specified by the given neighbour has timed-out or a plugin
4868 * has disconnected. We may either need to do nothing (other plugins
4869 * still up), or trigger a full disconnect and clean up. This
4870 * function updates our state and does the necessary notifications.
4871 * Also notifies our clients that the neighbour is now officially
4874 * @param n the neighbour list entry for the peer
4875 * @param check GNUNET_YES to check if ALL addresses for this peer
4876 * are gone, GNUNET_NO to force a disconnect of the peer
4877 * regardless of whether other addresses exist.
4880 disconnect_neighbour (struct NeighbourMapEntry *n, int check)
4882 struct ReadyList *rpos;
4883 struct MessageQueue *mq;
4884 struct ForeignAddressList *peer_addresses;
4885 struct ForeignAddressList *peer_pos;
4887 if (GNUNET_YES == n->in_disconnect)
4889 if (GNUNET_YES == check)
4892 while (NULL != rpos)
4894 peer_addresses = rpos->addresses;
4895 while (peer_addresses != NULL)
4897 /* Do not disconnect if: an address is connected or an inbound address exists */
4898 if ((GNUNET_YES == peer_addresses->connected) || (peer_addresses->addrlen == 0))
4901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4902 "NOT Disconnecting from `%4s', still have live address `%s'!\n",
4903 GNUNET_i2s (&n->id),
4904 a2s (peer_addresses->ready_list->plugin->short_name,
4905 peer_addresses->addr,
4906 peer_addresses->addrlen));
4908 return; /* still connected */
4910 peer_addresses = peer_addresses->next;
4916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4917 "Disconnecting from `%4s'\n",
4918 GNUNET_i2s (&n->id));
4920 n->in_disconnect = GNUNET_YES; /* prevent recursive entry */
4922 /* notify all clients about disconnect */
4923 if (GNUNET_YES == n->received_pong)
4925 n->received_pong = GNUNET_NO;
4926 notify_clients_disconnect (&n->id);
4929 ats_modify_problem_state(ats, ATS_MODIFIED);
4931 /* clean up all plugins, cancel connections and pending transmissions */
4932 while (NULL != (rpos = n->plugins))
4934 n->plugins = rpos->next;
4935 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4936 while (rpos->addresses != NULL)
4938 peer_pos = rpos->addresses;
4939 rpos->addresses = peer_pos->next;
4940 if (peer_pos->connected == GNUNET_YES)
4942 GNUNET_STATISTICS_update (stats,
4943 gettext_noop ("# connected addresses"),
4946 peer_pos->connected = GNUNET_NO;
4948 if (GNUNET_YES == peer_pos->validated)
4949 GNUNET_STATISTICS_update (stats,
4950 gettext_noop ("# peer addresses considered valid"),
4953 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4955 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4956 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4958 GNUNET_free (peer_pos->ressources);
4959 peer_pos->ressources = NULL;
4960 GNUNET_free (peer_pos->quality);
4961 peer_pos->ressources = NULL;
4962 GNUNET_free (peer_pos);
4967 /* free all messages on the queue */
4968 while (NULL != (mq = n->messages_head))
4970 GNUNET_STATISTICS_update (stats,
4971 gettext_noop ("# bytes in message queue for other peers"),
4972 - (int64_t) mq->message_buf_size,
4974 GNUNET_STATISTICS_update (stats,
4975 gettext_noop ("# bytes discarded due to disconnect"),
4976 mq->message_buf_size,
4978 GNUNET_CONTAINER_DLL_remove (n->messages_head,
4981 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4983 sizeof(struct GNUNET_PeerIdentity)));
4987 while (NULL != (mq = n->cont_head))
4990 GNUNET_CONTAINER_DLL_remove (n->cont_head,
4993 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4995 sizeof(struct GNUNET_PeerIdentity)));
4999 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
5001 GNUNET_SCHEDULER_cancel (n->timeout_task);
5002 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
5004 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
5006 GNUNET_SCHEDULER_cancel (n->retry_task);
5007 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
5009 if (n->piter != NULL)
5011 GNUNET_PEERINFO_iterate_cancel (n->piter);
5012 GNUNET_STATISTICS_update (stats,
5013 gettext_noop ("# outstanding peerinfo iterate requests"),
5019 GNUNET_assert (GNUNET_OK ==
5020 GNUNET_CONTAINER_multihashmap_remove (neighbours,
5023 /* finally, free n itself */
5024 GNUNET_STATISTICS_update (stats,
5025 gettext_noop ("# active neighbours"),
5028 GNUNET_free_non_null (n->pre_connect_message_buffer);
5034 * We have received a PING message from someone. Need to send a PONG message
5035 * in response to the peer by any means necessary.
5038 handle_ping (void *cls, const struct GNUNET_MessageHeader *message,
5039 const struct GNUNET_PeerIdentity *peer,
5040 struct Session *session,
5041 const char *sender_address,
5042 uint16_t sender_address_len)
5044 struct TransportPlugin *plugin = cls;
5045 struct SessionHeader *session_header = (struct SessionHeader*) session;
5046 struct TransportPingMessage *ping;
5047 struct TransportPongMessage *pong;
5048 struct NeighbourMapEntry *n;
5049 struct ReadyList *rl;
5050 struct ForeignAddressList *fal;
5051 struct OwnAddressList *oal;
5057 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
5059 GNUNET_break_op (0);
5060 return GNUNET_SYSERR;
5063 ping = (struct TransportPingMessage *) message;
5064 if (0 != memcmp (&ping->target,
5065 plugin->env.my_identity,
5066 sizeof (struct GNUNET_PeerIdentity)))
5069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5070 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
5072 (sender_address != NULL)
5073 ? a2s (plugin->short_name,
5074 (const struct sockaddr *)sender_address,
5077 GNUNET_i2s (&ping->target));
5079 return GNUNET_SYSERR;
5082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5083 "Processing `%s' from `%s'\n",
5085 (sender_address != NULL)
5086 ? a2s (plugin->short_name,
5087 (const struct sockaddr *)sender_address,
5091 GNUNET_STATISTICS_update (stats,
5092 gettext_noop ("# PING messages received"),
5095 addr = (const char*) &ping[1];
5096 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
5097 slen = strlen (plugin->short_name) + 1;
5100 /* peer wants to confirm that we have an outbound connection to him */
5101 if (session == NULL)
5103 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5104 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
5106 return GNUNET_SYSERR;
5108 /* FIXME-urg: the use of 'sender_address' in the code below is doubly-wrong:
5109 1) it is NULL when we need to have a real value
5110 2) it is documented to be the address of the sender (source-IP), where
5111 what we actually want is our LISTEN IP (what we 'bound' to); which we don't even
5114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5115 "Creating PONG indicating that we received a connection at our address `%s' from `%s'.\n",
5116 a2s (plugin->short_name,
5118 sender_address_len),
5121 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5122 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5123 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5124 pong->purpose.size =
5125 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5127 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5128 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
5129 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
5130 pong->challenge = ping->challenge;
5131 pong->addrlen = htonl(sender_address_len + slen);
5134 sizeof(struct GNUNET_PeerIdentity));
5138 if ((sender_address!=NULL) && (sender_address_len > 0))
5139 memcpy (&((char*)&pong[1])[slen],
5141 sender_address_len);
5142 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
5144 /* create / update cached sig */
5146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5147 "Creating PONG signature to indicate active connection.\n");
5149 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5150 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5151 GNUNET_assert (GNUNET_OK ==
5152 GNUNET_CRYPTO_rsa_sign (my_private_key,
5154 &session_header->pong_signature));
5158 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5160 memcpy (&pong->signature,
5161 &session_header->pong_signature,
5162 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5168 /* peer wants to confirm that this is one of our addresses */
5172 plugin->api->check_address (plugin->api->cls,
5176 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5177 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
5178 a2s (plugin->short_name,
5183 oal = plugin->addresses;
5186 if ( (oal->addrlen == alen) &&
5193 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
5194 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
5195 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5196 pong->purpose.size =
5197 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5199 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5200 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
5201 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
5202 pong->challenge = ping->challenge;
5203 pong->addrlen = htonl(alen + slen);
5206 sizeof(struct GNUNET_PeerIdentity));
5207 memcpy (&pong[1], plugin->short_name, slen);
5208 memcpy (&((char*)&pong[1])[slen], addr, alen);
5209 if ( (oal != NULL) &&
5210 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
5212 /* create / update cached sig */
5214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5215 "Creating PONG signature to indicate ownership.\n");
5217 oal->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5218 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5219 GNUNET_assert (GNUNET_OK ==
5220 GNUNET_CRYPTO_rsa_sign (my_private_key,
5222 &oal->pong_signature));
5223 memcpy (&pong->signature,
5224 &oal->pong_signature,
5225 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5227 else if (oal == NULL)
5229 /* not using cache (typically DV-only) */
5230 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
5231 GNUNET_assert (GNUNET_OK ==
5232 GNUNET_CRYPTO_rsa_sign (my_private_key,
5238 /* can used cached version */
5239 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5240 memcpy (&pong->signature,
5241 &oal->pong_signature,
5242 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5245 n = find_neighbour(peer);
5246 GNUNET_assert (n != NULL);
5247 did_pong = GNUNET_NO;
5248 /* first try reliable response transmission */
5252 fal = rl->addresses;
5255 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
5258 ntohs (pong->header.size),
5259 TRANSPORT_PONG_PRIORITY,
5260 HELLO_VERIFICATION_TIMEOUT,
5267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5268 "Transmitted PONG to `%s' via reliable mechanism\n",
5271 GNUNET_STATISTICS_update (stats,
5272 gettext_noop ("# PONGs unicast via reliable transport"),
5278 did_pong = GNUNET_YES;
5283 /* no reliable method found, do multicast */
5284 GNUNET_STATISTICS_update (stats,
5285 gettext_noop ("# PONGs multicast to all available addresses"),
5291 fal = rl->addresses;
5294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5295 "Transmitting PONG to `%s' via unreliable mechanism `%s':%s\n",
5297 a2s (rl->plugin->short_name,
5300 rl->plugin->short_name);
5301 transmit_to_peer(NULL, fal,
5302 TRANSPORT_PONG_PRIORITY,
5303 HELLO_VERIFICATION_TIMEOUT,
5305 ntohs(pong->header.size),
5308 did_pong = GNUNET_YES;
5314 if (GNUNET_YES != did_pong)
5315 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5316 _("Could not send PONG to `%s': no address available\n"),
5323 * Function called by the plugin for each received message. Update
5324 * data volumes, possibly notify plugins about reducing the rate at
5325 * which they read from the socket and generally forward to our
5328 * @param cls the "struct TransportPlugin *" we gave to the plugin
5329 * @param peer (claimed) identity of the other peer
5330 * @param message the message, NULL if we only care about
5331 * learning about the delay until we should receive again
5332 * @param ats_data information for automatic transport selection
5333 * @param ats_count number of elements in ats not including 0-terminator
5334 * @param session identifier used for this session (can be NULL)
5335 * @param sender_address binary address of the sender (if observed)
5336 * @param sender_address_len number of bytes in sender_address
5337 * @return how long in ms the plugin should wait until receiving more data
5338 * (plugins that do not support this, can ignore the return value)
5340 static struct GNUNET_TIME_Relative
5341 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
5342 const struct GNUNET_MessageHeader *message,
5343 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
5345 struct Session *session,
5346 const char *sender_address,
5347 uint16_t sender_address_len)
5349 struct TransportPlugin *plugin = cls;
5350 struct ReadyList *service_context;
5351 struct ForeignAddressList *peer_address;
5353 struct NeighbourMapEntry *n;
5354 struct GNUNET_TIME_Relative ret;
5358 if (0 == memcmp (peer,
5360 sizeof (struct GNUNET_PeerIdentity)))
5362 /* refuse to receive from myself */
5364 return GNUNET_TIME_UNIT_FOREVER_REL;
5366 if (is_blacklisted (peer, plugin))
5367 return GNUNET_TIME_UNIT_FOREVER_REL;
5368 n = find_neighbour (peer);
5370 n = setup_new_neighbour (peer, GNUNET_YES);
5371 service_context = n->plugins;
5372 while ((service_context != NULL) && (plugin != service_context->plugin))
5373 service_context = service_context->next;
5374 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
5375 peer_address = NULL;
5378 for (c=0; c<ats_count; c++)
5379 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
5380 distance = ntohl(ats_data[c].value);
5383 if (message != NULL)
5385 if ( (session != NULL) ||
5386 (sender_address != NULL) )
5387 peer_address = add_peer_address (n,
5391 sender_address_len);
5392 if (peer_address != NULL)
5394 update_addr_ats(peer_address, ats_data, ats_count);
5395 update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5397 peer_address->distance = distance;
5398 if (GNUNET_YES == peer_address->validated)
5400 mark_address_connected (peer_address);
5401 schedule_next_ping (peer_address);
5406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5407 "New address is unvalidated, trying to validate it now\n");
5409 if (peer_address->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
5411 GNUNET_SCHEDULER_cancel (peer_address->revalidate_task);
5412 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
5414 peer_address->revalidate_task = GNUNET_SCHEDULER_add_now (&send_periodic_ping, peer_address);
5417 peer_address->timeout
5418 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5420 /* update traffic received amount ... */
5421 msize = ntohs (message->size);
5423 GNUNET_STATISTICS_update (stats,
5424 gettext_noop ("# bytes received from other peers"),
5427 n->distance = distance;
5429 GNUNET_TIME_relative_to_absolute
5430 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5431 GNUNET_SCHEDULER_cancel (n->timeout_task);
5433 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
5434 &neighbour_timeout_task, n);
5435 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
5437 /* dropping message due to frequent inbound volume violations! */
5438 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
5439 GNUNET_ERROR_TYPE_BULK,
5441 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
5442 n->in_tracker.available_bytes_per_s__,
5443 n->quota_violation_count);
5444 GNUNET_STATISTICS_update (stats,
5445 gettext_noop ("# bandwidth quota violations by other peers"),
5448 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
5450 if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
5451 (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
5454 uint32_t value = ntohl(*((uint32_t *) &message[1]));
5455 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
5456 /* Force ressource and quality update */
5457 if ((value == 4) && (ats != NULL))
5458 ats_modify_problem_state(ats, ATS_QUALITY_COST_UPDATED);
5459 /* Force cost update */
5460 if ((value == 3) && (ats != NULL))
5461 ats_modify_problem_state(ats, ATS_COST_UPDATED);
5462 /* Force quality update */
5463 if ((value == 2) && (ats != NULL))
5464 ats_modify_problem_state(ats, ATS_QUALITY_UPDATED);
5465 /* Force full rebuild */
5466 if ((value == 1) && (ats != NULL))
5467 ats_modify_problem_state(ats, ATS_MODIFIED);
5472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5473 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
5474 ntohs (message->type),
5475 ntohs (message->size),
5478 switch (ntohs (message->type))
5480 case GNUNET_MESSAGE_TYPE_HELLO:
5481 GNUNET_STATISTICS_update (stats,
5482 gettext_noop ("# HELLO messages received from other peers"),
5485 process_hello (plugin, message);
5487 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
5488 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
5489 if (GNUNET_YES != n->received_pong)
5490 transmit_plain_ping (n);
5492 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
5493 handle_pong (plugin, message, peer, sender_address, sender_address_len);
5495 case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
5498 handle_payload_message (message, n);
5502 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
5503 if (ret.rel_value > 0)
5506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5507 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
5508 (unsigned long long) n->in_tracker.consumption_since_last_update__,
5509 (unsigned int) n->in_tracker.available_bytes_per_s__,
5510 (unsigned long long) ret.rel_value);
5512 GNUNET_STATISTICS_update (stats,
5513 gettext_noop ("# ms throttling suggested"),
5514 (int64_t) ret.rel_value,
5522 notify_client_about_neighbour (void *cls,
5523 const GNUNET_HashCode *key,
5526 struct TransportClient *c = cls;
5527 struct NeighbourMapEntry *n = value;
5528 struct ConnectInfoMessage * cim;
5532 if (GNUNET_YES != n->received_pong)
5536 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
5537 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
5538 cim = GNUNET_malloc (size);
5539 cim->header.size = htons (size);
5540 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
5541 cim->ats_count = htonl(ats_count);
5542 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
5543 (&(cim->ats))[2].value = htonl (0);
5544 if (GNUNET_YES == n->received_pong)
5546 (&cim->ats)[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5547 (&cim->ats)[0].value = htonl (n->distance);
5548 (&cim->ats)[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5549 (&cim->ats)[1].value = htonl ((uint32_t) n->latency.rel_value);
5551 transmit_to_client (c, &cim->header, GNUNET_NO);
5559 * Handle START-message. This is the first message sent to us
5560 * by any client which causes us to add it to our list.
5562 * @param cls closure (always NULL)
5563 * @param client identification of the client
5564 * @param message the actual message
5567 handle_start (void *cls,
5568 struct GNUNET_SERVER_Client *client,
5569 const struct GNUNET_MessageHeader *message)
5571 const struct StartMessage *start;
5572 struct TransportClient *c;
5574 start = (const struct StartMessage*) message;
5576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5577 "Received `%s' request from client\n", "START");
5582 if (c->client == client)
5584 /* client already on our list! */
5586 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5591 if ( (GNUNET_NO != ntohl (start->do_check)) &&
5592 (0 != memcmp (&start->self,
5594 sizeof (struct GNUNET_PeerIdentity))) )
5596 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5597 _("Rejecting control connection from peer `%s', which is not me!\n"),
5598 GNUNET_i2s (&start->self));
5599 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5602 c = GNUNET_malloc (sizeof (struct TransportClient));
5606 if (our_hello != NULL)
5609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5610 "Sending our own `%s' to new client\n", "HELLO");
5612 transmit_to_client (c,
5613 (const struct GNUNET_MessageHeader *) our_hello,
5615 /* tell new client about all existing connections */
5616 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
5617 ¬ify_client_about_neighbour,
5622 #if DEBUG_TRANSPORT_HELLO
5623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5624 "No HELLO created yet, will transmit HELLO to client later!\n");
5628 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5633 * Handle HELLO-message.
5635 * @param cls closure (always NULL)
5636 * @param client identification of the client
5637 * @param message the actual message
5640 handle_hello (void *cls,
5641 struct GNUNET_SERVER_Client *client,
5642 const struct GNUNET_MessageHeader *message)
5646 GNUNET_STATISTICS_update (stats,
5647 gettext_noop ("# HELLOs received from clients"),
5650 ret = process_hello (NULL, message);
5651 GNUNET_SERVER_receive_done (client, ret);
5656 * Closure for 'transmit_client_message'; followed by
5657 * 'msize' bytes of the actual message.
5659 struct TransmitClientMessageContext
5662 * Client on whom's behalf we are sending.
5664 struct GNUNET_SERVER_Client *client;
5667 * Timeout for the transmission.
5669 struct GNUNET_TIME_Absolute timeout;
5677 * Size of the message in bytes.
5684 * Schedule transmission of a message we got from a client to a peer.
5686 * @param cls the 'struct TransmitClientMessageContext*'
5687 * @param n destination, or NULL on error (in that case, drop the message)
5690 transmit_client_message (void *cls,
5691 struct NeighbourMapEntry *n)
5693 struct TransmitClientMessageContext *tcmc = cls;
5694 struct TransportClient *tc;
5697 while ((tc != NULL) && (tc->client != tcmc->client))
5702 transmit_to_peer (tc, NULL, tcmc->priority,
5703 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5705 tcmc->msize, GNUNET_NO, n);
5707 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5708 GNUNET_SERVER_client_drop (tcmc->client);
5714 * Handle SEND-message.
5716 * @param cls closure (always NULL)
5717 * @param client identification of the client
5718 * @param message the actual message
5721 handle_send (void *cls,
5722 struct GNUNET_SERVER_Client *client,
5723 const struct GNUNET_MessageHeader *message)
5725 const struct OutboundMessage *obm;
5726 const struct GNUNET_MessageHeader *obmm;
5727 struct TransmitClientMessageContext *tcmc;
5731 size = ntohs (message->size);
5733 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5736 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5739 GNUNET_STATISTICS_update (stats,
5740 gettext_noop ("# payload received for other peers"),
5743 obm = (const struct OutboundMessage *) message;
5744 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5745 msize = size - sizeof (struct OutboundMessage);
5747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5748 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5749 "SEND", GNUNET_i2s (&obm->peer),
5753 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5754 tcmc->client = client;
5755 tcmc->priority = ntohl (obm->priority);
5756 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5757 tcmc->msize = msize;
5758 /* FIXME: this memcpy can be up to 7% of our total runtime */
5759 memcpy (&tcmc[1], obmm, msize);
5760 GNUNET_SERVER_client_keep (client);
5761 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5762 &transmit_client_message,
5768 * Handle request connect message
5770 * @param cls closure (always NULL)
5771 * @param client identification of the client
5772 * @param message the actual message
5775 handle_request_connect (void *cls,
5776 struct GNUNET_SERVER_Client *client,
5777 const struct GNUNET_MessageHeader *message)
5779 const struct TransportRequestConnectMessage *trcm =
5780 (const struct TransportRequestConnectMessage *) message;
5782 GNUNET_STATISTICS_update (stats,
5783 gettext_noop ("# REQUEST CONNECT messages received"),
5787 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
5788 "Received a request connect message for peer `%s'\n",
5789 GNUNET_i2s(&trcm->peer));
5791 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5793 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5798 * Handle SET_QUOTA-message.
5800 * @param cls closure (always NULL)
5801 * @param client identification of the client
5802 * @param message the actual message
5805 handle_set_quota (void *cls,
5806 struct GNUNET_SERVER_Client *client,
5807 const struct GNUNET_MessageHeader *message)
5809 const struct QuotaSetMessage *qsm =
5810 (const struct QuotaSetMessage *) message;
5811 struct NeighbourMapEntry *n;
5813 GNUNET_STATISTICS_update (stats,
5814 gettext_noop ("# SET QUOTA messages received"),
5817 n = find_neighbour (&qsm->peer);
5820 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5821 GNUNET_STATISTICS_update (stats,
5822 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5829 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5831 (unsigned int) ntohl (qsm->quota.value__),
5832 (unsigned int) n->in_tracker.available_bytes_per_s__,
5833 GNUNET_i2s (&qsm->peer));
5835 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5837 if (0 == ntohl (qsm->quota.value__))
5840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5841 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5844 GNUNET_STATISTICS_update (stats,
5845 gettext_noop ("# disconnects due to quota of 0"),
5848 disconnect_neighbour (n, GNUNET_NO);
5850 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5855 * Take the given address and append it to the set of results sent back to
5858 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5859 * @param address the resolved name, NULL to indicate the last response
5862 transmit_address_to_client (void *cls, const char *address)
5864 struct GNUNET_SERVER_TransmitContext *tc = cls;
5867 if (NULL != address)
5869 slen = strlen (address) + 1;
5870 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5871 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5875 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5881 * Handle AddressLookup-message.
5883 * @param cls closure (always NULL)
5884 * @param client identification of the client
5885 * @param message the actual message
5888 handle_address_lookup (void *cls,
5889 struct GNUNET_SERVER_Client *client,
5890 const struct GNUNET_MessageHeader *message)
5892 const struct AddressLookupMessage *alum;
5893 struct TransportPlugin *lsPlugin;
5894 const char *nameTransport;
5895 const char *address;
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 AddressLookupMessage))
5905 GNUNET_break_op (0);
5906 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5909 alum = (const struct AddressLookupMessage *) message;
5910 uint32_t addressLen = ntohl (alum->addrlen);
5911 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5913 GNUNET_break_op (0);
5914 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5917 address = (const char *) &alum[1];
5918 nameTransport = (const char *) &address[addressLen];
5920 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5922 GNUNET_break_op (0);
5923 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5926 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5927 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5928 numeric = ntohl (alum->numeric_only);
5929 lsPlugin = find_transport (nameTransport);
5930 if (NULL == lsPlugin)
5932 tc = GNUNET_SERVER_transmit_context_create (client);
5933 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5934 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5935 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5938 GNUNET_SERVER_disable_receive_done_warning (client);
5939 tc = GNUNET_SERVER_transmit_context_create (client);
5940 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5942 address, addressLen,
5945 &transmit_address_to_client, tc);
5949 * Handle PeerAddressLookupMessage.
5951 * @param cls closure (always NULL)
5952 * @param client identification of the client
5953 * @param message the actual message
5956 handle_peer_address_lookup (void *cls,
5957 struct GNUNET_SERVER_Client *client,
5958 const struct GNUNET_MessageHeader *message)
5960 const struct PeerAddressLookupMessage *peer_address_lookup;
5961 struct NeighbourMapEntry *neighbor_iterator;
5962 struct ReadyList *ready_iterator;
5963 struct ForeignAddressList *foreign_address_iterator;
5964 struct TransportPlugin *transport_plugin;
5967 struct GNUNET_SERVER_TransmitContext *tc;
5968 struct GNUNET_TIME_Absolute timeout;
5969 struct GNUNET_TIME_Relative rtimeout;
5972 size = ntohs (message->size);
5973 if (size < sizeof (struct PeerAddressLookupMessage))
5975 GNUNET_break_op (0);
5976 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5979 peer_address_lookup = (const struct PeerAddressLookupMessage *) message;
5981 timeout = GNUNET_TIME_absolute_ntoh (peer_address_lookup->timeout);
5982 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5984 neighbor_iterator = find_neighbour (&peer_address_lookup->peer);
5986 /* Found no neighbor matching this peer id (shouldn't be possible, but...) */
5987 if (neighbor_iterator == NULL)
5990 tc = GNUNET_SERVER_transmit_context_create (client);
5991 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5992 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5993 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5997 ready_iterator = neighbor_iterator->plugins;
5998 GNUNET_SERVER_disable_receive_done_warning (client);
5999 tc = GNUNET_SERVER_transmit_context_create (client);
6000 while(ready_iterator != NULL)
6002 foreign_address_iterator = ready_iterator->addresses;
6003 while (foreign_address_iterator != NULL)
6005 transport_plugin = foreign_address_iterator->ready_list->plugin;
6006 if (foreign_address_iterator->addr != NULL)
6008 GNUNET_asprintf (&addr_buf, "%s --- %s, %s",
6009 a2s (transport_plugin->short_name,
6010 foreign_address_iterator->addr,
6011 foreign_address_iterator->addrlen),
6012 (foreign_address_iterator->connected
6013 == GNUNET_YES) ? "CONNECTED"
6015 (foreign_address_iterator->validated
6016 == GNUNET_YES) ? "VALIDATED"
6018 transmit_address_to_client(tc, addr_buf);
6019 GNUNET_free (addr_buf);
6021 else if (foreign_address_iterator->addrlen == 0)
6023 GNUNET_asprintf (&addr_buf, "%s --- %s, %s", "<inbound>",
6024 (foreign_address_iterator->connected
6025 == GNUNET_YES) ? "CONNECTED"
6027 (foreign_address_iterator->validated
6028 == GNUNET_YES) ? "VALIDATED"
6030 transmit_address_to_client (tc, addr_buf);
6031 GNUNET_free (addr_buf);
6034 foreign_address_iterator = foreign_address_iterator->next;
6036 ready_iterator = ready_iterator->next;
6038 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6039 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6040 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6046 output_addresses (void *cls,
6047 const GNUNET_HashCode *key,
6050 struct GNUNET_SERVER_TransmitContext *tc = cls;
6051 struct NeighbourMapEntry *neighbor_iterator = value;
6052 struct ForeignAddressList *foreign_address_iterator;
6053 struct TransportPlugin *transport_plugin;
6054 struct ReadyList *ready_iterator;
6057 ready_iterator = neighbor_iterator->plugins;
6058 while (ready_iterator != NULL)
6060 foreign_address_iterator = ready_iterator->addresses;
6061 while (foreign_address_iterator != NULL)
6063 transport_plugin = foreign_address_iterator->ready_list->plugin;
6064 if (foreign_address_iterator->addr != NULL)
6066 GNUNET_asprintf (&addr_buf, "%s:%s --- %s, %s",
6067 GNUNET_i2s(&neighbor_iterator->id),
6068 a2s (transport_plugin->short_name,
6069 foreign_address_iterator->addr,
6070 foreign_address_iterator->addrlen),
6071 (foreign_address_iterator->connected
6072 == GNUNET_YES) ? "CONNECTED"
6074 (foreign_address_iterator->validated
6075 == GNUNET_YES) ? "VALIDATED"
6077 transmit_address_to_client (tc, addr_buf);
6078 GNUNET_free (addr_buf);
6080 else if (foreign_address_iterator->addrlen == 0)
6082 GNUNET_asprintf (&addr_buf, "%s:%s --- %s, %s",
6083 GNUNET_i2s (&neighbor_iterator->id),
6085 (foreign_address_iterator->connected
6086 == GNUNET_YES) ? "CONNECTED"
6088 (foreign_address_iterator->validated
6089 == GNUNET_YES) ? "VALIDATED"
6091 transmit_address_to_client (tc, addr_buf);
6092 GNUNET_free (addr_buf);
6095 foreign_address_iterator = foreign_address_iterator->next;
6097 ready_iterator = ready_iterator->next;
6104 * Handle AddressIterateMessage
6106 * @param cls closure (always NULL)
6107 * @param client identification of the client
6108 * @param message the actual message
6111 handle_address_iterate (void *cls,
6112 struct GNUNET_SERVER_Client *client,
6113 const struct GNUNET_MessageHeader *message)
6115 struct GNUNET_SERVER_TransmitContext *tc;
6118 size = ntohs (message->size);
6119 if (size < sizeof (struct AddressIterateMessage))
6121 GNUNET_break_op (0);
6122 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6125 GNUNET_SERVER_disable_receive_done_warning (client);
6126 tc = GNUNET_SERVER_transmit_context_create (client);
6127 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
6130 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6131 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6132 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6137 * Setup the environment for this plugin.
6140 create_environment (struct TransportPlugin *plug)
6142 plug->env.cfg = cfg;
6143 plug->env.my_identity = &my_identity;
6144 plug->env.our_hello = &our_hello;
6145 plug->env.cls = plug;
6146 plug->env.receive = &plugin_env_receive;
6147 plug->env.notify_address = &plugin_env_notify_address;
6148 plug->env.session_end = &plugin_env_session_end;
6149 plug->env.max_connections = max_connect_per_transport;
6150 plug->env.stats = stats;
6155 * Start the specified transport (load the plugin).
6158 start_transport (struct GNUNET_SERVER_Handle *server,
6161 struct TransportPlugin *plug;
6164 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6165 _("Loading `%s' transport plugin\n"), name);
6166 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
6167 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
6168 create_environment (plug);
6169 plug->short_name = GNUNET_strdup (name);
6170 plug->lib_name = libname;
6171 plug->next = plugins;
6173 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
6174 if (plug->api == NULL)
6176 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6177 _("Failed to load transport plugin for `%s'\n"), name);
6178 GNUNET_free (plug->short_name);
6179 plugins = plug->next;
6180 GNUNET_free (libname);
6187 null_mq_client_pointers (void *cls,
6188 const GNUNET_HashCode *key,
6191 struct TransportClient *pos = cls;
6192 struct NeighbourMapEntry *n = value;
6193 struct MessageQueue *mq;
6195 for (mq = n->messages_head; mq != NULL; mq = mq->next)
6197 if (mq->client == pos)
6198 mq->client = NULL; /* do not use anymore! */
6205 * Called whenever a client is disconnected. Frees our
6206 * resources associated with that client.
6208 * @param cls closure
6209 * @param client identification of the client
6212 client_disconnect_notification (void *cls,
6213 struct GNUNET_SERVER_Client *client)
6215 struct TransportClient *pos;
6216 struct TransportClient *prev;
6217 struct ClientMessageQueueEntry *mqe;
6218 struct Blacklisters *bl;
6219 struct BlacklistCheck *bc;
6224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
6225 "Client disconnected, cleaning up.\n");
6227 /* clean up blacklister */
6231 if (bl->client == client)
6236 if (bc->bl_pos == bl)
6238 bc->bl_pos = bl->next;
6241 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
6244 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
6245 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
6251 GNUNET_CONTAINER_DLL_remove (bl_head,
6254 GNUNET_SERVER_client_drop (bl->client);
6260 /* clean up 'normal' clients */
6263 while ((pos != NULL) && (pos->client != client))
6270 while (NULL != (mqe = pos->message_queue_head))
6272 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
6273 pos->message_queue_tail,
6275 pos->message_count--;
6278 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
6279 &null_mq_client_pointers,
6282 clients = pos->next;
6284 prev->next = pos->next;
6285 if (GNUNET_YES == pos->tcs_pending)
6290 if (pos->th != NULL)
6292 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
6295 GNUNET_break (0 == pos->message_count);
6301 disconnect_all_neighbours (void *cls,
6302 const GNUNET_HashCode *key,
6305 struct NeighbourMapEntry *n = value;
6308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6309 "Disconnecting peer `%4s', %s\n",
6313 disconnect_neighbour (n, GNUNET_NO);
6319 * Function called when the service shuts down. Unloads our plugins
6320 * and cancels pending validations.
6322 * @param cls closure, unused
6323 * @param tc task context (unused)
6326 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6328 struct TransportPlugin *plug;
6329 struct OwnAddressList *al;
6330 struct CheckHelloValidatedContext *chvc;
6332 shutdown_in_progress = GNUNET_YES;
6333 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
6334 &disconnect_all_neighbours,
6337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6338 "Transport service is unloading plugins...\n");
6340 while (NULL != (plug = plugins))
6342 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
6344 GNUNET_SCHEDULER_cancel (plug->address_update_task);
6345 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
6347 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
6348 GNUNET_free (plug->lib_name);
6349 GNUNET_free (plug->short_name);
6350 while (NULL != (al = plug->addresses))
6352 plug->addresses = al->next;
6355 plugins = plug->next;
6358 if (my_private_key != NULL)
6359 GNUNET_CRYPTO_rsa_key_free (my_private_key);
6360 GNUNET_free_non_null (our_hello);
6362 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
6365 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6366 validation_map = NULL;
6369 if (ats_task != GNUNET_SCHEDULER_NO_TASK)
6371 GNUNET_SCHEDULER_cancel(ats_task);
6372 ats_task = GNUNET_SCHEDULER_NO_TASK;
6379 /* free 'chvc' data structure */
6380 while (NULL != (chvc = chvc_head))
6382 chvc_head = chvc->next;
6383 if (chvc->piter != NULL)
6385 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
6386 GNUNET_STATISTICS_update (stats,
6387 gettext_noop ("# outstanding peerinfo iterate requests"),
6394 GNUNET_assert (chvc->ve_count == 0);
6401 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6404 if (peerinfo != NULL)
6406 GNUNET_PEERINFO_disconnect (peerinfo);
6409 if (GNUNET_SCHEDULER_NO_TASK != hello_task)
6411 GNUNET_SCHEDULER_cancel (hello_task);
6412 hello_task = GNUNET_SCHEDULER_NO_TASK;
6414 /* Can we assume those are gone by now, or do we need to clean up
6416 GNUNET_break (bl_head == NULL);
6417 GNUNET_break (bc_head == NULL);
6418 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
6423 void ats_result_cb ()
6425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6426 "ATS Result callback\n");
6431 struct AtsBuildContext
6433 struct ATS_mechanism * mechanisms;
6434 struct ATS_peer *peers;
6441 find_and_count_addresses (void *cls,
6442 const GNUNET_HashCode *key,
6445 struct AtsBuildContext *abc = cls;
6446 struct NeighbourMapEntry *next = value;
6447 int found_addresses = GNUNET_NO;
6449 struct ReadyList *r_next = next->plugins;
6450 while (r_next != NULL)
6452 struct ForeignAddressList * a_next = r_next->addresses;
6453 while (a_next != NULL)
6456 found_addresses = GNUNET_YES;
6457 a_next = a_next->next;
6459 r_next = r_next->next;
6461 if (found_addresses)
6468 setup_ats_problem (void *cls,
6469 const GNUNET_HashCode *key,
6472 struct AtsBuildContext *abc = cls;
6473 struct NeighbourMapEntry *next = value;
6475 int found_addresses = GNUNET_NO;
6476 struct ReadyList *r_next = next->plugins;
6477 while (r_next != NULL)
6479 struct ForeignAddressList * a_next = r_next->addresses;
6480 while (a_next != NULL)
6482 if (found_addresses == GNUNET_NO)
6484 abc->peers[abc->c_peers].peer = next->id;
6485 abc->peers[abc->c_peers].m_head = NULL;
6486 abc->peers[abc->c_peers].m_tail = NULL;
6487 abc->peers[abc->c_peers].f = 1.0 / abc->c_mechs;
6489 abc->mechanisms[abc->c_mechs].addr = a_next;
6490 abc->mechanisms[abc->c_mechs].col_index = abc->c_mechs;
6491 abc->mechanisms[abc->c_mechs].peer = &abc->peers[abc->c_peers];
6492 abc->mechanisms[abc->c_mechs].next = NULL;
6493 abc->mechanisms[abc->c_mechs].plugin = r_next->plugin;
6494 abc->mechanisms[abc->c_mechs].ressources = a_next->ressources;
6495 abc->mechanisms[abc->c_mechs].quality = a_next->quality;
6496 GNUNET_CONTAINER_DLL_insert_tail(abc->peers[abc->c_peers].m_head,
6497 abc->peers[abc->c_peers].m_tail,
6498 &abc->mechanisms[abc->c_mechs]);
6499 found_addresses = GNUNET_YES;
6501 a_next = a_next->next;
6503 r_next = r_next->next;
6505 if (found_addresses == GNUNET_YES)
6512 create_ats_information ( struct ATS_peer **p,
6514 struct ATS_mechanism ** m,
6517 struct AtsBuildContext abc;
6520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6521 "ATS requires clean address information\n");
6525 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
6526 &find_and_count_addresses,
6529 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6530 "Found %u peers with % u transport mechanisms\n", c_peers, c_mechs);
6533 if ( (abc.c_peers == 0) && (abc.c_mechs == 0) )
6542 abc.mechanisms = GNUNET_malloc((1+abc.c_mechs) * sizeof (struct ATS_mechanism));
6543 abc.peers = GNUNET_malloc((1+abc.c_peers) * sizeof (struct ATS_peer));
6546 GNUNET_CONTAINER_multihashmap_iterate (neighbours,
6551 (*c_m) = abc.c_mechs;
6552 (*c_p) = abc.c_peers;
6554 (*m) = abc.mechanisms;
6559 schedule_ats (void *cls,
6560 const struct GNUNET_SCHEDULER_TaskContext *tc)
6562 struct ATS_Handle *ats = (struct ATS_Handle *) cls;
6566 ats_task = GNUNET_SCHEDULER_NO_TASK;
6567 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
6570 if (shutdown_in_progress == GNUNET_YES)
6573 struct GNUNET_TIME_Relative delta =
6574 GNUNET_TIME_absolute_get_difference (last_ats_execution, GNUNET_TIME_absolute_get());
6575 if (delta.rel_value < ats_minimum_interval.rel_value)
6578 GNUNET_log (GNUNET_ERROR_TYPE_BULK,
6579 "Minimum time between cycles not reached\n");
6585 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
6588 ats_calculate_bandwidth_distribution (ats);
6590 last_ats_execution = GNUNET_TIME_absolute_get();
6592 ats_task = GNUNET_SCHEDULER_add_delayed (ats_regular_interval,
6593 &schedule_ats, ats);
6598 struct ForeignAddressList * get_preferred_ats_address (
6599 struct NeighbourMapEntry *n)
6601 // TODO get ATS prefered address
6602 return find_ready_address(n);
6606 * Initiate transport service.
6608 * @param cls closure
6609 * @param server the initialized server
6610 * @param c configuration to use
6614 struct GNUNET_SERVER_Handle *server,
6615 const struct GNUNET_CONFIGURATION_Handle *c)
6617 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
6618 {&handle_start, NULL,
6619 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
6620 {&handle_hello, NULL,
6621 GNUNET_MESSAGE_TYPE_HELLO, 0},
6622 {&handle_send, NULL,
6623 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
6624 {&handle_request_connect, NULL,
6625 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
6626 {&handle_set_quota, NULL,
6627 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
6628 {&handle_address_lookup, NULL,
6629 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
6631 {&handle_peer_address_lookup, NULL,
6632 GNUNET_MESSAGE_TYPE_TRANSPORT_PEER_ADDRESS_LOOKUP,
6634 {&handle_address_iterate, NULL,
6635 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE,
6637 {&handle_blacklist_init, NULL,
6638 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
6639 {&handle_blacklist_reply, NULL,
6640 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
6646 unsigned long long tneigh;
6649 shutdown_in_progress = GNUNET_NO;
6651 stats = GNUNET_STATISTICS_create ("transport", cfg);
6652 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
6653 neighbours = GNUNET_CONTAINER_multihashmap_create (256);
6654 /* parse configuration */
6656 GNUNET_CONFIGURATION_get_value_number (c,
6661 GNUNET_CONFIGURATION_get_value_filename (c,
6663 "HOSTKEY", &keyfile)))
6665 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6667 ("Transport service is lacking key configuration settings. Exiting.\n"));
6668 GNUNET_SCHEDULER_shutdown ();
6671 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6674 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6675 validation_map = NULL;
6676 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
6681 max_connect_per_transport = (uint32_t) tneigh;
6682 peerinfo = GNUNET_PEERINFO_connect (cfg);
6683 if (peerinfo == NULL)
6685 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6686 _("Could not access PEERINFO service. Exiting.\n"));
6687 GNUNET_SCHEDULER_shutdown ();
6690 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6693 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6694 validation_map = NULL;
6695 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
6697 GNUNET_free (keyfile);
6700 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
6701 GNUNET_free (keyfile);
6702 if (my_private_key == NULL)
6704 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6706 ("Transport service could not access hostkey. Exiting.\n"));
6707 GNUNET_SCHEDULER_shutdown ();
6710 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6713 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6714 validation_map = NULL;
6715 GNUNET_CONTAINER_multihashmap_destroy (neighbours);
6719 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
6720 GNUNET_CRYPTO_hash (&my_public_key,
6721 sizeof (my_public_key), &my_identity.hashPubKey);
6722 /* setup notification */
6723 GNUNET_SERVER_disconnect_notify (server,
6724 &client_disconnect_notification, NULL);
6725 /* load plugins... */
6728 GNUNET_CONFIGURATION_get_value_string (c,
6729 "TRANSPORT", "PLUGINS", &plugs))
6731 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6732 _("Starting transport plugins `%s'\n"), plugs);
6733 pos = strtok (plugs, " ");
6736 start_transport (server, pos);
6738 pos = strtok (NULL, " ");
6740 GNUNET_free (plugs);
6742 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
6743 &shutdown_task, NULL);
6747 /* Initializing ATS */
6750 unsigned long long value;
6755 int v_b_min = 64000;
6759 ats_minimum_interval = ATS_MIN_INTERVAL;
6760 ats_regular_interval = ATS_EXEC_INTERVAL;
6762 /* loading cost ressources */
6763 for (co=0; co<available_ressources; co++)
6765 GNUNET_asprintf(§ion,"%s_UP",ressources[co].cfg_param);
6766 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
6768 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg,
6774 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6775 "Found ressource cost: [%s] = %llu\n",
6778 ressources[co].c_max = value;
6781 GNUNET_free (section);
6782 GNUNET_asprintf(§ion,"%s_DOWN",ressources[co].cfg_param);
6783 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
6785 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg,
6791 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6792 "Found ressource cost: [%s] = %llu\n",
6795 ressources[co].c_min = value;
6798 GNUNET_free (section);
6801 ats = ats_init (D, U, R, v_b_min, v_n_min,
6802 ATS_MAX_ITERATIONS, ATS_MAX_EXEC_DURATION,
6803 &create_ats_information,
6805 ats_set_logging_options (ats,
6808 GNUNET_break (GNUNET_OK ==
6809 GNUNET_CONFIGURATION_get_value_time (cfg,
6811 "ATS_EXEC_INTERVAL",
6812 &ats_regular_interval));
6813 GNUNET_break (GNUNET_OK ==
6814 GNUNET_CONFIGURATION_get_value_time (cfg,
6817 &ats_minimum_interval));
6819 ats_task = GNUNET_SCHEDULER_add_now (&schedule_ats, ats);
6824 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6825 _("Transport service ready.\n"));
6827 /* If we have a blacklist file, read from it */
6828 read_blacklist_file(cfg);
6829 /* process client requests */
6830 GNUNET_SERVER_add_handlers (server, handlers);
6835 * The main function for the transport service.
6837 * @param argc number of arguments from the command line
6838 * @param argv command line arguments
6839 * @return 0 ok, 1 on error
6842 main (int argc, char *const *argv)
6844 a2s (NULL, NULL, 0); /* make compiler happy */
6845 return (GNUNET_OK ==
6846 GNUNET_SERVICE_run (argc,
6849 GNUNET_SERVICE_OPTION_NONE,
6850 &run, NULL)) ? 0 : 1;
6853 /* end of gnunet-service-transport.c */