2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file transport/gnunet-service-transport.c
23 * @brief low-level P2P messaging
24 * @author Christian Grothoff
28 #include "gnunet_client_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_peerinfo_service.h"
35 #include "gnunet_plugin_lib.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_service_lib.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
45 #define DEBUG_BLACKLIST GNUNET_NO
47 #define DEBUG_PING_PONG GNUNET_NO
49 #define DEBUG_TRANSPORT_HELLO GNUNET_NO
51 #define DEBUG_ATS GNUNET_NO
52 #define VERBOSE_ATS GNUNET_NO
55 * Should we do some additional checks (to validate behavior
58 #define EXTRA_CHECKS GNUNET_YES
61 * How many messages can we have pending for a given client process
62 * before we start to drop incoming messages? We typically should
63 * have only one client and so this would be the primary buffer for
64 * messages, so the number should be chosen rather generously.
66 * The expectation here is that most of the time the queue is large
67 * enough so that a drop is virtually never required. Note that
68 * this value must be about as large as 'TOTAL_MSGS' in the
69 * 'test_transport_api_reliability.c', otherwise that testcase may
72 #define MAX_PENDING (128 * 1024)
75 * Size of the per-transport blacklist hash maps.
77 #define TRANSPORT_BLACKLIST_HT_SIZE 16
80 * How often should we try to reconnect to a peer using a particular
81 * transport plugin before giving up? Note that the plugin may be
82 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
84 #define MAX_CONNECT_RETRY 3
87 * Limit on the number of ready-to-run tasks when validating
88 * HELLOs. If more tasks are ready to run, we will drop
89 * HELLOs instead of validating them.
91 #define MAX_HELLO_LOAD 4
94 * How often must a peer violate bandwidth quotas before we start
95 * to simply drop its messages?
97 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
100 * How long until a HELLO verification attempt should time out?
101 * Must be rather small, otherwise a partially successful HELLO
102 * validation (some addresses working) might not be available
103 * before a client's request for a connection fails for good.
104 * Besides, if a single request to an address takes a long time,
105 * then the peer is unlikely worthwhile anyway.
107 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
110 * How long is a PONG signature valid? We'll recycle a signature until
111 * 1/4 of this time is remaining. PONGs should expire so that if our
112 * external addresses change an adversary cannot replay them indefinitely.
113 * OTOH, we don't want to spend too much time generating PONG signatures,
114 * so they must have some lifetime to reduce our CPU usage.
116 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
119 * Priority to use for PONG messages.
121 #define TRANSPORT_PONG_PRIORITY 4
124 * How often do we re-add (cheaper) plugins to our list of plugins
125 * to try for a given connected peer?
127 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
130 * After how long do we expire an address in a HELLO that we just
131 * validated? This value is also used for our own addresses when we
134 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
138 * How long before an existing address expires should we again try to
139 * validate it? Must be (significantly) smaller than
140 * HELLO_ADDRESS_EXPIRATION.
142 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
145 * Maximum frequency for re-evaluating latencies for all transport addresses.
147 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
150 * Maximum frequency for re-evaluating latencies for connected addresses.
152 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
156 * List of addresses of other peers
158 struct ForeignAddressList
161 * This is a linked list.
163 struct ForeignAddressList *next;
166 * Which ready list does this entry belong to.
168 struct ReadyList *ready_list;
171 * How long until we auto-expire this address (unless it is
172 * re-confirmed by the transport)?
174 struct GNUNET_TIME_Absolute expires;
177 * Task used to re-validate addresses, updates latencies and
180 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
188 * Session (or NULL if no valid session currently exists or if the
189 * plugin does not use sessions).
191 struct Session *session;
194 * What was the last latency observed for this address, plugin and peer?
196 struct GNUNET_TIME_Relative latency;
199 * If we did not successfully transmit a message to the given peer
200 * via this connection during the specified time, we should consider
201 * the connection to be dead. This is used in the case that a TCP
202 * transport simply stalls writing to the stream but does not
203 * formerly get a signal that the other peer died.
205 struct GNUNET_TIME_Absolute timeout;
208 * How often have we tried to connect using this plugin? Used to
209 * discriminate against addresses that do not work well.
210 * FIXME: not yet used, but should be!
212 unsigned int connect_attempts;
215 * DV distance to this peer (1 if no DV is used).
216 * FIXME: need to set this from transport plugins!
226 * Have we ever estimated the latency of this address? Used to
227 * ensure that the first time we add an address, we immediately
233 * Are we currently connected via this address? The first time we
234 * successfully transmit or receive data to a peer via a particular
235 * address, we set this to GNUNET_YES. If we later get an error
236 * (disconnect notification, transmission failure, timeout), we set
237 * it back to GNUNET_NO.
242 * Is this plugin currently busy transmitting to the specific target?
243 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
244 * messages do not count as 'in transmit'.
249 * Has this address been validated yet?
257 * Entry in linked list of network addresses for ourselves. Also
258 * includes a cached signature for 'struct TransportPongMessage's.
260 struct OwnAddressList
263 * This is a linked list.
265 struct OwnAddressList *next;
268 * How long until we actually auto-expire this address (unless it is
269 * re-confirmed by the transport)?
271 struct GNUNET_TIME_Absolute expires;
274 * How long until the current signature expires? (ZERO if the
275 * signature was never created).
277 struct GNUNET_TIME_Absolute pong_sig_expires;
280 * Signature for a 'struct TransportPongMessage' for this address.
282 struct GNUNET_CRYPTO_RsaSignature pong_signature;
293 * Entry in linked list of all of our plugins.
295 struct TransportPlugin
299 * This is a linked list.
301 struct TransportPlugin *next;
304 * API of the transport as returned by the plugin's
305 * initialization function.
307 struct GNUNET_TRANSPORT_PluginFunctions *api;
310 * Short name for the plugin (i.e. "tcp").
315 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
320 * List of our known addresses for this transport.
322 struct OwnAddressList *addresses;
325 * Environment this transport service is using
328 struct GNUNET_TRANSPORT_PluginEnvironment env;
331 * ID of task that is used to clean up expired addresses.
333 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
336 * Set to GNUNET_YES if we need to scrap the existing list of
337 * "addresses" and start fresh when we receive the next address
338 * update from a transport. Set to GNUNET_NO if we should just add
339 * the new address to the list and wait for the commit call.
344 * Hashmap of blacklisted peers for this particular transport.
346 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
349 struct NeighbourList;
352 * For each neighbour we keep a list of messages
353 * that we still want to transmit to the neighbour.
359 * This is a doubly linked list.
361 struct MessageQueue *next;
364 * This is a doubly linked list.
366 struct MessageQueue *prev;
369 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
370 * stuck together in memory. Allocated at the end of this struct.
372 const char *message_buf;
375 * Size of the message buf
377 size_t message_buf_size;
380 * Client responsible for queueing the message;
381 * used to check that a client has no two messages
382 * pending for the same target. Can be NULL.
384 struct TransportClient *client;
387 * Using which specific address should we send this message?
389 struct ForeignAddressList *specific_address;
392 * Peer ID of the Neighbour this entry belongs to.
394 struct GNUNET_PeerIdentity neighbour_id;
397 * Plugin that we used for the transmission.
398 * NULL until we scheduled a transmission.
400 struct TransportPlugin *plugin;
403 * At what time should we fail?
405 struct GNUNET_TIME_Absolute timeout;
408 * Internal message of the transport system that should not be
409 * included in the usual SEND-SEND_OK transmission confirmation
410 * traffic management scheme. Typically, "internal_msg" will
411 * be set whenever "client" is NULL (but it is not strictly
417 * How important is the message?
419 unsigned int priority;
425 * For a given Neighbour, which plugins are available
426 * to talk to this peer and what are their costs?
431 * This is a linked list.
433 struct ReadyList *next;
436 * Which of our transport plugins does this entry
439 struct TransportPlugin *plugin;
442 * Transport addresses, latency, and readiness for
443 * this particular plugin.
445 struct ForeignAddressList *addresses;
448 * To which neighbour does this ready list belong to?
450 struct NeighbourList *neighbour;
456 * Entry in linked list of all of our current neighbours.
462 * This is a linked list.
464 struct NeighbourList *next;
467 * Which of our transports is connected to this peer
468 * and what is their status?
470 struct ReadyList *plugins;
473 * Head of list of messages we would like to send to this peer;
474 * must contain at most one message per client.
476 struct MessageQueue *messages_head;
479 * Tail of list of messages we would like to send to this peer; must
480 * contain at most one message per client.
482 struct MessageQueue *messages_tail;
485 * Buffer for at most one payload message used when we receive
486 * payload data before our PING-PONG has succeeded. We then
487 * store such messages in this intermediary buffer until the
488 * connection is fully up.
490 struct GNUNET_MessageHeader *pre_connect_message_buffer;
493 * Context for peerinfo iteration.
494 * NULL after we are done processing peerinfo's information.
496 struct GNUNET_PEERINFO_IteratorContext *piter;
499 * Public key for this peer. Valid only if the respective flag is set below.
501 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
504 * Identity of this neighbour.
506 struct GNUNET_PeerIdentity id;
509 * ID of task scheduled to run when this peer is about to
510 * time out (will free resources associated with the peer).
512 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
515 * ID of task scheduled to run when we should retry transmitting
516 * the head of the message queue. Actually triggered when the
517 * transmission is timing out (we trigger instantly when we have
518 * a chance of success).
520 GNUNET_SCHEDULER_TaskIdentifier retry_task;
523 * How long until we should consider this peer dead
524 * (if we don't receive another message in the
527 struct GNUNET_TIME_Absolute peer_timeout;
530 * Tracker for inbound bandwidth.
532 struct GNUNET_BANDWIDTH_Tracker in_tracker;
535 * The latency we have seen for this particular address for
536 * this particular peer. This latency may have been calculated
537 * over multiple transports. This value reflects how long it took
538 * us to receive a response when SENDING via this particular
539 * transport/neighbour/address combination!
541 * FIXME: we need to periodically send PINGs to update this
542 * latency (at least more often than the current "huge" (11h?)
545 struct GNUNET_TIME_Relative latency;
548 * How often has the other peer (recently) violated the
549 * inbound traffic limit? Incremented by 10 per violation,
550 * decremented by 1 per non-violation (for each
553 unsigned int quota_violation_count;
556 * DV distance to this peer (1 if no DV is used).
561 * Have we seen an PONG from this neighbour in the past (and
562 * not had a disconnect since)?
567 * Do we have a valid public key for this neighbour?
569 int public_key_valid;
572 * Performance data for the peer.
574 struct GNUNET_TRANSPORT_ATS_Information *ats;
577 * Identity of the neighbour.
579 struct GNUNET_PeerIdentity peer;
584 * Message used to ask a peer to validate receipt (to check an address
585 * from a HELLO). Followed by the address we are trying to validate,
586 * or an empty address if we are just sending a PING to confirm that a
587 * connection which the receiver (of the PING) initiated is still valid.
589 struct TransportPingMessage
593 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
595 struct GNUNET_MessageHeader header;
598 * Challenge code (to ensure fresh reply).
600 uint32_t challenge GNUNET_PACKED;
603 * Who is the intended recipient?
605 struct GNUNET_PeerIdentity target;
611 * Message used to validate a HELLO. The challenge is included in the
612 * confirmation to make matching of replies to requests possible. The
613 * signature signs our public key, an expiration time and our address.<p>
615 * This message is followed by our transport address that the PING tried
616 * to confirm (if we liked it). The address can be empty (zero bytes)
617 * if the PING had not address either (and we received the request via
618 * a connection that we initiated).
620 struct TransportPongMessage
624 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
626 struct GNUNET_MessageHeader header;
629 * Challenge code from PING (showing freshness). Not part of what
630 * is signed so that we can re-use signatures.
632 uint32_t challenge GNUNET_PACKED;
637 struct GNUNET_CRYPTO_RsaSignature signature;
640 * What are we signing and why? Two possible reason codes can be here:
641 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
642 * plausible address for this peer (pid is set to identity of signer); or
643 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
644 * an address we used to connect to the peer with the given pid.
646 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
649 * When does this signature expire?
651 struct GNUNET_TIME_AbsoluteNBO expiration;
654 * Either the identity of the peer Who signed this message, or the
655 * identity of the peer that we're connected to using the given
656 * address (depending on purpose.type).
658 struct GNUNET_PeerIdentity pid;
661 * Size of address appended to this message (part of what is
662 * being signed, hence not redundant).
670 * Linked list of messages to be transmitted to the client. Each
671 * entry is followed by the actual message.
673 struct ClientMessageQueueEntry
676 * This is a doubly-linked list.
678 struct ClientMessageQueueEntry *next;
681 * This is a doubly-linked list.
683 struct ClientMessageQueueEntry *prev;
688 * Client connected to the transport service.
690 struct TransportClient
694 * This is a linked list.
696 struct TransportClient *next;
699 * Handle to the client.
701 struct GNUNET_SERVER_Client *client;
704 * Linked list of messages yet to be transmitted to
707 struct ClientMessageQueueEntry *message_queue_head;
710 * Tail of linked list of messages yet to be transmitted to the
713 struct ClientMessageQueueEntry *message_queue_tail;
716 * Current transmit request handle.
718 struct GNUNET_CONNECTION_TransmitHandle *th;
721 * Is a call to "transmit_send_continuation" pending? If so, we
722 * must not free this struct (even if the corresponding client
723 * disconnects) and instead only remove it from the linked list and
724 * set the "client" field to NULL.
729 * Length of the list of messages pending for this client.
731 unsigned int message_count;
737 * Context of currently active requests to peerinfo
738 * for validation of HELLOs.
740 struct CheckHelloValidatedContext;
744 * Entry in map of all HELLOs awaiting validation.
746 struct ValidationEntry
750 * NULL if this entry is not part of a larger HELLO validation.
752 struct CheckHelloValidatedContext *chvc;
755 * The address, actually a pointer to the end
756 * of this struct. Do not free!
761 * Name of the transport.
763 char *transport_name;
766 * The public key of the peer.
768 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
771 * ID of task that will clean up this entry if we don't succeed
772 * with the validation first.
774 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
777 * At what time did we send this validation?
779 struct GNUNET_TIME_Absolute send_time;
782 * Session being validated (or NULL for none).
784 struct Session *session;
787 * Challenge number we used.
800 * Context of currently active requests to peerinfo
801 * for validation of HELLOs.
803 struct CheckHelloValidatedContext
807 * This is a doubly-linked list.
809 struct CheckHelloValidatedContext *next;
812 * This is a doubly-linked list.
814 struct CheckHelloValidatedContext *prev;
817 * Hello that we are validating.
819 const struct GNUNET_HELLO_Message *hello;
822 * Context for peerinfo iteration.
823 * NULL after we are done processing peerinfo's information.
825 struct GNUNET_PEERINFO_IteratorContext *piter;
828 * Was a HELLO known for this peer to peerinfo?
833 * Number of validation entries currently referring to this
836 unsigned int ve_count;
844 static struct GNUNET_HELLO_Message *our_hello;
849 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
854 static struct GNUNET_PeerIdentity my_identity;
859 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
864 const struct GNUNET_CONFIGURATION_Handle *cfg;
867 * Linked list of all clients to this service.
869 static struct TransportClient *clients;
872 * All loaded plugins.
874 static struct TransportPlugin *plugins;
877 * Handle to peerinfo service.
879 static struct GNUNET_PEERINFO_Handle *peerinfo;
882 * All known neighbours and their HELLOs.
884 static struct NeighbourList *neighbours;
887 * Number of neighbours we'd like to have.
889 static uint32_t max_connect_per_transport;
892 * Head of linked list.
894 static struct CheckHelloValidatedContext *chvc_head;
897 * Tail of linked list.
899 static struct CheckHelloValidatedContext *chvc_tail;
902 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
903 * of the given peer that we are currently validating).
905 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
908 * Handle for reporting statistics.
910 static struct GNUNET_STATISTICS_Handle *stats;
913 * Handle for ats information
915 static struct ATS_info *ats;
918 * The peer specified by the given neighbour has timed-out or a plugin
919 * has disconnected. We may either need to do nothing (other plugins
920 * still up), or trigger a full disconnect and clean up. This
921 * function updates our state and do the necessary notifications.
922 * Also notifies our clients that the neighbour is now officially
925 * @param n the neighbour list entry for the peer
926 * @param check should we just check if all plugins
927 * disconnected or must we ask all plugins to
930 static void disconnect_neighbour (struct NeighbourList *n, int check);
933 * Check the ready list for the given neighbour and if a plugin is
934 * ready for transmission (and if we have a message), do so!
936 * @param nexi target peer for which to transmit
938 static void try_transmission_to_peer (struct NeighbourList *n);
941 struct ATS_info * ats_init ();
943 void ats_shutdown ( );
945 void ats_notify_peer_connect (
946 const struct GNUNET_PeerIdentity *peer,
947 const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
949 void ats_notify_peer_disconnect (
950 const struct GNUNET_PeerIdentity *peer);
952 void ats_notify_ats_data (
953 const struct GNUNET_PeerIdentity *peer,
954 const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
956 struct ForeignAddressList * ats_get_preferred_address (
957 struct NeighbourList *n);
960 * Find an entry in the neighbour list for a particular peer.
962 * @return NULL if not found.
964 static struct NeighbourList *
965 find_neighbour (const struct GNUNET_PeerIdentity *key)
967 struct NeighbourList *head = neighbours;
969 while ((head != NULL) &&
970 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
977 * Find an entry in the transport list for a particular transport.
979 * @return NULL if not found.
981 static struct TransportPlugin *
982 find_transport (const char *short_name)
984 struct TransportPlugin *head = plugins;
985 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
991 * Is a particular peer blacklisted for a particular transport?
993 * @param peer the peer to check for
994 * @param plugin the plugin used to connect to the peer
996 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
999 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
1002 if (plugin->blacklist != NULL)
1004 if (GNUNET_CONTAINER_multihashmap_contains (plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
1007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1008 "Peer `%s:%s' is blacklisted!\n",
1009 plugin->short_name, GNUNET_i2s (peer));
1012 GNUNET_STATISTICS_update (stats, "# blacklisted peers refused", 1, GNUNET_NO);
1022 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
1024 struct TransportPlugin *plugin;
1026 plugin = find_transport(transport_name);
1027 if (plugin == NULL) /* Nothing to do */
1029 if (plugin->blacklist == NULL)
1030 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
1031 GNUNET_assert(plugin->blacklist != NULL);
1032 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
1034 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1039 * Read the blacklist file, containing transport:peer entries.
1040 * Provided the transport is loaded, set up hashmap with these
1041 * entries to blacklist peers by transport.
1045 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1052 struct GNUNET_PeerIdentity pid;
1054 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1055 unsigned int entries_found;
1056 char *transport_name;
1059 GNUNET_CONFIGURATION_get_value_filename (cfg,
1065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066 "Option `%s' in section `%s' not specified!\n",
1072 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1073 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1074 | GNUNET_DISK_PERM_USER_WRITE);
1075 if (0 != STAT (fn, &frstat))
1077 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1078 _("Could not read blacklist file `%s'\n"), fn);
1082 if (frstat.st_size == 0)
1085 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1086 _("Blacklist file `%s' is empty.\n"),
1092 /* FIXME: use mmap */
1093 data = GNUNET_malloc_large (frstat.st_size);
1094 GNUNET_assert(data != NULL);
1095 if (frstat.st_size !=
1096 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1098 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1099 _("Failed to read blacklist from `%s'\n"), fn);
1106 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1108 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1109 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1112 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1115 if (colon_pos >= frstat.st_size)
1117 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1118 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1119 (unsigned long long) colon_pos);
1125 if (isspace( (unsigned char) data[colon_pos]))
1127 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1128 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1129 (unsigned long long) colon_pos);
1131 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1135 tsize = colon_pos - pos;
1136 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1138 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1139 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1140 (unsigned long long) colon_pos);
1149 transport_name = GNUNET_malloc(tsize + 1);
1150 memcpy(transport_name, &data[pos], tsize);
1151 pos = colon_pos + 1;
1153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1154 "Read transport name %s in blacklist file.\n",
1157 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1158 if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1160 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1161 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1162 (unsigned long long) pos);
1164 while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1166 GNUNET_free_non_null(transport_name);
1169 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1170 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1172 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1173 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1174 (unsigned long long) pos,
1179 if (0 != memcmp (&pid,
1181 sizeof (struct GNUNET_PeerIdentity)))
1184 add_peer_to_blacklist (&pid,
1189 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1190 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1194 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1195 GNUNET_free_non_null(transport_name);
1196 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1199 GNUNET_STATISTICS_update (stats, "# Transport entries blacklisted", entries_found, GNUNET_NO);
1206 * Function called to notify a client about the socket being ready to
1207 * queue more data. "buf" will be NULL and "size" zero if the socket
1208 * was closed for writing in the meantime.
1210 * @param cls closure
1211 * @param size number of bytes available in buf
1212 * @param buf where the callee should write the message
1213 * @return number of bytes written to buf
1216 transmit_to_client_callback (void *cls, size_t size, void *buf)
1218 struct TransportClient *client = cls;
1219 struct ClientMessageQueueEntry *q;
1222 const struct GNUNET_MessageHeader *msg;
1229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230 "Transmission to client failed, closing connection.\n");
1232 /* fatal error with client, free message queue! */
1233 while (NULL != (q = client->message_queue_head))
1235 GNUNET_STATISTICS_update (stats,
1236 gettext_noop ("# bytes discarded (could not transmit to client)"),
1237 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1239 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1240 client->message_queue_tail,
1244 client->message_count = 0;
1249 while (NULL != (q = client->message_queue_head))
1251 msg = (const struct GNUNET_MessageHeader *) &q[1];
1252 msize = ntohs (msg->size);
1253 if (msize + tsize > size)
1256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257 "Transmitting message of type %u to client.\n",
1260 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1261 client->message_queue_tail,
1263 memcpy (&cbuf[tsize], msg, msize);
1266 client->message_count--;
1270 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1271 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1273 GNUNET_TIME_UNIT_FOREVER_REL,
1274 &transmit_to_client_callback,
1276 GNUNET_assert (client->th != NULL);
1283 * Convert an address to a string.
1285 * @param plugin name of the plugin responsible for the address
1286 * @param addr binary address
1287 * @param addr_len number of bytes in addr
1288 * @return NULL on error, otherwise address string
1291 a2s (const char *plugin,
1295 struct TransportPlugin *p;
1299 p = find_transport (plugin);
1302 return p->api->address_to_string (p->api->cls,
1309 * Mark the given FAL entry as 'connected' (and hence preferred for
1310 * sending); also mark all others for the same peer as 'not connected'
1311 * (since only one can be preferred).
1313 * @param fal address to set to 'connected'
1316 mark_address_connected (struct ForeignAddressList *fal)
1318 struct ForeignAddressList *pos;
1321 GNUNET_assert (GNUNET_YES == fal->validated);
1322 if (fal->connected == GNUNET_YES)
1323 return; /* nothing to do */
1325 pos = fal->ready_list->addresses;
1328 if (GNUNET_YES == pos->connected)
1331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1332 "Marking address `%s' as no longer connected (due to connect on other address)\n",
1333 a2s (pos->ready_list->plugin->short_name,
1337 GNUNET_break (cnt == GNUNET_YES);
1339 pos->connected = GNUNET_NO;
1340 GNUNET_STATISTICS_update (stats,
1341 gettext_noop ("# connected addresses"),
1347 fal->connected = GNUNET_YES;
1348 if (GNUNET_YES == cnt)
1350 GNUNET_STATISTICS_update (stats,
1351 gettext_noop ("# connected addresses"),
1359 * Send the specified message to the specified client. Since multiple
1360 * messages may be pending for the same client at a time, this code
1361 * makes sure that no message is lost.
1363 * @param client client to transmit the message to
1364 * @param msg the message to send
1365 * @param may_drop can this message be dropped if the
1366 * message queue for this client is getting far too large?
1369 transmit_to_client (struct TransportClient *client,
1370 const struct GNUNET_MessageHeader *msg, int may_drop)
1372 struct ClientMessageQueueEntry *q;
1375 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1377 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1379 ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1382 client->message_count,
1384 GNUNET_STATISTICS_update (stats,
1385 gettext_noop ("# messages dropped due to slow client"),
1390 msize = ntohs (msg->size);
1391 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1392 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1393 memcpy (&q[1], msg, msize);
1394 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1395 client->message_queue_tail,
1396 client->message_queue_tail,
1398 client->message_count++;
1399 if (client->th == NULL)
1401 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1403 GNUNET_TIME_UNIT_FOREVER_REL,
1404 &transmit_to_client_callback,
1406 GNUNET_assert (client->th != NULL);
1412 * Transmit a 'SEND_OK' notification to the given client for the
1415 * @param client who to notify
1416 * @param n neighbour to notify about, can be NULL (on failure)
1417 * @param target target of the transmission
1418 * @param result status code for the transmission request
1421 transmit_send_ok (struct TransportClient *client,
1422 struct NeighbourList *n,
1423 const struct GNUNET_PeerIdentity *target,
1426 struct SendOkMessage send_ok_msg;
1428 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1429 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1430 send_ok_msg.success = htonl (result);
1432 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1434 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1435 send_ok_msg.peer = *target;
1436 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1441 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1442 * upon "completion" of a send request. This tells the API
1443 * that it is now legal to send another message to the given
1446 * @param cls closure, identifies the entry on the
1447 * message queue that was transmitted and the
1448 * client responsible for queuing the message
1449 * @param target the peer receiving the message
1450 * @param result GNUNET_OK on success, if the transmission
1451 * failed, we should not tell the client to transmit
1455 transmit_send_continuation (void *cls,
1456 const struct GNUNET_PeerIdentity *target,
1459 struct MessageQueue *mq = cls;
1460 struct NeighbourList *n;
1462 GNUNET_STATISTICS_update (stats,
1463 gettext_noop ("# bytes pending with plugins"),
1464 - (int64_t) mq->message_buf_size,
1466 if (result == GNUNET_OK)
1468 GNUNET_STATISTICS_update (stats,
1469 gettext_noop ("# bytes successfully transmitted by plugins"),
1470 mq->message_buf_size,
1475 GNUNET_STATISTICS_update (stats,
1476 gettext_noop ("# bytes with transmission failure by plugins"),
1477 mq->message_buf_size,
1480 if (mq->specific_address != NULL)
1482 if (result == GNUNET_OK)
1484 mq->specific_address->timeout =
1485 GNUNET_TIME_relative_to_absolute
1486 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1487 if (mq->specific_address->validated == GNUNET_YES)
1488 mark_address_connected (mq->specific_address);
1492 if (mq->specific_address->connected != GNUNET_NO)
1495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1496 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1497 a2s (mq->specific_address->ready_list->plugin->short_name,
1498 mq->specific_address->addr,
1499 mq->specific_address->addrlen));
1501 GNUNET_STATISTICS_update (stats,
1502 gettext_noop ("# connected addresses"),
1505 mq->specific_address->connected = GNUNET_NO;
1508 if (! mq->internal_msg)
1509 mq->specific_address->in_transmit = GNUNET_NO;
1511 n = find_neighbour(&mq->neighbour_id);
1512 if (mq->client != NULL)
1513 transmit_send_ok (mq->client, n, target, result);
1516 try_transmission_to_peer (n);
1521 * Find an address in any of the available transports for
1522 * the given neighbour that would be good for message
1523 * transmission. This is essentially the transport selection
1526 * @param neighbour for whom to select an address
1527 * @return selected address, NULL if we have none
1529 struct ForeignAddressList *
1530 find_ready_address(struct NeighbourList *neighbour)
1532 struct ReadyList *head = neighbour->plugins;
1533 struct ForeignAddressList *addresses;
1534 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1535 struct ForeignAddressList *best_address;
1537 /* Hack to prefer unix domain sockets */
1538 struct ForeignAddressList *unix_address = NULL;
1540 best_address = NULL;
1541 while (head != NULL)
1543 addresses = head->addresses;
1544 while (addresses != NULL)
1546 if ( (addresses->timeout.abs_value < now.abs_value) &&
1547 (addresses->connected == GNUNET_YES) )
1550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1551 "Marking long-time inactive connection to `%4s' as down.\n",
1552 GNUNET_i2s (&neighbour->id));
1554 GNUNET_STATISTICS_update (stats,
1555 gettext_noop ("# connected addresses"),
1558 addresses->connected = GNUNET_NO;
1560 addresses = addresses->next;
1563 addresses = head->addresses;
1564 while (addresses != NULL)
1566 #if DEBUG_TRANSPORT > 1
1567 if (addresses->addr != NULL)
1568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1569 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1570 a2s (head->plugin->short_name,
1572 addresses->addrlen),
1573 GNUNET_i2s (&neighbour->id),
1574 addresses->connected,
1575 addresses->in_transmit,
1576 addresses->validated,
1577 addresses->connect_attempts,
1578 (unsigned long long) addresses->timeout.abs_value,
1579 (unsigned int) addresses->distance);
1581 if (0==strcmp(head->plugin->short_name,"unix"))
1583 if ((unix_address == NULL) || ((unix_address != NULL) &&
1584 (addresses->latency.rel_value < unix_address->latency.rel_value)))
1585 unix_address = addresses;
1587 if ( ( (best_address == NULL) ||
1588 (addresses->connected == GNUNET_YES) ||
1589 (best_address->connected == GNUNET_NO) ) &&
1590 (addresses->in_transmit == GNUNET_NO) &&
1591 ( (best_address == NULL) ||
1592 (addresses->latency.rel_value < best_address->latency.rel_value)) )
1593 best_address = addresses;
1594 /* FIXME: also give lower-latency addresses that are not
1595 connected a chance some times... */
1596 addresses = addresses->next;
1598 if (unix_address != NULL)
1602 if (unix_address != NULL)
1604 best_address = unix_address;
1606 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found unix address, forced this address\n");
1609 if (best_address != NULL)
1613 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1614 "Best address found (`%s') has latency of %llu ms.\n",
1615 (best_address->addrlen > 0)
1616 ? a2s (best_address->ready_list->plugin->short_name,
1618 best_address->addrlen)
1620 best_address->latency.rel_value);
1625 GNUNET_STATISTICS_update (stats,
1626 gettext_noop ("# transmission attempts failed (no address)"),
1631 return best_address;
1637 * We should re-try transmitting to the given peer,
1638 * hopefully we've learned something in the meantime.
1641 retry_transmission_task (void *cls,
1642 const struct GNUNET_SCHEDULER_TaskContext *tc)
1644 struct NeighbourList *n = cls;
1646 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1647 try_transmission_to_peer (n);
1652 * Check the ready list for the given neighbour and if a plugin is
1653 * ready for transmission (and if we have a message), do so!
1655 * @param neighbour target peer for which to transmit
1658 try_transmission_to_peer (struct NeighbourList *n)
1660 struct ReadyList *rl;
1661 struct MessageQueue *mq;
1662 struct GNUNET_TIME_Relative timeout;
1666 if (n->messages_head == NULL)
1669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1670 "Transmission queue for `%4s' is empty\n",
1671 GNUNET_i2s (&neighbour->id));
1673 return; /* nothing to do */
1676 mq = n->messages_head;
1677 force_address = GNUNET_YES;
1678 if (mq->specific_address == NULL)
1681 mq->specific_address = ats_get_preferred_address(n);
1682 GNUNET_STATISTICS_update (stats,
1683 gettext_noop ("# transport selected peer address freely"),
1686 force_address = GNUNET_NO;
1688 if (mq->specific_address == NULL)
1690 GNUNET_STATISTICS_update (stats,
1691 gettext_noop ("# transport failed to selected peer address"),
1694 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1695 if (timeout.rel_value == 0)
1698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699 "No destination address available to transmit message of size %u to peer `%4s'\n",
1700 mq->message_buf_size,
1701 GNUNET_i2s (&mq->neighbour_id));
1703 GNUNET_STATISTICS_update (stats,
1704 gettext_noop ("# bytes in message queue for other peers"),
1705 - (int64_t) mq->message_buf_size,
1707 GNUNET_STATISTICS_update (stats,
1708 gettext_noop ("# bytes discarded (no destination address available)"),
1709 mq->message_buf_size,
1711 if (mq->client != NULL)
1712 transmit_send_ok (mq->client, n, &n->id, GNUNET_NO);
1713 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1717 return; /* nobody ready */
1719 GNUNET_STATISTICS_update (stats,
1720 gettext_noop ("# message delivery deferred (no address)"),
1723 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1724 GNUNET_SCHEDULER_cancel (n->retry_task);
1725 n->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
1726 &retry_transmission_task,
1729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1730 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1731 mq->message_buf_size,
1732 GNUNET_i2s (&mq->neighbour_id),
1735 /* FIXME: might want to trigger peerinfo lookup here
1736 (unless that's already pending...) */
1739 GNUNET_CONTAINER_DLL_remove (n->messages_head,
1742 if (mq->specific_address->connected == GNUNET_NO)
1743 mq->specific_address->connect_attempts++;
1744 rl = mq->specific_address->ready_list;
1745 mq->plugin = rl->plugin;
1746 if (!mq->internal_msg)
1747 mq->specific_address->in_transmit = GNUNET_YES;
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1750 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1751 mq->message_buf_size,
1752 GNUNET_i2s (&neighbour->id),
1753 (mq->specific_address->addr != NULL)
1754 ? a2s (mq->plugin->short_name,
1755 mq->specific_address->addr,
1756 mq->specific_address->addrlen)
1758 rl->plugin->short_name);
1760 GNUNET_STATISTICS_update (stats,
1761 gettext_noop ("# bytes in message queue for other peers"),
1762 - (int64_t) mq->message_buf_size,
1764 GNUNET_STATISTICS_update (stats,
1765 gettext_noop ("# bytes pending with plugins"),
1766 mq->message_buf_size,
1768 ret = rl->plugin->api->send (rl->plugin->api->cls,
1771 mq->message_buf_size,
1773 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1774 mq->specific_address->session,
1775 mq->specific_address->addr,
1776 mq->specific_address->addrlen,
1778 &transmit_send_continuation, mq);
1781 /* failure, but 'send' would not call continuation in this case,
1782 so we need to do it here! */
1783 transmit_send_continuation (mq,
1791 * Send the specified message to the specified peer.
1793 * @param client source of the transmission request (can be NULL)
1794 * @param peer_address ForeignAddressList where we should send this message
1795 * @param priority how important is the message
1796 * @param timeout how long do we have to transmit?
1797 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1798 * @param message_buf_size total size of all messages in message_buf
1799 * @param is_internal is this an internal message; these are pre-pended and
1800 * also do not count for plugins being "ready" to transmit
1801 * @param neighbour handle to the neighbour for transmission
1804 transmit_to_peer (struct TransportClient *client,
1805 struct ForeignAddressList *peer_address,
1806 unsigned int priority,
1807 struct GNUNET_TIME_Relative timeout,
1808 const char *message_buf,
1809 size_t message_buf_size,
1810 int is_internal, struct NeighbourList *neighbour)
1812 struct MessageQueue *mq;
1817 /* check for duplicate submission */
1818 mq = neighbour->messages_head;
1821 if (mq->client == client)
1823 /* client transmitted to same peer twice
1824 before getting SEND_OK! */
1832 GNUNET_STATISTICS_update (stats,
1833 gettext_noop ("# bytes in message queue for other peers"),
1836 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1837 mq->specific_address = peer_address;
1838 mq->client = client;
1839 /* FIXME: this memcpy can be up to 7% of our total runtime! */
1840 memcpy (&mq[1], message_buf, message_buf_size);
1841 mq->message_buf = (const char*) &mq[1];
1842 mq->message_buf_size = message_buf_size;
1843 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1844 mq->internal_msg = is_internal;
1845 mq->priority = priority;
1846 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1848 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1849 neighbour->messages_tail,
1852 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1853 neighbour->messages_tail,
1854 neighbour->messages_tail,
1856 try_transmission_to_peer (neighbour);
1863 struct GeneratorContext
1865 struct TransportPlugin *plug_pos;
1866 struct OwnAddressList *addr_pos;
1867 struct GNUNET_TIME_Absolute expiration;
1875 address_generator (void *cls, size_t max, void *buf)
1877 struct GeneratorContext *gc = cls;
1880 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1882 gc->plug_pos = gc->plug_pos->next;
1883 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1885 if (NULL == gc->plug_pos)
1890 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1893 gc->addr_pos->addrlen, buf, max);
1894 gc->addr_pos = gc->addr_pos->next;
1900 * Construct our HELLO message from all of the addresses of
1901 * all of the transports.
1906 struct GNUNET_HELLO_Message *hello;
1907 struct TransportClient *cpos;
1908 struct NeighbourList *npos;
1909 struct GeneratorContext gc;
1911 gc.plug_pos = plugins;
1912 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1913 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1914 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1917 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1919 GNUNET_STATISTICS_update (stats,
1920 gettext_noop ("# refreshed my HELLO"),
1924 while (cpos != NULL)
1926 transmit_to_client (cpos,
1927 (const struct GNUNET_MessageHeader *) hello,
1932 GNUNET_free_non_null (our_hello);
1934 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1936 while (npos != NULL)
1939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1940 "Transmitting updated `%s' to neighbour `%4s'\n",
1941 "HELLO", GNUNET_i2s (&npos->id));
1943 GNUNET_STATISTICS_update (stats,
1944 gettext_noop ("# transmitted my HELLO to other peers"),
1947 transmit_to_peer (NULL, NULL, 0,
1948 HELLO_ADDRESS_EXPIRATION,
1949 (const char *) our_hello,
1950 GNUNET_HELLO_size(our_hello),
1958 * Task used to clean up expired addresses for a plugin.
1960 * @param cls closure
1964 expire_address_task (void *cls,
1965 const struct GNUNET_SCHEDULER_TaskContext *tc);
1969 * Update the list of addresses for this plugin,
1970 * expiring those that are past their expiration date.
1972 * @param plugin addresses of which plugin should be recomputed?
1973 * @param fresh set to GNUNET_YES if a new address was added
1974 * and we need to regenerate the HELLO even if nobody
1978 update_addresses (struct TransportPlugin *plugin,
1981 static struct GNUNET_TIME_Absolute last_update;
1982 struct GNUNET_TIME_Relative min_remaining;
1983 struct GNUNET_TIME_Relative remaining;
1984 struct GNUNET_TIME_Absolute now;
1985 struct OwnAddressList *pos;
1986 struct OwnAddressList *prev;
1987 struct OwnAddressList *next;
1990 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1991 GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1992 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1993 now = GNUNET_TIME_absolute_get ();
1994 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1995 expired = (GNUNET_TIME_absolute_get_duration (last_update).rel_value > (HELLO_ADDRESS_EXPIRATION.rel_value / 4));
1997 pos = plugin->addresses;
2001 if (pos->expires.abs_value < now.abs_value)
2003 expired = GNUNET_YES;
2005 plugin->addresses = pos->next;
2007 prev->next = pos->next;
2012 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
2013 if (remaining.rel_value < min_remaining.rel_value)
2014 min_remaining = remaining;
2020 if (expired || fresh)
2025 min_remaining = GNUNET_TIME_relative_min (min_remaining,
2026 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
2028 plugin->address_update_task
2029 = GNUNET_SCHEDULER_add_delayed (min_remaining,
2030 &expire_address_task, plugin);
2035 * Task used to clean up expired addresses for a plugin.
2037 * @param cls closure
2041 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2043 struct TransportPlugin *plugin = cls;
2045 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
2046 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2047 update_addresses (plugin, GNUNET_NO);
2052 * Iterator over hash map entries that NULLs the session of validation
2053 * entries that match the given session.
2055 * @param cls closure (the 'struct Session*' to match against)
2056 * @param key current key code (peer ID, not used)
2057 * @param value value in the hash map ('struct ValidationEntry*')
2058 * @return GNUNET_YES (we should continue to iterate)
2061 remove_session_validations (void *cls,
2062 const GNUNET_HashCode * key,
2065 struct Session *session = cls;
2066 struct ValidationEntry *ve = value;
2068 if (session == ve->session)
2075 * We've been disconnected from the other peer (for some
2076 * connection-oriented transport). Either quickly
2077 * re-establish the connection or signal the disconnect
2080 * Only signal CORE level disconnect if ALL addresses
2081 * for the peer are exhausted.
2083 * @param p overall plugin context
2084 * @param nl neighbour that was disconnected
2087 try_fast_reconnect (struct TransportPlugin *p,
2088 struct NeighbourList *nl)
2090 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2091 /* Note: the idea here is to hide problems with transports (or
2092 switching between plugins) from the core to eliminate the need to
2093 re-negotiate session keys and the like; OTOH, we should tell core
2094 quickly (much faster than timeout) `if a connection was lost and
2095 could not be re-established (i.e. other peer went down or is
2096 unable / refuses to communicate);
2098 So we should consider:
2099 1) ideally: our own willingness / need to connect
2100 2) prior failures to connect to this peer (by plugin)
2101 3) ideally: reasons why other peer terminated (as far as knowable)
2103 Most importantly, it must be POSSIBLE for another peer to terminate
2104 a connection for a while (without us instantly re-establishing it).
2105 Similarly, if another peer is gone we should quickly notify CORE.
2106 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2107 on the other end), we should reconnect in such a way that BOTH CORE
2108 services never even notice.
2109 Furthermore, the same mechanism (or small variation) could be used
2110 to switch to a better-performing plugin (ATS).
2112 Finally, this needs to be tested throughly... */
2115 * GNUNET_NO in the call below makes transport disconnect the peer,
2116 * even if only a single address (out of say, six) went away. This
2117 * function must be careful to ONLY disconnect if the peer is gone,
2118 * not just a specifi address.
2120 * More specifically, half the places it was used had it WRONG.
2123 /* No reconnect, signal disconnect instead! */
2124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2125 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2126 "try_fast_reconnect");
2127 disconnect_neighbour (nl, GNUNET_YES);
2132 * Function that will be called whenever the plugin internally
2133 * cleans up a session pointer and hence the service needs to
2134 * discard all of those sessions as well. Plugins that do not
2135 * use sessions can simply omit calling this function and always
2136 * use NULL wherever a session pointer is needed.
2138 * @param cls closure
2139 * @param peer which peer was the session for
2140 * @param session which session is being destoyed
2143 plugin_env_session_end (void *cls,
2144 const struct GNUNET_PeerIdentity *peer,
2145 struct Session *session)
2147 struct TransportPlugin *p = cls;
2148 struct NeighbourList *nl;
2149 struct ReadyList *rl;
2150 struct ForeignAddressList *pos;
2151 struct ForeignAddressList *prev;
2153 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2154 &remove_session_validations,
2156 nl = find_neighbour (peer);
2158 return; /* was never marked as connected */
2162 if (rl->plugin == p)
2167 return; /* was never marked as connected */
2169 pos = rl->addresses;
2170 while ( (pos != NULL) &&
2171 (pos->session != session) )
2177 return; /* was never marked as connected */
2178 pos->session = NULL;
2179 if (pos->addrlen != 0)
2181 if (nl->received_pong != GNUNET_NO)
2182 try_fast_reconnect (p, nl);
2185 /* was inbound connection, free 'pos' */
2187 rl->addresses = pos->next;
2189 prev->next = pos->next;
2190 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2192 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2193 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2196 if (nl->received_pong == GNUNET_NO)
2197 return; /* nothing to do, never connected... */
2198 /* check if we have any validated addresses left */
2199 pos = rl->addresses;
2204 try_fast_reconnect (p, nl);
2209 /* no valid addresses left, signal disconnect! */
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2213 "plugin_env_session_end");
2214 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2215 * it means there aren't any left for this PLUGIN/PEER combination! So
2216 * calling disconnect_neighbor here with GNUNET_NO forces disconnect
2217 * when it isn't necessary. Using GNUNET_YES at least checks to see
2218 * if there are any addresses that work first, so as not to overdo it.
2221 disconnect_neighbour (nl, GNUNET_YES);
2226 * Function that must be called by each plugin to notify the
2227 * transport service about the addresses under which the transport
2228 * provided by the plugin can be reached.
2230 * @param cls closure
2231 * @param name name of the transport that generated the address
2232 * @param addr one of the addresses of the host, NULL for the last address
2233 * the specific address format depends on the transport
2234 * @param addrlen length of the address
2235 * @param expires when should this address automatically expire?
2238 plugin_env_notify_address (void *cls,
2242 struct GNUNET_TIME_Relative expires)
2244 struct TransportPlugin *p = cls;
2245 struct OwnAddressList *al;
2246 struct GNUNET_TIME_Absolute abex;
2248 GNUNET_assert (addr != NULL);
2249 abex = GNUNET_TIME_relative_to_absolute (expires);
2250 GNUNET_assert (p == find_transport (name));
2254 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2257 update_addresses (p, GNUNET_NO);
2263 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2264 al->next = p->addresses;
2267 al->addrlen = addrlen;
2268 memcpy (&al[1], addr, addrlen);
2269 update_addresses (p, GNUNET_YES);
2274 * Notify all of our clients about a peer connecting.
2277 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2278 struct GNUNET_TIME_Relative latency,
2281 struct ConnectInfoMessage * cim;
2282 struct TransportClient *cpos;
2287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2288 "Notifying clients about connection from `%s'\n",
2291 GNUNET_STATISTICS_update (stats,
2292 gettext_noop ("# peers connected"),
2297 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2298 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2302 cim = GNUNET_malloc (size);
2304 cim->header.size = htons (size);
2305 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2306 cim->ats_count = htonl(2);
2307 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2308 (&(cim->ats))[0].value = htonl (distance);
2309 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2310 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2311 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2312 (&(cim->ats))[2].value = htonl (0);
2313 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2315 /* notify ats about connecting peer */
2316 ats_notify_peer_connect (peer, &(cim->ats));
2319 while (cpos != NULL)
2321 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2330 * Notify all of our clients about a peer disconnecting.
2333 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2335 struct DisconnectInfoMessage dim;
2336 struct TransportClient *cpos;
2339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2340 "Notifying clients about lost connection to `%s'\n",
2343 GNUNET_STATISTICS_update (stats,
2344 gettext_noop ("# peers connected"),
2347 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2348 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2349 dim.reserved = htonl (0);
2350 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2352 /* notify ats about connecting peer */
2353 ats_notify_peer_disconnect (peer);
2356 while (cpos != NULL)
2358 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2365 * Find a ForeignAddressList entry for the given neighbour
2366 * that matches the given address and transport.
2368 * @param neighbour which peer we care about
2369 * @param tname name of the transport plugin
2370 * @param session session to look for, NULL for 'any'; otherwise
2371 * can be used for the service to "learn" this session ID
2373 * @param addr binary address
2374 * @param addrlen length of addr
2375 * @return NULL if no such entry exists
2377 static struct ForeignAddressList *
2378 find_peer_address(struct NeighbourList *neighbour,
2380 struct Session *session,
2384 struct ReadyList *head;
2385 struct ForeignAddressList *pos;
2387 head = neighbour->plugins;
2388 while (head != NULL)
2390 if (0 == strcmp (tname, head->plugin->short_name))
2396 pos = head->addresses;
2397 while ( (pos != NULL) &&
2398 ( (pos->addrlen != addrlen) ||
2399 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2401 if ( (session != NULL) &&
2402 (pos->session == session) )
2406 if ( (session != NULL) && (pos != NULL) )
2407 pos->session = session; /* learn it! */
2413 * Get the peer address struct for the given neighbour and
2414 * address. If it doesn't yet exist, create it.
2416 * @param neighbour which peer we care about
2417 * @param tname name of the transport plugin
2418 * @param session session of the plugin, or NULL for none
2419 * @param addr binary address
2420 * @param addrlen length of addr
2421 * @return NULL if we do not have a transport plugin for 'tname'
2423 static struct ForeignAddressList *
2424 add_peer_address (struct NeighbourList *neighbour,
2426 struct Session *session,
2430 struct ReadyList *head;
2431 struct ForeignAddressList *ret;
2433 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2436 head = neighbour->plugins;
2438 while (head != NULL)
2440 if (0 == strcmp (tname, head->plugin->short_name))
2446 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2447 ret->session = session;
2450 ret->addr = (const char*) &ret[1];
2451 memcpy (&ret[1], addr, addrlen);
2457 ret->addrlen = addrlen;
2458 ret->expires = GNUNET_TIME_relative_to_absolute
2459 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2460 ret->latency = GNUNET_TIME_relative_get_forever();
2462 ret->timeout = GNUNET_TIME_relative_to_absolute
2463 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2464 ret->ready_list = head;
2465 ret->next = head->addresses;
2466 head->addresses = ret;
2472 * Closure for 'add_validated_address'.
2474 struct AddValidatedAddressContext
2477 * Entry that has been validated.
2479 const struct ValidationEntry *ve;
2482 * Flag set after we have added the address so
2483 * that we terminate the iteration next time.
2490 * Callback function used to fill a buffer of max bytes with a list of
2491 * addresses in the format used by HELLOs. Should use
2492 * "GNUNET_HELLO_add_address" as a helper function.
2494 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2495 * @param max maximum number of bytes that can be written to buf
2496 * @param buf where to write the address information
2497 * @return number of bytes written, 0 to signal the
2498 * end of the iteration.
2501 add_validated_address (void *cls,
2502 size_t max, void *buf)
2504 struct AddValidatedAddressContext *avac = cls;
2505 const struct ValidationEntry *ve = avac->ve;
2507 if (GNUNET_YES == avac->done)
2509 avac->done = GNUNET_YES;
2510 return GNUNET_HELLO_add_address (ve->transport_name,
2511 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2521 * Closure for 'check_address_exists'.
2523 struct CheckAddressExistsClosure
2526 * Address to check for.
2531 * Name of the transport.
2538 struct Session *session;
2541 * Set to GNUNET_YES if the address exists.
2554 * Iterator over hash map entries. Checks if the given
2555 * validation entry is for the same address as what is given
2558 * @param cls the 'struct CheckAddressExistsClosure*'
2559 * @param key current key code (ignored)
2560 * @param value value in the hash map ('struct ValidationEntry')
2561 * @return GNUNET_YES if we should continue to
2562 * iterate (mismatch), GNUNET_NO if not (entry matched)
2565 check_address_exists (void *cls,
2566 const GNUNET_HashCode * key,
2569 struct CheckAddressExistsClosure *caec = cls;
2570 struct ValidationEntry *ve = value;
2572 if ( (0 == strcmp (caec->tname,
2573 ve->transport_name)) &&
2574 (caec->addrlen == ve->addrlen) &&
2575 (0 == memcmp (caec->addr,
2579 caec->exists = GNUNET_YES;
2582 if ( (ve->session != NULL) &&
2583 (caec->session == ve->session) )
2585 caec->exists = GNUNET_YES;
2594 * Iterator to free entries in the validation_map.
2596 * @param cls closure (unused)
2597 * @param key current key code
2598 * @param value value in the hash map (validation to abort)
2599 * @return GNUNET_YES (always)
2602 abort_validation (void *cls,
2603 const GNUNET_HashCode * key,
2606 struct ValidationEntry *va = value;
2608 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2609 GNUNET_SCHEDULER_cancel (va->timeout_task);
2610 GNUNET_free (va->transport_name);
2611 if (va->chvc != NULL)
2613 va->chvc->ve_count--;
2614 if (va->chvc->ve_count == 0)
2616 GNUNET_CONTAINER_DLL_remove (chvc_head,
2619 GNUNET_free (va->chvc);
2629 * HELLO validation cleanup task (validation failed).
2631 * @param cls the 'struct ValidationEntry' that failed
2632 * @param tc scheduler context (unused)
2635 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2637 struct ValidationEntry *va = cls;
2638 struct GNUNET_PeerIdentity pid;
2640 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2641 GNUNET_STATISTICS_update (stats,
2642 gettext_noop ("# address validation timeouts"),
2645 GNUNET_CRYPTO_hash (&va->publicKey,
2647 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2649 GNUNET_break (GNUNET_OK ==
2650 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2653 abort_validation (NULL, NULL, va);
2658 neighbour_timeout_task (void *cls,
2659 const struct GNUNET_SCHEDULER_TaskContext *tc)
2661 struct NeighbourList *n = cls;
2664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2665 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2667 GNUNET_STATISTICS_update (stats,
2668 gettext_noop ("# disconnects due to timeout"),
2671 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2672 disconnect_neighbour (n, GNUNET_NO);
2677 * Schedule the job that will cause us to send a PING to the
2678 * foreign address to evaluate its validity and latency.
2680 * @param fal address to PING
2683 schedule_next_ping (struct ForeignAddressList *fal);
2687 * Add the given address to the list of foreign addresses
2688 * available for the given peer (check for duplicates).
2690 * @param cls the respective 'struct NeighbourList' to update
2691 * @param tname name of the transport
2692 * @param expiration expiration time
2693 * @param addr the address
2694 * @param addrlen length of the address
2695 * @return GNUNET_OK (always)
2698 add_to_foreign_address_list (void *cls,
2700 struct GNUNET_TIME_Absolute expiration,
2704 struct NeighbourList *n = cls;
2705 struct ForeignAddressList *fal;
2708 GNUNET_STATISTICS_update (stats,
2709 gettext_noop ("# valid peer addresses returned by PEERINFO"),
2713 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2716 #if DEBUG_TRANSPORT_HELLO
2717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2718 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2719 a2s (tname, addr, addrlen),
2721 GNUNET_i2s (&n->id),
2722 expiration.abs_value);
2724 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2727 GNUNET_STATISTICS_update (stats,
2728 gettext_noop ("# previously validated addresses lacking transport"),
2734 fal->expires = GNUNET_TIME_absolute_max (expiration,
2736 schedule_next_ping (fal);
2742 fal->expires = GNUNET_TIME_absolute_max (expiration,
2747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748 "Failed to add new address for `%4s'\n",
2749 GNUNET_i2s (&n->id));
2752 if (fal->validated == GNUNET_NO)
2754 fal->validated = GNUNET_YES;
2755 GNUNET_STATISTICS_update (stats,
2756 gettext_noop ("# peer addresses considered valid"),
2760 if (try == GNUNET_YES)
2762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 "Have new addresses, will try to trigger transmissions.\n");
2764 try_transmission_to_peer (n);
2771 * Add addresses in validated HELLO "h" to the set of addresses
2772 * we have for this peer.
2774 * @param cls closure ('struct NeighbourList*')
2775 * @param peer id of the peer, NULL for last call
2776 * @param h hello message for the peer (can be NULL)
2777 * @param err_msg NULL if successful, otherwise contains error message
2780 add_hello_for_peer (void *cls,
2781 const struct GNUNET_PeerIdentity *peer,
2782 const struct GNUNET_HELLO_Message *h,
2783 const char *err_msg)
2785 struct NeighbourList *n = cls;
2787 if (err_msg != NULL)
2789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2790 _("Error in communication with PEERINFO service\n"));
2795 GNUNET_STATISTICS_update (stats,
2796 gettext_noop ("# outstanding peerinfo iterate requests"),
2803 return; /* no HELLO available */
2805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2806 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2810 if (GNUNET_YES != n->public_key_valid)
2812 GNUNET_HELLO_get_key (h, &n->publicKey);
2813 n->public_key_valid = GNUNET_YES;
2815 GNUNET_HELLO_iterate_addresses (h,
2817 &add_to_foreign_address_list,
2823 * Create a fresh entry in our neighbour list for the given peer.
2824 * Will try to transmit our current HELLO to the new neighbour.
2825 * Do not call this function directly, use 'setup_peer_check_blacklist.
2827 * @param peer the peer for which we create the entry
2828 * @param do_hello should we schedule transmitting a HELLO
2829 * @return the new neighbour list entry
2831 static struct NeighbourList *
2832 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2835 struct NeighbourList *n;
2836 struct TransportPlugin *tp;
2837 struct ReadyList *rl;
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "Setting up state for neighbour `%4s'\n",
2844 GNUNET_assert (our_hello != NULL);
2845 GNUNET_STATISTICS_update (stats,
2846 gettext_noop ("# active neighbours"),
2849 n = GNUNET_malloc (sizeof (struct NeighbourList));
2850 n->next = neighbours;
2854 GNUNET_TIME_relative_to_absolute
2855 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2856 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2857 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2858 MAX_BANDWIDTH_CARRY_S);
2862 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2864 rl = GNUNET_malloc (sizeof (struct ReadyList));
2866 rl->next = n->plugins;
2869 rl->addresses = NULL;
2873 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2875 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2876 &neighbour_timeout_task, n);
2879 GNUNET_STATISTICS_update (stats,
2880 gettext_noop ("# peerinfo new neighbor iterate requests"),
2883 GNUNET_STATISTICS_update (stats,
2884 gettext_noop ("# outstanding peerinfo iterate requests"),
2887 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2888 GNUNET_TIME_UNIT_FOREVER_REL,
2889 &add_hello_for_peer, n);
2891 GNUNET_STATISTICS_update (stats,
2892 gettext_noop ("# HELLO's sent to new neighbors"),
2895 transmit_to_peer (NULL, NULL, 0,
2896 HELLO_ADDRESS_EXPIRATION,
2897 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2905 * Function called after we have checked if communicating
2906 * with a given peer is acceptable.
2908 * @param cls closure
2909 * @param n NULL if communication is not acceptable
2911 typedef void (*SetupContinuation)(void *cls,
2912 struct NeighbourList *n);
2916 * Information kept for each client registered to perform
2922 * This is a linked list.
2924 struct Blacklisters *next;
2927 * This is a linked list.
2929 struct Blacklisters *prev;
2932 * Client responsible for this entry.
2934 struct GNUNET_SERVER_Client *client;
2937 * Blacklist check that we're currently performing.
2939 struct BlacklistCheck *bc;
2945 * Head of DLL of blacklisting clients.
2947 static struct Blacklisters *bl_head;
2950 * Tail of DLL of blacklisting clients.
2952 static struct Blacklisters *bl_tail;
2956 * Context we use when performing a blacklist check.
2958 struct BlacklistCheck
2962 * This is a linked list.
2964 struct BlacklistCheck *next;
2967 * This is a linked list.
2969 struct BlacklistCheck *prev;
2972 * Peer being checked.
2974 struct GNUNET_PeerIdentity peer;
2977 * Option for setup neighbour afterwards.
2982 * Continuation to call with the result.
2984 SetupContinuation cont;
2992 * Current transmission request handle for this client, or NULL if no
2993 * request is pending.
2995 struct GNUNET_CONNECTION_TransmitHandle *th;
2998 * Our current position in the blacklisters list.
3000 struct Blacklisters *bl_pos;
3003 * Current task performing the check.
3005 GNUNET_SCHEDULER_TaskIdentifier task;
3010 * Head of DLL of active blacklisting queries.
3012 static struct BlacklistCheck *bc_head;
3015 * Tail of DLL of active blacklisting queries.
3017 static struct BlacklistCheck *bc_tail;
3021 * Perform next action in the blacklist check.
3023 * @param cls the 'struct BlacklistCheck*'
3027 do_blacklist_check (void *cls,
3028 const struct GNUNET_SCHEDULER_TaskContext *tc);
3031 * Transmit blacklist query to the client.
3033 * @param cls the 'struct BlacklistCheck'
3034 * @param size number of bytes allowed
3035 * @param buf where to copy the message
3036 * @return number of bytes copied to buf
3039 transmit_blacklist_message (void *cls,
3043 struct BlacklistCheck *bc = cls;
3044 struct Blacklisters *bl;
3045 struct BlacklistMessage bm;
3050 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3051 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3056 bm.header.size = htons (sizeof (struct BlacklistMessage));
3057 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3058 bm.is_allowed = htonl (0);
3060 memcpy (buf, &bm, sizeof (bm));
3061 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3067 * Perform next action in the blacklist check.
3069 * @param cls the 'struct BlacklistCheck*'
3073 do_blacklist_check (void *cls,
3074 const struct GNUNET_SCHEDULER_TaskContext *tc)
3076 struct BlacklistCheck *bc = cls;
3077 struct Blacklisters *bl;
3079 bc->task = GNUNET_SCHEDULER_NO_TASK;
3083 bc->cont (bc->cont_cls,
3084 setup_new_neighbour (&bc->peer, bc->do_hello));
3091 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3092 sizeof (struct BlacklistMessage),
3093 GNUNET_TIME_UNIT_FOREVER_REL,
3094 &transmit_blacklist_message,
3101 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3102 * does not yet exist, check the blacklist. If the blacklist says creating
3103 * one is acceptable, create one and call the continuation; otherwise
3104 * call the continuation with NULL.
3106 * @param peer peer to setup or look up a struct NeighbourList for
3107 * @param do_hello should we also schedule sending our HELLO to the peer
3108 * if this is a new record
3109 * @param cont function to call with the 'struct NeigbhbourList*'
3110 * @param cont_cls closure for cont
3113 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3115 SetupContinuation cont,
3118 struct NeighbourList *n;
3119 struct BlacklistCheck *bc;
3121 n = find_neighbour(peer);
3128 if (bl_head == NULL)
3131 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3133 setup_new_neighbour(peer, do_hello);
3136 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3137 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3139 bc->do_hello = do_hello;
3141 bc->cont_cls = cont_cls;
3142 bc->bl_pos = bl_head;
3143 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3149 * Function called with the result of querying a new blacklister about
3150 * it being allowed (or not) to continue to talk to an existing neighbour.
3152 * @param cls the original 'struct NeighbourList'
3153 * @param n NULL if we need to disconnect
3156 confirm_or_drop_neighbour (void *cls,
3157 struct NeighbourList *n)
3159 struct NeighbourList * orig = cls;
3163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3164 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3165 "confirm_or_drop_neighboUr");
3166 disconnect_neighbour (orig, GNUNET_NO);
3172 * Handle a request to start a blacklist.
3174 * @param cls closure (always NULL)
3175 * @param client identification of the client
3176 * @param message the actual message
3179 handle_blacklist_init (void *cls,
3180 struct GNUNET_SERVER_Client *client,
3181 const struct GNUNET_MessageHeader *message)
3183 struct Blacklisters *bl;
3184 struct BlacklistCheck *bc;
3185 struct NeighbourList *n;
3190 if (bl->client == client)
3193 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3198 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3199 bl->client = client;
3200 GNUNET_SERVER_client_keep (client);
3201 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3202 /* confirm that all existing connections are OK! */
3206 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3207 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3209 bc->do_hello = GNUNET_NO;
3210 bc->cont = &confirm_or_drop_neighbour;
3213 if (n == neighbours) /* all would wait for the same client, no need to
3214 create more than just the first task right now */
3215 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3223 * Handle a request to blacklist a peer.
3225 * @param cls closure (always NULL)
3226 * @param client identification of the client
3227 * @param message the actual message
3230 handle_blacklist_reply (void *cls,
3231 struct GNUNET_SERVER_Client *client,
3232 const struct GNUNET_MessageHeader *message)
3234 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3235 struct Blacklisters *bl;
3236 struct BlacklistCheck *bc;
3239 while ( (bl != NULL) &&
3240 (bl->client != client) )
3244 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3249 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3251 bc->cont (bc->cont_cls, NULL);
3252 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3257 bc->bl_pos = bc->bl_pos->next;
3258 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3261 /* check if any other bc's are waiting for this blacklister */
3265 if ( (bc->bl_pos == bl) &&
3266 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3267 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3275 * Send periodic PING messages to a given foreign address.
3277 * @param cls our 'struct PeriodicValidationContext*'
3278 * @param tc task context
3281 send_periodic_ping (void *cls,
3282 const struct GNUNET_SCHEDULER_TaskContext *tc)
3284 struct ForeignAddressList *peer_address = cls;
3285 struct TransportPlugin *tp;
3286 struct ValidationEntry *va;
3287 struct NeighbourList *neighbour;
3288 struct TransportPingMessage ping;
3289 struct CheckAddressExistsClosure caec;
3291 uint16_t hello_size;
3295 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3296 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3298 tp = peer_address->ready_list->plugin;
3299 neighbour = peer_address->ready_list->neighbour;
3300 if (GNUNET_YES != neighbour->public_key_valid)
3302 /* no public key yet, try again later */
3303 schedule_next_ping (peer_address);
3306 caec.addr = peer_address->addr;
3307 caec.addrlen = peer_address->addrlen;
3308 caec.tname = tp->short_name;
3309 caec.session = peer_address->session;
3310 caec.exists = GNUNET_NO;
3311 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3312 &check_address_exists,
3314 if (caec.exists == GNUNET_YES)
3316 /* During validation attempts we will likely trigger the other
3317 peer trying to validate our address which in turn will cause
3318 it to send us its HELLO, so we expect to hit this case rather
3319 frequently. Only print something if we are very verbose. */
3320 #if DEBUG_TRANSPORT > 1
3321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3322 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3323 (peer_address->addr != NULL)
3324 ? a2s (tp->short_name,
3326 peer_address->addrlen)
3329 GNUNET_i2s (&neighbour->id));
3331 schedule_next_ping (peer_address);
3334 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3335 va->transport_name = GNUNET_strdup (tp->short_name);
3336 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3338 va->send_time = GNUNET_TIME_absolute_get();
3339 va->session = peer_address->session;
3340 if (peer_address->addr != NULL)
3342 va->addr = (const void*) &va[1];
3343 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3344 va->addrlen = peer_address->addrlen;
3346 memcpy(&va->publicKey,
3347 &neighbour->publicKey,
3348 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3350 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3351 &timeout_hello_validation,
3353 GNUNET_CONTAINER_multihashmap_put (validation_map,
3354 &neighbour->id.hashPubKey,
3356 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3358 if (peer_address->validated != GNUNET_YES)
3359 hello_size = GNUNET_HELLO_size(our_hello);
3363 tsize = sizeof(struct TransportPingMessage) + hello_size;
3365 if (peer_address->addr != NULL)
3367 slen = strlen (tp->short_name) + 1;
3368 tsize += slen + peer_address->addrlen;
3372 slen = 0; /* make gcc happy */
3374 message_buf = GNUNET_malloc(tsize);
3375 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3376 ping.challenge = htonl(va->challenge);
3377 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3378 if (peer_address->validated != GNUNET_YES)
3380 memcpy(message_buf, our_hello, hello_size);
3383 if (peer_address->addr != NULL)
3385 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3386 peer_address->addrlen +
3388 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3391 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3393 peer_address->addrlen);
3397 ping.header.size = htons(sizeof(struct TransportPingMessage));
3400 memcpy(&message_buf[hello_size],
3402 sizeof(struct TransportPingMessage));
3404 #if DEBUG_TRANSPORT_REVALIDATION
3405 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3406 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3407 (peer_address->addr != NULL)
3408 ? a2s (peer_address->plugin->short_name,
3410 peer_address->addrlen)
3413 GNUNET_i2s (&neighbour->id),
3414 "HELLO", hello_size,
3417 if (peer_address->validated != GNUNET_YES)
3418 GNUNET_STATISTICS_update (stats,
3419 gettext_noop ("# PING with HELLO messages sent"),
3423 GNUNET_STATISTICS_update (stats,
3424 gettext_noop ("# PING without HELLO messages sent"),
3427 GNUNET_STATISTICS_update (stats,
3428 gettext_noop ("# PING messages sent for re-validation"),
3431 transmit_to_peer (NULL, peer_address,
3432 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3433 HELLO_VERIFICATION_TIMEOUT,
3435 GNUNET_YES, neighbour);
3436 GNUNET_free(message_buf);
3437 schedule_next_ping (peer_address);
3442 * Schedule the job that will cause us to send a PING to the
3443 * foreign address to evaluate its validity and latency.
3445 * @param fal address to PING
3448 schedule_next_ping (struct ForeignAddressList *fal)
3450 struct GNUNET_TIME_Relative delay;
3452 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3454 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3455 delay.rel_value /= 2; /* do before expiration */
3456 delay = GNUNET_TIME_relative_min (delay,
3457 LATENCY_EVALUATION_MAX_DELAY);
3458 if (GNUNET_YES != fal->estimated)
3460 delay = GNUNET_TIME_UNIT_ZERO;
3461 fal->estimated = GNUNET_YES;
3463 if (GNUNET_YES == fal->connected)
3465 delay = GNUNET_TIME_relative_min (delay,
3466 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3468 /* FIXME: also adjust delay based on how close the last
3469 observed latency is to the latency of the best alternative */
3470 /* bound how fast we can go */
3471 delay = GNUNET_TIME_relative_max (delay,
3472 GNUNET_TIME_UNIT_SECONDS);
3473 /* randomize a bit (to avoid doing all at the same time) */
3474 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3475 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3476 &send_periodic_ping,
3484 * Function that will be called if we receive some payload
3485 * from another peer.
3487 * @param message the payload
3488 * @param n peer who claimed to be the sender
3491 handle_payload_message (const struct GNUNET_MessageHeader *message,
3492 struct NeighbourList *n)
3494 struct InboundMessage *im;
3495 struct TransportClient *cpos;
3498 msize = ntohs (message->size);
3499 if (n->received_pong == GNUNET_NO)
3501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3502 "Received message of type %u and size %u from `%4s', but no pong yet!!\n",
3503 ntohs (message->type),
3504 ntohs (message->size),
3505 GNUNET_i2s (&n->id));
3506 GNUNET_free_non_null (n->pre_connect_message_buffer);
3507 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3508 memcpy (n->pre_connect_message_buffer, message, msize);
3513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3514 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3515 ntohs (message->type),
3516 ntohs (message->size),
3517 GNUNET_i2s (&n->id));
3519 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3522 n->quota_violation_count++;
3524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3525 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3526 n->in_tracker.available_bytes_per_s__,
3527 n->quota_violation_count);
3529 /* Discount 32k per violation */
3530 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3535 if (n->quota_violation_count > 0)
3537 /* try to add 32k back */
3538 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3540 n->quota_violation_count--;
3543 GNUNET_STATISTICS_update (stats,
3544 gettext_noop ("# payload received from other peers"),
3547 /* transmit message to all clients */
3548 uint32_t ats_count = 2;
3549 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
3550 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3553 im = GNUNET_malloc (size);
3554 im->header.size = htons (size);
3555 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3557 im->ats_count = htonl(ats_count);
3558 /* Setting ATS data */
3559 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
3560 (&(im->ats))[0].value = htonl (n->distance);
3561 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
3562 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
3563 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3564 (&(im->ats))[ats_count].value = htonl (0);
3566 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
3568 while (cpos != NULL)
3570 transmit_to_client (cpos, &im->header, GNUNET_YES);
3578 * Iterator over hash map entries. Checks if the given validation
3579 * entry is for the same challenge as what is given in the PONG.
3581 * @param cls the 'struct TransportPongMessage*'
3582 * @param key peer identity
3583 * @param value value in the hash map ('struct ValidationEntry')
3584 * @return GNUNET_YES if we should continue to
3585 * iterate (mismatch), GNUNET_NO if not (entry matched)
3588 check_pending_validation (void *cls,
3589 const GNUNET_HashCode * key,
3592 const struct TransportPongMessage *pong = cls;
3593 struct ValidationEntry *ve = value;
3594 struct AddValidatedAddressContext avac;
3595 unsigned int challenge = ntohl(pong->challenge);
3596 struct GNUNET_HELLO_Message *hello;
3597 struct GNUNET_PeerIdentity target;
3598 struct NeighbourList *n;
3599 struct ForeignAddressList *fal;
3600 struct OwnAddressList *oal;
3601 struct TransportPlugin *tp;
3602 struct GNUNET_MessageHeader *prem;
3608 ps = ntohs (pong->header.size);
3609 if (ps < sizeof (struct TransportPongMessage))
3611 GNUNET_break_op (0);
3614 addr = (const char*) &pong[1];
3615 slen = strlen (ve->transport_name) + 1;
3616 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
3617 (ve->challenge != challenge) ||
3618 (addr[slen-1] != '\0') ||
3619 (0 != strcmp (addr, ve->transport_name)) ||
3620 (ntohl (pong->purpose.size)
3621 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3623 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3624 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
3629 alen = ps - sizeof (struct TransportPongMessage) - slen;
3630 switch (ntohl (pong->purpose.purpose))
3632 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
3633 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
3634 (0 != memcmp (&addr[slen],
3638 return GNUNET_YES; /* different entry, keep trying! */
3640 if (0 != memcmp (&pong->pid,
3642 sizeof (struct GNUNET_PeerIdentity)))
3644 GNUNET_break_op (0);
3648 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
3653 GNUNET_break_op (0);
3658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3659 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3661 a2s (ve->transport_name,
3662 (const struct sockaddr *) ve->addr,
3664 ve->transport_name);
3667 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
3668 if (0 != memcmp (&pong->pid,
3670 sizeof (struct GNUNET_PeerIdentity)))
3672 GNUNET_break_op (0);
3675 if (ve->addrlen != 0)
3677 /* must have been for a different validation entry */
3680 tp = find_transport (ve->transport_name);
3686 oal = tp->addresses;
3689 if ( (oal->addrlen == alen) &&
3690 (0 == memcmp (&oal[1],
3698 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3699 _("Not accepting PONG with address `%s' since I cannot confirm having this address.\n"),
3700 a2s (ve->transport_name,
3706 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
3711 GNUNET_break_op (0);
3716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3717 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
3719 a2s (ve->transport_name,
3722 ve->transport_name);
3726 GNUNET_break_op (0);
3729 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
3731 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3732 _("Received expired signature. Check system time.\n"));
3735 GNUNET_STATISTICS_update (stats,
3736 gettext_noop ("# address validation successes"),
3739 /* create the updated HELLO */
3740 GNUNET_CRYPTO_hash (&ve->publicKey,
3741 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3742 &target.hashPubKey);
3743 if (ve->addr != NULL)
3745 avac.done = GNUNET_NO;
3747 hello = GNUNET_HELLO_create (&ve->publicKey,
3748 &add_validated_address,
3750 GNUNET_PEERINFO_add_peer (peerinfo,
3752 GNUNET_free (hello);
3754 n = find_neighbour (&target);
3757 n->publicKey = ve->publicKey;
3758 n->public_key_valid = GNUNET_YES;
3759 fal = add_peer_address (n,
3764 GNUNET_assert (fal != NULL);
3765 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3766 fal->validated = GNUNET_YES;
3767 mark_address_connected (fal);
3768 GNUNET_STATISTICS_update (stats,
3769 gettext_noop ("# peer addresses considered valid"),
3772 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3773 schedule_next_ping (fal);
3774 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3775 n->latency = fal->latency;
3777 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
3779 n->distance = fal->distance;
3780 if (GNUNET_NO == n->received_pong)
3782 n->received_pong = GNUNET_YES;
3784 notify_clients_connect (&target, n->latency, n->distance);
3785 if (NULL != (prem = n->pre_connect_message_buffer))
3787 n->pre_connect_message_buffer = NULL;
3788 handle_payload_message (prem, n);
3792 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3794 GNUNET_SCHEDULER_cancel (n->retry_task);
3795 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3796 try_transmission_to_peer (n);
3800 /* clean up validation entry */
3801 GNUNET_assert (GNUNET_YES ==
3802 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3805 abort_validation (NULL, NULL, ve);
3811 * Function that will be called if we receive a validation
3812 * of an address challenge that we transmitted to another
3813 * peer. Note that the validation should only be considered
3814 * acceptable if the challenge matches AND if the sender
3815 * address is at least a plausible address for this peer
3816 * (otherwise we may be seeing a MiM attack).
3818 * @param cls closure
3819 * @param message the pong message
3820 * @param peer who responded to our challenge
3821 * @param sender_address string describing our sender address (as observed
3822 * by the other peer in binary format)
3823 * @param sender_address_len number of bytes in 'sender_address'
3826 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3827 const struct GNUNET_PeerIdentity *peer,
3828 const char *sender_address,
3829 size_t sender_address_len)
3831 #if DEBUG_TRANSPORT > 1
3832 /* we get tons of these that just get discarded, only log
3833 if we are quite verbose */
3834 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3835 "Receiving `%s' message from `%4s'.\n", "PONG",
3838 GNUNET_STATISTICS_update (stats,
3839 gettext_noop ("# PONG messages received"),
3842 if (GNUNET_SYSERR !=
3843 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3845 &check_pending_validation,
3848 /* This is *expected* to happen a lot since we send
3849 PONGs to *all* known addresses of the sender of
3850 the PING, so most likely we get multiple PONGs
3851 per PING, and all but the first PONG will end up
3852 here. So really we should not print anything here
3853 unless we want to be very, very verbose... */
3854 #if DEBUG_TRANSPORT > 2
3855 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3856 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3868 * Try to validate a neighbour's address by sending him our HELLO and a PING.
3870 * @param cls the 'struct ValidationEntry*'
3871 * @param neighbour neighbour to validate, NULL if validation failed
3874 transmit_hello_and_ping (void *cls,
3875 struct NeighbourList *neighbour)
3877 struct ValidationEntry *va = cls;
3878 struct ForeignAddressList *peer_address;
3879 struct TransportPingMessage ping;
3880 uint16_t hello_size;
3883 struct GNUNET_PeerIdentity id;
3886 GNUNET_CRYPTO_hash (&va->publicKey,
3887 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3889 if (neighbour == NULL)
3891 /* FIXME: stats... */
3892 GNUNET_break (GNUNET_OK ==
3893 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3896 abort_validation (NULL, NULL, va);
3899 neighbour->publicKey = va->publicKey;
3900 neighbour->public_key_valid = GNUNET_YES;
3901 peer_address = add_peer_address (neighbour,
3902 va->transport_name, NULL,
3903 (const void*) &va[1],
3905 if (peer_address == NULL)
3907 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3908 "Failed to add peer `%4s' for plugin `%s'\n",
3909 GNUNET_i2s (&neighbour->id),
3910 va->transport_name);
3911 GNUNET_break (GNUNET_OK ==
3912 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3915 abort_validation (NULL, NULL, va);
3918 hello_size = GNUNET_HELLO_size(our_hello);
3919 slen = strlen(va->transport_name) + 1;
3920 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
3921 message_buf = GNUNET_malloc(tsize);
3922 ping.challenge = htonl(va->challenge);
3923 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
3924 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3925 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3926 memcpy(message_buf, our_hello, hello_size);
3927 memcpy(&message_buf[hello_size],
3929 sizeof(struct TransportPingMessage));
3930 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3933 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3938 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3941 : a2s (va->transport_name,
3942 (const void*) &va[1], va->addrlen),
3944 GNUNET_i2s (&neighbour->id),
3945 "HELLO", hello_size,
3946 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
3949 GNUNET_STATISTICS_update (stats,
3950 gettext_noop ("# PING messages sent for initial validation"),
3953 transmit_to_peer (NULL, peer_address,
3954 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3955 HELLO_VERIFICATION_TIMEOUT,
3957 GNUNET_YES, neighbour);
3958 GNUNET_free(message_buf);
3963 * Check if the given address is already being validated; if not,
3964 * append the given address to the list of entries that are being be
3965 * validated and initiate validation.
3967 * @param cls closure ('struct CheckHelloValidatedContext *')
3968 * @param tname name of the transport
3969 * @param expiration expiration time
3970 * @param addr the address
3971 * @param addrlen length of the address
3972 * @return GNUNET_OK (always)
3975 run_validation (void *cls,
3977 struct GNUNET_TIME_Absolute expiration,
3981 struct CheckHelloValidatedContext *chvc = cls;
3982 struct GNUNET_PeerIdentity id;
3983 struct TransportPlugin *tp;
3984 struct ValidationEntry *va;
3985 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3986 struct CheckAddressExistsClosure caec;
3987 struct OwnAddressList *oal;
3989 GNUNET_assert (addr != NULL);
3991 GNUNET_STATISTICS_update (stats,
3992 gettext_noop ("# peer addresses scheduled for validation"),
3995 tp = find_transport (tname);
3998 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3999 GNUNET_ERROR_TYPE_BULK,
4001 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4003 GNUNET_STATISTICS_update (stats,
4004 gettext_noop ("# peer addresses not validated (plugin not available)"),
4009 /* check if this is one of our own addresses */
4010 oal = tp->addresses;
4013 if ( (oal->addrlen == addrlen) &&
4014 (0 == memcmp (&oal[1],
4018 /* not plausible, this address is equivalent to our own address! */
4019 GNUNET_STATISTICS_update (stats,
4020 gettext_noop ("# peer addresses not validated (loopback)"),
4027 GNUNET_HELLO_get_key (chvc->hello, &pk);
4028 GNUNET_CRYPTO_hash (&pk,
4030 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4033 if (is_blacklisted(&id, tp))
4036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4037 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4045 caec.addrlen = addrlen;
4046 caec.session = NULL;
4048 caec.exists = GNUNET_NO;
4049 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4050 &check_address_exists,
4052 if (caec.exists == GNUNET_YES)
4054 /* During validation attempts we will likely trigger the other
4055 peer trying to validate our address which in turn will cause
4056 it to send us its HELLO, so we expect to hit this case rather
4057 frequently. Only print something if we are very verbose. */
4058 #if DEBUG_TRANSPORT > 1
4059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4060 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4061 a2s (tname, addr, addrlen),
4065 GNUNET_STATISTICS_update (stats,
4066 gettext_noop ("# peer addresses not validated (in progress)"),
4071 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4074 va->transport_name = GNUNET_strdup (tname);
4075 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4077 va->send_time = GNUNET_TIME_absolute_get();
4078 va->addr = (const void*) &va[1];
4079 memcpy (&va[1], addr, addrlen);
4080 va->addrlen = addrlen;
4081 GNUNET_HELLO_get_key (chvc->hello,
4083 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4084 &timeout_hello_validation,
4086 GNUNET_CONTAINER_multihashmap_put (validation_map,
4089 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4090 setup_peer_check_blacklist (&id, GNUNET_NO,
4091 &transmit_hello_and_ping,
4098 * Check if addresses in validated hello "h" overlap with
4099 * those in "chvc->hello" and validate the rest.
4101 * @param cls closure
4102 * @param peer id of the peer, NULL for last call
4103 * @param h hello message for the peer (can be NULL)
4104 * @param err_msg NULL if successful, otherwise contains error message
4107 check_hello_validated (void *cls,
4108 const struct GNUNET_PeerIdentity *peer,
4109 const struct GNUNET_HELLO_Message *h,
4110 const char *err_msg)
4112 struct CheckHelloValidatedContext *chvc = cls;
4113 struct GNUNET_HELLO_Message *plain_hello;
4114 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4115 struct GNUNET_PeerIdentity target;
4116 struct NeighbourList *n;
4118 if (err_msg != NULL)
4120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4121 _("Error in communication with PEERINFO service\n"));
4127 GNUNET_STATISTICS_update (stats,
4128 gettext_noop ("# outstanding peerinfo iterate requests"),
4132 if (GNUNET_NO == chvc->hello_known)
4134 /* notify PEERINFO about the peer now, so that we at least
4135 have the public key if some other component needs it */
4136 GNUNET_HELLO_get_key (chvc->hello, &pk);
4137 GNUNET_CRYPTO_hash (&pk,
4138 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4139 &target.hashPubKey);
4140 plain_hello = GNUNET_HELLO_create (&pk,
4143 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4144 GNUNET_free (plain_hello);
4145 #if DEBUG_TRANSPORT_HELLO
4146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4147 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4149 GNUNET_i2s (&target));
4151 GNUNET_STATISTICS_update (stats,
4152 gettext_noop ("# new HELLOs requiring full validation"),
4155 GNUNET_HELLO_iterate_addresses (chvc->hello,
4162 GNUNET_STATISTICS_update (stats,
4163 gettext_noop ("# duplicate HELLO (peer known)"),
4168 if (chvc->ve_count == 0)
4170 GNUNET_CONTAINER_DLL_remove (chvc_head,
4179 #if DEBUG_TRANSPORT_HELLO
4180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4181 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4185 chvc->hello_known = GNUNET_YES;
4186 n = find_neighbour (peer);
4189 #if DEBUG_TRANSPORT_HELLO
4190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4191 "Calling hello_iterate_addresses for %s!\n",
4194 GNUNET_HELLO_iterate_addresses (h,
4196 &add_to_foreign_address_list,
4198 try_transmission_to_peer (n);
4202 #if DEBUG_TRANSPORT_HELLO
4203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4204 "No existing neighbor record for %s!\n",
4207 GNUNET_STATISTICS_update (stats,
4208 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4212 GNUNET_STATISTICS_update (stats,
4213 gettext_noop ("# HELLO validations (update case)"),
4216 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4218 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4225 * Process HELLO-message.
4227 * @param plugin transport involved, may be NULL
4228 * @param message the actual message
4229 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4232 process_hello (struct TransportPlugin *plugin,
4233 const struct GNUNET_MessageHeader *message)
4236 struct GNUNET_PeerIdentity target;
4237 const struct GNUNET_HELLO_Message *hello;
4238 struct CheckHelloValidatedContext *chvc;
4239 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4240 #if DEBUG_TRANSPORT_HELLO > 2
4243 hsize = ntohs (message->size);
4244 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4245 (hsize < sizeof (struct GNUNET_MessageHeader)))
4248 return GNUNET_SYSERR;
4250 GNUNET_STATISTICS_update (stats,
4251 gettext_noop ("# HELLOs received for validation"),
4255 /* first, check if load is too high */
4256 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4258 GNUNET_STATISTICS_update (stats,
4259 gettext_noop ("# HELLOs ignored due to high load"),
4262 #if DEBUG_TRANSPORT_HELLO
4263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4264 "Ignoring `%s' for `%4s', load too high.\n",
4266 GNUNET_i2s (&target));
4270 hello = (const struct GNUNET_HELLO_Message *) message;
4271 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4273 #if DEBUG_TRANSPORT_HELLO
4274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4275 "Unable to get public key from `%s' for `%4s'!\n",
4277 GNUNET_i2s (&target));
4279 GNUNET_break_op (0);
4280 return GNUNET_SYSERR;
4283 GNUNET_CRYPTO_hash (&publicKey,
4284 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4285 &target.hashPubKey);
4287 #if DEBUG_TRANSPORT_HELLO
4288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4289 "Received `%s' message for `%4s'\n",
4291 GNUNET_i2s (&target));
4294 if (0 == memcmp (&my_identity,
4296 sizeof (struct GNUNET_PeerIdentity)))
4298 GNUNET_STATISTICS_update (stats,
4299 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4305 while (NULL != chvc)
4307 if (GNUNET_HELLO_equals (hello,
4309 GNUNET_TIME_absolute_get ()).abs_value > 0)
4311 #if DEBUG_TRANSPORT_HELLO > 2
4312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4313 "Received duplicate `%s' message for `%4s'; ignored\n",
4315 GNUNET_i2s (&target));
4317 return GNUNET_OK; /* validation already pending */
4319 if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
4320 GNUNET_break (0 != memcmp (hello, chvc->hello,
4321 GNUNET_HELLO_size(hello)));
4326 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4327 if ((NULL != temp_neighbor))
4329 fprintf(stderr, "Already know peer, ignoring hello\n");
4334 #if DEBUG_TRANSPORT_HELLO > 2
4337 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4339 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4342 GNUNET_i2s (&target),
4344 GNUNET_HELLO_size(hello));
4348 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4350 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4351 memcpy (&chvc[1], hello, hsize);
4352 GNUNET_CONTAINER_DLL_insert (chvc_head,
4355 /* finally, check if HELLO was previously validated
4356 (continuation will then schedule actual validation) */
4357 GNUNET_STATISTICS_update (stats,
4358 gettext_noop ("# peerinfo process hello iterate requests"),
4361 GNUNET_STATISTICS_update (stats,
4362 gettext_noop ("# outstanding peerinfo iterate requests"),
4365 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4367 HELLO_VERIFICATION_TIMEOUT,
4368 &check_hello_validated, chvc);
4374 * The peer specified by the given neighbour has timed-out or a plugin
4375 * has disconnected. We may either need to do nothing (other plugins
4376 * still up), or trigger a full disconnect and clean up. This
4377 * function updates our state and does the necessary notifications.
4378 * Also notifies our clients that the neighbour is now officially
4381 * @param n the neighbour list entry for the peer
4382 * @param check GNUNET_YES to check if ALL addresses for this peer
4383 * are gone, GNUNET_NO to force a disconnect of the peer
4384 * regardless of whether other addresses exist.
4387 disconnect_neighbour (struct NeighbourList *n, int check)
4389 struct ReadyList *rpos;
4390 struct NeighbourList *npos;
4391 struct NeighbourList *nprev;
4392 struct MessageQueue *mq;
4393 struct ForeignAddressList *peer_addresses;
4394 struct ForeignAddressList *peer_pos;
4396 if (GNUNET_YES == check)
4399 while (NULL != rpos)
4401 peer_addresses = rpos->addresses;
4402 while (peer_addresses != NULL)
4404 if (GNUNET_YES == peer_addresses->connected)
4406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4407 "NOT Disconnecting from `%4s', still have live addresses!\n",
4408 GNUNET_i2s (&n->id));
4409 return; /* still connected */
4411 peer_addresses = peer_addresses->next;
4417 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4418 "Disconnecting from `%4s'\n",
4419 GNUNET_i2s (&n->id));
4421 /* remove n from neighbours list */
4424 while ((npos != NULL) && (npos != n))
4429 GNUNET_assert (npos != NULL);
4431 neighbours = n->next;
4433 nprev->next = n->next;
4435 /* notify all clients about disconnect */
4436 if (GNUNET_YES == n->received_pong)
4437 notify_clients_disconnect (&n->id);
4439 /* clean up all plugins, cancel connections and pending transmissions */
4440 while (NULL != (rpos = n->plugins))
4442 n->plugins = rpos->next;
4443 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4444 while (rpos->addresses != NULL)
4446 peer_pos = rpos->addresses;
4447 rpos->addresses = peer_pos->next;
4448 if (peer_pos->connected == GNUNET_YES)
4449 GNUNET_STATISTICS_update (stats,
4450 gettext_noop ("# connected addresses"),
4453 if (GNUNET_YES == peer_pos->validated)
4454 GNUNET_STATISTICS_update (stats,
4455 gettext_noop ("# peer addresses considered valid"),
4458 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4460 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4461 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4463 GNUNET_free(peer_pos);
4468 /* free all messages on the queue */
4469 while (NULL != (mq = n->messages_head))
4471 GNUNET_STATISTICS_update (stats,
4472 gettext_noop ("# bytes in message queue for other peers"),
4473 - (int64_t) mq->message_buf_size,
4475 GNUNET_STATISTICS_update (stats,
4476 gettext_noop ("# bytes discarded due to disconnect"),
4477 mq->message_buf_size,
4479 GNUNET_CONTAINER_DLL_remove (n->messages_head,
4482 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4484 sizeof(struct GNUNET_PeerIdentity)));
4487 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4489 GNUNET_SCHEDULER_cancel (n->timeout_task);
4490 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4492 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4494 GNUNET_SCHEDULER_cancel (n->retry_task);
4495 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4497 if (n->piter != NULL)
4499 GNUNET_PEERINFO_iterate_cancel (n->piter);
4500 GNUNET_STATISTICS_update (stats,
4501 gettext_noop ("# outstanding peerinfo iterate requests"),
4506 /* finally, free n itself */
4507 GNUNET_STATISTICS_update (stats,
4508 gettext_noop ("# active neighbours"),
4511 GNUNET_free_non_null (n->pre_connect_message_buffer);
4517 * We have received a PING message from someone. Need to send a PONG message
4518 * in response to the peer by any means necessary.
4521 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4522 const struct GNUNET_PeerIdentity *peer,
4523 struct Session *session,
4524 const char *sender_address,
4525 uint16_t sender_address_len)
4527 struct TransportPlugin *plugin = cls;
4528 struct SessionHeader *session_header = (struct SessionHeader*) session;
4529 struct TransportPingMessage *ping;
4530 struct TransportPongMessage *pong;
4531 struct NeighbourList *n;
4532 struct ReadyList *rl;
4533 struct ForeignAddressList *fal;
4534 struct OwnAddressList *oal;
4539 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
4541 GNUNET_break_op (0);
4542 return GNUNET_SYSERR;
4545 ping = (struct TransportPingMessage *) message;
4546 if (0 != memcmp (&ping->target,
4547 plugin->env.my_identity,
4548 sizeof (struct GNUNET_PeerIdentity)))
4550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4551 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
4553 (sender_address != NULL)
4554 ? a2s (plugin->short_name,
4555 (const struct sockaddr *)sender_address,
4558 GNUNET_i2s (&ping->target));
4559 return GNUNET_SYSERR;
4562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4563 "Processing `%s' from `%s'\n",
4565 (sender_address != NULL)
4566 ? a2s (plugin->short_name,
4567 (const struct sockaddr *)sender_address,
4571 GNUNET_STATISTICS_update (stats,
4572 gettext_noop ("# PING messages received"),
4575 addr = (const char*) &ping[1];
4576 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
4577 slen = strlen (plugin->short_name) + 1;
4580 /* peer wants to confirm that we have an outbound connection to him */
4581 if (session == NULL)
4583 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4584 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
4586 return GNUNET_SYSERR;
4588 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4589 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4590 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4591 pong->purpose.size =
4592 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4594 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4595 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
4596 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
4597 pong->challenge = ping->challenge;
4598 pong->addrlen = htonl(sender_address_len + slen);
4601 sizeof(struct GNUNET_PeerIdentity));
4605 if ((sender_address!=NULL) && (sender_address_len > 0))
4606 memcpy (&((char*)&pong[1])[slen],
4608 sender_address_len);
4609 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
4611 /* create / update cached sig */
4613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4614 "Creating PONG signature to indicate active connection.\n");
4616 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
4617 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4618 GNUNET_assert (GNUNET_OK ==
4619 GNUNET_CRYPTO_rsa_sign (my_private_key,
4621 &session_header->pong_signature));
4625 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4627 memcpy (&pong->signature,
4628 &session_header->pong_signature,
4629 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4635 /* peer wants to confirm that this is one of our addresses */
4639 plugin->api->check_address (plugin->api->cls,
4643 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4644 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
4645 a2s (plugin->short_name,
4650 oal = plugin->addresses;
4653 if ( (oal->addrlen == alen) &&
4660 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
4661 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
4662 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4663 pong->purpose.size =
4664 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4666 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4667 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
4668 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
4669 pong->challenge = ping->challenge;
4670 pong->addrlen = htonl(alen + slen);
4673 sizeof(struct GNUNET_PeerIdentity));
4674 memcpy (&pong[1], plugin->short_name, slen);
4675 memcpy (&((char*)&pong[1])[slen], addr, alen);
4676 if ( (oal != NULL) &&
4677 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
4679 /* create / update cached sig */
4681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4682 "Creating PONG signature to indicate ownership.\n");
4684 oal->pong_sig_expires = GNUNET_TIME_absolute_min (oal->expires,
4685 GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4686 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4687 GNUNET_assert (GNUNET_OK ==
4688 GNUNET_CRYPTO_rsa_sign (my_private_key,
4690 &oal->pong_signature));
4691 memcpy (&pong->signature,
4692 &oal->pong_signature,
4693 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4695 else if (oal == NULL)
4697 /* not using cache (typically DV-only) */
4698 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4699 GNUNET_assert (GNUNET_OK ==
4700 GNUNET_CRYPTO_rsa_sign (my_private_key,
4706 /* can used cached version */
4707 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4708 memcpy (&pong->signature,
4709 &oal->pong_signature,
4710 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4713 n = find_neighbour(peer);
4714 GNUNET_assert (n != NULL);
4715 /* first try reliable response transmission */
4719 fal = rl->addresses;
4722 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4725 ntohs (pong->header.size),
4726 TRANSPORT_PONG_PRIORITY,
4727 HELLO_VERIFICATION_TIMEOUT,
4735 GNUNET_STATISTICS_update (stats,
4736 gettext_noop ("# PONGs unicast via reliable transport"),
4746 /* no reliable method found, do multicast */
4747 GNUNET_STATISTICS_update (stats,
4748 gettext_noop ("# PONGs multicast to all available addresses"),
4754 fal = rl->addresses;
4757 transmit_to_peer(NULL, fal,
4758 TRANSPORT_PONG_PRIORITY,
4759 HELLO_VERIFICATION_TIMEOUT,
4761 ntohs(pong->header.size),
4774 * Function called by the plugin for each received message.
4775 * Update data volumes, possibly notify plugins about
4776 * reducing the rate at which they read from the socket
4777 * and generally forward to our receive callback.
4779 * @param cls the "struct TransportPlugin *" we gave to the plugin
4780 * @param peer (claimed) identity of the other peer
4781 * @param message the message, NULL if we only care about
4782 * learning about the delay until we should receive again
4783 * @param ats_data information for automatic transport selection
4784 * @param ats_count number of elements in ats not including 0-terminator
4785 * @param session identifier used for this session (can be NULL)
4786 * @param sender_address binary address of the sender (if observed)
4787 * @param sender_address_len number of bytes in sender_address
4788 * @return how long in ms the plugin should wait until receiving more data
4789 * (plugins that do not support this, can ignore the return value)
4791 static struct GNUNET_TIME_Relative
4792 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4793 const struct GNUNET_MessageHeader *message,
4794 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
4796 struct Session *session,
4797 const char *sender_address,
4798 uint16_t sender_address_len)
4800 struct TransportPlugin *plugin = cls;
4801 struct ReadyList *service_context;
4802 struct ForeignAddressList *peer_address;
4804 struct NeighbourList *n;
4805 struct GNUNET_TIME_Relative ret;
4806 if (is_blacklisted (peer, plugin))
4807 return GNUNET_TIME_UNIT_FOREVER_REL;
4811 n = find_neighbour (peer);
4813 n = setup_new_neighbour (peer, GNUNET_YES);
4814 service_context = n->plugins;
4815 while ((service_context != NULL) && (plugin != service_context->plugin))
4816 service_context = service_context->next;
4817 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4818 peer_address = NULL;
4820 for (c=0; c<ats_count; c++)
4822 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
4824 distance = ntohl(ats_data[c].value);
4827 /* notify ATS about incoming data */
4828 ats_notify_ats_data(peer, ats_data);
4830 if (message != NULL)
4832 if ( (session != NULL) ||
4833 (sender_address != NULL) )
4834 peer_address = add_peer_address (n,
4838 sender_address_len);
4839 if (peer_address != NULL)
4841 peer_address->distance = distance;
4842 if (GNUNET_YES == peer_address->validated)
4843 mark_address_connected (peer_address);
4844 peer_address->timeout
4846 GNUNET_TIME_relative_to_absolute
4847 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4848 schedule_next_ping (peer_address);
4850 /* update traffic received amount ... */
4851 msize = ntohs (message->size);
4852 GNUNET_STATISTICS_update (stats,
4853 gettext_noop ("# bytes received from other peers"),
4856 n->distance = distance;
4858 GNUNET_TIME_relative_to_absolute
4859 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4860 GNUNET_SCHEDULER_cancel (n->timeout_task);
4862 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4863 &neighbour_timeout_task, n);
4864 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4866 /* dropping message due to frequent inbound volume violations! */
4867 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4868 GNUNET_ERROR_TYPE_BULK,
4870 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4871 n->in_tracker.available_bytes_per_s__,
4872 n->quota_violation_count);
4873 GNUNET_STATISTICS_update (stats,
4874 gettext_noop ("# bandwidth quota violations by other peers"),
4877 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4882 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4883 ntohs (message->type),
4884 ntohs (message->size),
4887 switch (ntohs (message->type))
4889 case GNUNET_MESSAGE_TYPE_HELLO:
4890 GNUNET_STATISTICS_update (stats,
4891 gettext_noop ("# HELLO messages received from other peers"),
4894 process_hello (plugin, message);
4896 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4897 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
4899 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4900 handle_pong (plugin, message, peer, sender_address, sender_address_len);
4903 handle_payload_message (message, n);
4907 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4908 if (ret.rel_value > 0)
4910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4911 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4912 (unsigned long long) n->in_tracker.consumption_since_last_update__,
4913 (unsigned int) n->in_tracker.available_bytes_per_s__,
4914 (unsigned long long) ret.rel_value);
4915 GNUNET_STATISTICS_update (stats,
4916 gettext_noop ("# ms throttling suggested"),
4917 (int64_t) ret.rel_value,
4924 * Handle START-message. This is the first message sent to us
4925 * by any client which causes us to add it to our list.
4927 * @param cls closure (always NULL)
4928 * @param client identification of the client
4929 * @param message the actual message
4932 handle_start (void *cls,
4933 struct GNUNET_SERVER_Client *client,
4934 const struct GNUNET_MessageHeader *message)
4936 const struct StartMessage *start;
4937 struct TransportClient *c;
4938 struct ConnectInfoMessage * cim;
4939 struct NeighbourList *n;
4943 start = (const struct StartMessage*) message;
4945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4946 "Received `%s' request from client\n", "START");
4951 if (c->client == client)
4953 /* client already on our list! */
4955 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4960 if ( (GNUNET_NO != ntohl (start->do_check)) &&
4961 (0 != memcmp (&start->self,
4963 sizeof (struct GNUNET_PeerIdentity))) )
4965 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4966 _("Rejecting control connection from peer `%s', which is not me!\n"),
4967 GNUNET_i2s (&start->self));
4968 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4971 c = GNUNET_malloc (sizeof (struct TransportClient));
4975 if (our_hello != NULL)
4978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4979 "Sending our own `%s' to new client\n", "HELLO");
4981 transmit_to_client (c,
4982 (const struct GNUNET_MessageHeader *) our_hello,
4984 /* tell new client about all existing connections */
4986 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
4987 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4991 cim = GNUNET_malloc (size);
4992 cim->header.size = htons (size);
4993 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4994 cim->ats_count = htonl(ats_count);
4995 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4996 (&(cim->ats))[2].value = htonl (0);
5000 if (GNUNET_YES == n->received_pong)
5002 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5003 (&(cim->ats))[0].value = htonl (n->distance);
5004 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5005 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
5007 transmit_to_client (c, &cim->header, GNUNET_NO);
5013 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5018 * Handle HELLO-message.
5020 * @param cls closure (always NULL)
5021 * @param client identification of the client
5022 * @param message the actual message
5025 handle_hello (void *cls,
5026 struct GNUNET_SERVER_Client *client,
5027 const struct GNUNET_MessageHeader *message)
5031 GNUNET_STATISTICS_update (stats,
5032 gettext_noop ("# HELLOs received from clients"),
5035 ret = process_hello (NULL, message);
5036 GNUNET_SERVER_receive_done (client, ret);
5041 * Closure for 'transmit_client_message'; followed by
5042 * 'msize' bytes of the actual message.
5044 struct TransmitClientMessageContext
5047 * Client on whom's behalf we are sending.
5049 struct GNUNET_SERVER_Client *client;
5052 * Timeout for the transmission.
5054 struct GNUNET_TIME_Absolute timeout;
5062 * Size of the message in bytes.
5069 * Schedule transmission of a message we got from a client to a peer.
5071 * @param cls the 'struct TransmitClientMessageContext*'
5072 * @param n destination, or NULL on error (in that case, drop the message)
5075 transmit_client_message (void *cls,
5076 struct NeighbourList *n)
5078 struct TransmitClientMessageContext *tcmc = cls;
5079 struct TransportClient *tc;
5082 while ((tc != NULL) && (tc->client != tcmc->client))
5087 transmit_to_peer (tc, NULL, tcmc->priority,
5088 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5090 tcmc->msize, GNUNET_NO, n);
5092 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5093 GNUNET_SERVER_client_drop (tcmc->client);
5099 * Handle SEND-message.
5101 * @param cls closure (always NULL)
5102 * @param client identification of the client
5103 * @param message the actual message
5106 handle_send (void *cls,
5107 struct GNUNET_SERVER_Client *client,
5108 const struct GNUNET_MessageHeader *message)
5110 const struct OutboundMessage *obm;
5111 const struct GNUNET_MessageHeader *obmm;
5112 struct TransmitClientMessageContext *tcmc;
5116 size = ntohs (message->size);
5118 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5121 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5124 GNUNET_STATISTICS_update (stats,
5125 gettext_noop ("# payload received for other peers"),
5128 obm = (const struct OutboundMessage *) message;
5129 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5130 msize = size - sizeof (struct OutboundMessage);
5132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5133 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5134 "SEND", GNUNET_i2s (&obm->peer),
5138 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5139 tcmc->client = client;
5140 tcmc->priority = ntohl (obm->priority);
5141 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5142 tcmc->msize = msize;
5143 /* FIXME: this memcpy can be up to 7% of our total runtime */
5144 memcpy (&tcmc[1], obmm, msize);
5145 GNUNET_SERVER_client_keep (client);
5146 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5147 &transmit_client_message,
5153 * Handle request connect message
5155 * @param cls closure (always NULL)
5156 * @param client identification of the client
5157 * @param message the actual message
5160 handle_request_connect (void *cls,
5161 struct GNUNET_SERVER_Client *client,
5162 const struct GNUNET_MessageHeader *message)
5164 const struct TransportRequestConnectMessage *trcm =
5165 (const struct TransportRequestConnectMessage *) message;
5167 GNUNET_STATISTICS_update (stats,
5168 gettext_noop ("# REQUEST CONNECT messages received"),
5171 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a request connect message for peer %s\n", GNUNET_i2s(&trcm->peer));
5172 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5174 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5178 * Handle SET_QUOTA-message.
5180 * @param cls closure (always NULL)
5181 * @param client identification of the client
5182 * @param message the actual message
5185 handle_set_quota (void *cls,
5186 struct GNUNET_SERVER_Client *client,
5187 const struct GNUNET_MessageHeader *message)
5189 const struct QuotaSetMessage *qsm =
5190 (const struct QuotaSetMessage *) message;
5191 struct NeighbourList *n;
5193 GNUNET_STATISTICS_update (stats,
5194 gettext_noop ("# SET QUOTA messages received"),
5197 n = find_neighbour (&qsm->peer);
5200 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5201 GNUNET_STATISTICS_update (stats,
5202 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5209 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5211 (unsigned int) ntohl (qsm->quota.value__),
5212 (unsigned int) n->in_tracker.available_bytes_per_s__,
5213 GNUNET_i2s (&qsm->peer));
5215 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5217 if (0 == ntohl (qsm->quota.value__))
5219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5220 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5222 disconnect_neighbour (n, GNUNET_NO);
5224 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5229 * Take the given address and append it to the set of results sent back to
5232 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5233 * @param address the resolved name, NULL to indicate the last response
5236 transmit_address_to_client (void *cls, const char *address)
5238 struct GNUNET_SERVER_TransmitContext *tc = cls;
5241 if (NULL == address)
5244 slen = strlen (address) + 1;
5246 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5247 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5248 if (NULL == address)
5249 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5254 * Handle AddressLookup-message.
5256 * @param cls closure (always NULL)
5257 * @param client identification of the client
5258 * @param message the actual message
5261 handle_address_lookup (void *cls,
5262 struct GNUNET_SERVER_Client *client,
5263 const struct GNUNET_MessageHeader *message)
5265 const struct AddressLookupMessage *alum;
5266 struct TransportPlugin *lsPlugin;
5267 const char *nameTransport;
5268 const char *address;
5270 struct GNUNET_SERVER_TransmitContext *tc;
5271 struct GNUNET_TIME_Absolute timeout;
5272 struct GNUNET_TIME_Relative rtimeout;
5275 size = ntohs (message->size);
5276 if (size < sizeof (struct AddressLookupMessage))
5278 GNUNET_break_op (0);
5279 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5282 alum = (const struct AddressLookupMessage *) message;
5283 uint32_t addressLen = ntohl (alum->addrlen);
5284 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5286 GNUNET_break_op (0);
5287 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5290 address = (const char *) &alum[1];
5291 nameTransport = (const char *) &address[addressLen];
5293 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5295 GNUNET_break_op (0);
5296 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5299 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5300 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5301 numeric = ntohl (alum->numeric_only);
5302 lsPlugin = find_transport (nameTransport);
5303 if (NULL == lsPlugin)
5305 tc = GNUNET_SERVER_transmit_context_create (client);
5306 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5307 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5308 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5311 tc = GNUNET_SERVER_transmit_context_create (client);
5312 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5314 address, addressLen,
5317 &transmit_address_to_client, tc);
5322 * Setup the environment for this plugin.
5325 create_environment (struct TransportPlugin *plug)
5327 plug->env.cfg = cfg;
5328 plug->env.my_identity = &my_identity;
5329 plug->env.our_hello = &our_hello;
5330 plug->env.cls = plug;
5331 plug->env.receive = &plugin_env_receive;
5332 plug->env.notify_address = &plugin_env_notify_address;
5333 plug->env.session_end = &plugin_env_session_end;
5334 plug->env.max_connections = max_connect_per_transport;
5335 plug->env.stats = stats;
5340 * Start the specified transport (load the plugin).
5343 start_transport (struct GNUNET_SERVER_Handle *server,
5346 struct TransportPlugin *plug;
5349 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5350 _("Loading `%s' transport plugin\n"), name);
5351 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
5352 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
5353 create_environment (plug);
5354 plug->short_name = GNUNET_strdup (name);
5355 plug->lib_name = libname;
5356 plug->next = plugins;
5358 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
5359 if (plug->api == NULL)
5361 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5362 _("Failed to load transport plugin for `%s'\n"), name);
5363 GNUNET_free (plug->short_name);
5364 plugins = plug->next;
5365 GNUNET_free (libname);
5372 * Called whenever a client is disconnected. Frees our
5373 * resources associated with that client.
5375 * @param cls closure
5376 * @param client identification of the client
5379 client_disconnect_notification (void *cls,
5380 struct GNUNET_SERVER_Client *client)
5382 struct TransportClient *pos;
5383 struct TransportClient *prev;
5384 struct ClientMessageQueueEntry *mqe;
5385 struct Blacklisters *bl;
5386 struct BlacklistCheck *bc;
5391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5392 "Client disconnected, cleaning up.\n");
5394 /* clean up blacklister */
5398 if (bl->client == client)
5403 if (bc->bl_pos == bl)
5405 bc->bl_pos = bl->next;
5408 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
5411 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
5412 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
5418 GNUNET_CONTAINER_DLL_remove (bl_head,
5421 GNUNET_SERVER_client_drop (bl->client);
5427 /* clean up 'normal' clients */
5430 while ((pos != NULL) && (pos->client != client))
5437 while (NULL != (mqe = pos->message_queue_head))
5439 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
5440 pos->message_queue_tail,
5442 pos->message_count--;
5446 clients = pos->next;
5448 prev->next = pos->next;
5449 if (GNUNET_YES == pos->tcs_pending)
5454 if (pos->th != NULL)
5456 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
5459 GNUNET_break (0 == pos->message_count);
5465 * Function called when the service shuts down. Unloads our plugins
5466 * and cancels pending validations.
5468 * @param cls closure, unused
5469 * @param tc task context (unused)
5472 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5474 struct TransportPlugin *plug;
5475 struct OwnAddressList *al;
5476 struct CheckHelloValidatedContext *chvc;
5478 while (neighbours != NULL)
5480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5481 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
5483 disconnect_neighbour (neighbours, GNUNET_NO);
5486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5487 "Transport service is unloading plugins...\n");
5489 while (NULL != (plug = plugins))
5491 plugins = plug->next;
5492 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
5494 GNUNET_SCHEDULER_cancel (plug->address_update_task);
5495 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
5497 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
5498 GNUNET_free (plug->lib_name);
5499 GNUNET_free (plug->short_name);
5500 while (NULL != (al = plug->addresses))
5502 plug->addresses = al->next;
5507 if (my_private_key != NULL)
5508 GNUNET_CRYPTO_rsa_key_free (my_private_key);
5509 GNUNET_free_non_null (our_hello);
5511 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
5514 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5515 validation_map = NULL;
5519 /* free 'chvc' data structure */
5520 while (NULL != (chvc = chvc_head))
5522 chvc_head = chvc->next;
5523 if (chvc->piter != NULL)
5525 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
5526 GNUNET_STATISTICS_update (stats,
5527 gettext_noop ("# outstanding peerinfo iterate requests"),
5533 GNUNET_assert (chvc->ve_count == 0);
5540 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5543 if (peerinfo != NULL)
5545 GNUNET_PEERINFO_disconnect (peerinfo);
5548 /* Can we assume those are gone by now, or do we need to clean up
5550 GNUNET_break (bl_head == NULL);
5551 GNUNET_break (bc_head == NULL);
5554 struct ATS_mechanism
5556 struct ATS_mechanism * prev;
5557 struct ATS_mechanism * next;
5558 struct ForeignAddressList * addr;
5559 struct TransportPlugin * plugin;
5560 struct ATS_peer * peer;
5570 struct GNUNET_PeerIdentity peer;
5571 struct NeighbourList * n;
5572 struct ATS_mechanism * m_head;
5573 struct ATS_mechanism * m_tail;
5575 /* preference value f */
5581 static int ats_create_problem (int max_it, int max_dur )
5584 if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "no glpk installed\n");
5587 if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "glpk installed\n");
5598 int c_c_ressources = 0;
5599 int c_q_metrics = 0;
5601 double v_b_min = 100;
5603 double M = 1000000000;
5608 double Q[c_q_metrics+1];
5609 for (c=1; c<=c_q_metrics; c++)
5614 struct NeighbourList *next = neighbours;
5617 struct ReadyList *r_next = next->plugins;
5618 while (r_next != NULL)
5620 struct ForeignAddressList * a_next = r_next->addresses;
5621 while (a_next != NULL)
5624 a_next = a_next->next;
5626 r_next = r_next->next;
5634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No addresses for bw distribution available\n", c_peers);
5638 struct ATS_mechanism * mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
5639 struct ATS_peer * peers = GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
5641 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found mechanisms: %i\n", c_mechs);
5647 peers[c_peers].peer = next->id;
5648 peers[c_peers].m_head = NULL;
5649 peers[c_peers].m_tail = NULL;
5651 struct ReadyList *r_next = next->plugins;
5652 while (r_next != NULL)
5654 struct ForeignAddressList * a_next = r_next->addresses;
5655 while (a_next != NULL)
5657 if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%i Peer: `%s' %x:\n", c_mechs, GNUNET_i2s(&next->id),
5659 mechanisms[c_mechs].addr = a_next;
5660 mechanisms[c_mechs].col_index = c_mechs;
5661 mechanisms[c_mechs].peer = &peers[c_peers];
5662 mechanisms[c_mechs].next = NULL;
5664 GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head, peers[c_peers].m_tail, &mechanisms[c_mechs]);
5666 a_next = a_next->next;
5668 r_next = r_next->next;
5676 /* number of variables == coloumns */
5677 //int c_cols = 2 * c_mechs + 3 + c_q_metrics;
5678 /* number of constraints == rows */
5679 //int c_rows = 2 * c_peers + 2 * c_mechs + c_c_ressources + c_q_metrics + 3;
5681 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Creating problem with: %i peers, %i mechanisms\n", c_peers, c_mechs);
5683 int size = 6 *c_mechs;
5686 int * ia = GNUNET_malloc (size * sizeof (int));
5687 int * ja = GNUNET_malloc (size * sizeof (int));
5688 double * ar = GNUNET_malloc(size* sizeof (double));
5690 prob = glp_create_prob();
5691 glp_set_prob_name(prob, "gnunet ats bandwidth distribution");
5692 glp_set_obj_dir(prob, GLP_MAX);
5694 /* adding columns */
5696 glp_add_cols(prob, 2 * c_mechs);
5697 /* adding b_t cols */
5698 for (c=1; c <= c_mechs; c++)
5700 GNUNET_asprintf(&name, "b%i",c);
5701 glp_set_col_name(prob, c, name);
5703 glp_set_col_bnds(prob, c, GLP_LO, 0.0, 0.0);
5704 glp_set_obj_coef(prob, c, 1.0);
5707 /* adding n_t cols */
5708 for (c=c_mechs+1; c <= 2*c_mechs; c++)
5710 GNUNET_asprintf(&name, "n%i",(c-c_mechs)+1);
5711 glp_set_col_name(prob, c, name);
5713 glp_set_col_bnds(prob, c, GLP_DB, 0.0, 1.0);
5714 glp_set_col_kind(prob, c, GLP_IV);
5715 glp_set_obj_coef(prob, c, 1.0);
5718 /* feasibility constraints */
5719 /* Constraint 1: one address per peer*/
5720 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constraint 1\n");
5722 glp_add_rows(prob, c_peers);
5723 for (c=1; c<=c_peers; c++)
5725 glp_set_row_bnds(prob, row_index, GLP_DB, 0.0, 1.0);
5727 struct ATS_mechanism *m = peers[c].m_head;
5730 ia[array_index] = row_index;
5731 ja[array_index] = (c_mechs + m->col_index);
5732 ar[array_index] = 1;
5733 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5739 GNUNET_assert (row_index-1==c_peers);
5740 GNUNET_assert (array_index==c_mechs);
5742 /* Constraint 2: only active mechanism gets bandwidth assigned */
5743 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constraint 2\n");
5744 glp_add_rows(prob, c_mechs);
5745 for (c=1; c<=c_mechs; c++)
5747 /* b_t - n_t * M <= 0 */
5748 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
5749 glp_set_row_bnds(prob, row_index, GLP_UP, 0.0, 0.0);
5751 ia[array_index] = row_index;
5752 ja[array_index] = mechanisms[c].col_index;
5753 ar[array_index] = 1;
5754 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5756 ia[array_index] = row_index;
5757 ja[array_index] = c_mechs + mechanisms[c].col_index;
5758 ar[array_index] = -M;
5759 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5763 GNUNET_assert (row_index-1==c_peers+c_mechs);
5764 GNUNET_assert (array_index==c_mechs+(2*c_mechs));
5766 /* Constraint 3: minimum bandwidth*/
5767 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constraint 3\n");
5768 glp_add_rows(prob, c_mechs);
5769 for (c=1; c<=c_mechs; c++)
5771 /* b_t - n_t * b_min <= 0 */
5772 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
5773 glp_set_row_bnds(prob, row_index, GLP_UP, 0.0, 0.0);
5775 ia[array_index] = row_index;
5776 ja[array_index] = mechanisms[c].col_index;
5777 ar[array_index] = 1;
5778 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5780 ia[array_index] = row_index;
5781 ja[array_index] = c_mechs + mechanisms[c].col_index;
5782 ar[array_index] = -v_b_min;
5783 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5787 GNUNET_assert (row_index-1==c_peers+(2*c_mechs));
5788 GNUNET_assert (array_index==c_mechs+(4*c_mechs));
5790 /* Constraint 4: max ressource capacity */
5792 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constraint 3\n");
5793 glp_add_rows(prob, c_mechs);
5794 for (c=1; c<=c_mechs; c++)
5796 // b_t - n_t * b_min >= 0
5797 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
5798 glp_set_row_bnds(prob, row_index, GLP_LO, 0.0, 0.0);
5800 ia[array_index] = row_index;
5801 ja[array_index] = mechanisms[c].col_index;
5802 ar[array_index] = 1;
5803 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5805 ia[array_index] = row_index;
5806 ja[array_index] = c_mechs + mechanisms[c].col_index;
5807 ar[array_index] = -v_b_min;
5808 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5812 GNUNET_assert (row_index-1==c_peers+(2*c_mechs));
5813 GNUNET_assert (array_index==5*c_mechs);
5816 /* Constraint 5: min number of connections*/
5817 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constraint 5\n");
5818 glp_add_rows(prob, 1);
5819 for (c=1; c<=c_mechs; c++)
5821 // b_t - n_t * b_min >= 0
5822 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
5823 glp_set_row_bnds(prob, row_index, GLP_LO, v_n_min, 0.0);
5825 ia[array_index] = row_index;
5826 ja[array_index] = c_mechs + mechanisms[c].col_index;
5827 ar[array_index] = 1;
5828 if (VERBOSE_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
5832 GNUNET_assert (row_index-1==c_peers+(2*c_mechs)+1);
5833 GNUNET_assert (array_index==6*c_mechs);
5835 /* optimisation constraints*/
5837 /* adding columns */
5838 glp_add_cols(prob, 3 + c_q_metrics);
5839 glp_set_col_name(prob, (2*c_mechs) + 1, "d");
5840 glp_set_obj_coef(prob, (2*c_mechs) + 1, D);
5841 //glp_set_col_bnds(prob, c, GLP_DB, 0.0, 1.0);
5842 //glp_set_col_kind(prob, c, GLP_IV);
5843 glp_set_col_name(prob, (2*c_mechs) + 2, "u");
5844 glp_set_obj_coef(prob, (2*c_mechs) + 2, U);
5845 //glp_set_col_bnds(prob, c, GLP_DB, 0.0, 1.0);
5846 //glp_set_col_kind(prob, c, GLP_IV);
5847 glp_set_col_name(prob, (2*c_mechs) + 3, "r");
5848 glp_set_obj_coef(prob, (2*c_mechs) + 3, R);
5849 //glp_set_col_bnds(prob, c, GLP_DB, 0.0, 1.0);
5850 //glp_set_col_kind(prob, c, GLP_IV);
5851 for (c=1; c<= c_q_metrics; c++)
5853 GNUNET_asprintf(&name, "q%i",c);
5854 glp_set_col_name(prob, c, name);
5855 glp_set_col_name(prob, (2*c_mechs) + 3 +c, name);
5857 glp_set_obj_coef(prob, (2*c_mechs) + 3 +c, Q[c]);
5860 glp_load_matrix(prob, array_index-1, ia, ja, ar);
5863 glp_init_iocp(&opt);
5865 /* Use LP presolver (if not, valid LP solution has to be provided)*/
5866 opt.presolve =GLP_ON;
5867 /* maximum duration */
5868 opt.tm_lim = max_dur;
5871 opt.msg_lev = GLP_MSG_ALL;
5873 opt.msg_lev = GLP_MSG_OFF;
5874 result = glp_intopt (prob, &opt);
5875 solution = glp_mip_status (prob);
5878 case GLP_ESTOP : /* search terminated by application */
5879 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Search terminated by application ");
5881 case GLP_EITLIM : /* iteration limit exceeded */
5882 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Iteration limit exceeded ");
5885 case GLP_ETMLIM : /* time limit exceeded */
5886 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Time limit exceeded ");
5888 case GLP_ENOFEAS: /* no primal/dual feasible solution */
5889 case GLP_ENOCVG : /* no convergence */
5890 case GLP_ERANGE : /* result out of range */
5891 case GLP_ENOPFS : /* no primal feasible solution */
5892 case GLP_ENODFS : /* no dual feasible solution */
5893 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No feasible solution");
5896 case GLP_EBADB : /* invalid basis */
5897 case GLP_ESING : /* singular matrix */
5898 case GLP_ECOND : /* ill-conditioned matrix */
5899 case GLP_EBOUND : /* invalid bounds */
5900 case GLP_EFAIL : /* solver failed */
5901 case GLP_EOBJLL : /* objective lower limit reached */
5902 case GLP_EOBJUL : /* objective upper limit reached */
5903 case GLP_EROOT : /* root LP optimum not provided */
5904 case GLP_EMIPGAP: /* relative mip gap tolerance reached */
5905 case GLP_EINSTAB: /* numerical instability */
5906 case GLP_EDATA : /* invalid data */
5907 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid Input data\n");
5912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Problem has been solved\n");
5918 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MIP solution is undefined\n");
5921 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MIP solution is integer optimal\n");
5924 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MIP solution is integer feasible, however, its optimality (or non-optimality) has not been proven, \n");
5927 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MI problem has no integer feasible solution\n");
5934 char * debug_solution = NULL;
5936 for (c=1; c<= 2*c_mechs; c++ )
5938 old = debug_solution;
5939 GNUNET_asprintf(&debug_solution, "%s %s = %g;", (debug_solution!=NULL) ? debug_solution : "", glp_get_col_name(prob,c), glp_get_col_prim(prob, c));
5940 if (old!=NULL) GNUNET_free(old);
5942 old = debug_solution;
5943 GNUNET_asprintf(&debug_solution, "%s z = %g; \n", debug_solution, glp_get_obj_val(prob));
5944 if (old!=NULL) GNUNET_free(old);
5945 if (DEBUG_ATS) GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s \n",debug_solution);
5946 GNUNET_free(debug_solution);
5948 glp_delete_prob(prob);
5956 GNUNET_free(mechanisms);
5963 /* To remove: just for testing */
5964 void ats_benchmark (int peers, int transports, int start_peers, int end_peers)
5966 static int glpk = GNUNET_YES;
5967 struct GNUNET_TIME_Absolute start;
5968 struct GNUNET_TIME_Relative duration;
5971 if (glpk==GNUNET_YES)
5973 start = GNUNET_TIME_absolute_get();
5974 c_mechs = ats_create_problem(5000,5000);
5977 duration = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
5978 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP execution time in [ms] for %i mechanisms: %llu\n", c_mechs, duration.rel_value);
5979 GNUNET_STATISTICS_set (stats, "ATS execution time 100 peers", duration.rel_value, GNUNET_NO);
5981 else glpk = GNUNET_NO;
5985 void ats_calculate_bandwidth_distribution ()
5987 struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference(ats->last,GNUNET_TIME_absolute_get());
5988 if (delta.rel_value < ats->min_delta.rel_value)
5991 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
5996 struct GNUNET_TIME_Absolute start;
5998 int mlp = GNUNET_NO;
6007 int it = ATS_MAX_ITERATIONS;
6010 if (INT_MAX < ats->max_exec_duration.rel_value)
6013 dur = (int) ats->max_exec_duration.rel_value;
6015 struct ATS_mechanism * tl = NULL;
6016 struct ATS_peer * pl = NULL;
6018 start = GNUNET_TIME_absolute_get();
6019 ats_benchmark(100,3,100,100);
6020 //ats_create_problem(peers, transports, b_min, b_max, r, R, pl, tl, it, dur, mlp);
6022 GNUNET_free_non_null (pl);
6023 GNUNET_free_non_null (tl);
6025 ats->last = GNUNET_TIME_absolute_get();
6031 ats_schedule_calculation (void *cls,
6032 const struct GNUNET_SCHEDULER_TaskContext *tc)
6034 struct ATS_info *ats = (struct ATS_info *) cls;
6038 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
6039 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
6043 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
6045 ats_calculate_bandwidth_distribution (ats);
6047 ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_intervall,
6048 &ats_schedule_calculation, ats);
6052 int ats_map_remove_peer (void *cls,
6053 const GNUNET_HashCode * key,
6057 struct ATS_peer * p = (struct ATS_peer *) value;
6059 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "map_remove_peer_it: `%s'\n", GNUNET_i2s(&p->peer));
6068 struct ATS_info * ats_init ()
6070 struct ATS_info * ats;
6072 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_init\n");
6074 ats = GNUNET_malloc(sizeof (struct ATS_info));
6075 ats->peers = GNUNET_CONTAINER_multihashmap_create(10);
6076 GNUNET_assert(ats->peers!=NULL);
6078 ats->min_delta = ATS_MIN_INTERVAL;
6079 ats->exec_intervall = ATS_EXEC_INTERVAL;
6080 ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
6081 ats->max_iterations = ATS_MAX_ITERATIONS;
6083 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
6085 ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->reg_delta,
6086 &schedule_calculation, NULL);
6088 ats->ats_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
6089 &schedule_calculation, NULL);
6091 ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
6097 void ats_shutdown ()
6100 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_destroy\n");
6102 if (ats->ats_task != GNUNET_SCHEDULER_NO_TASK)
6103 GNUNET_SCHEDULER_cancel(ats->ats_task);
6104 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
6106 GNUNET_CONTAINER_multihashmap_iterate (ats->peers,ats_map_remove_peer,NULL);
6107 GNUNET_CONTAINER_multihashmap_destroy (ats->peers);
6112 void ats_notify_peer_connect (
6113 const struct GNUNET_PeerIdentity *peer,
6114 const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
6118 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_connect: %s\n",GNUNET_i2s(peer));
6121 while (ntohl(ats_data[c].type)!=0)
6124 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats type [%i]: %i\n",ntohl(ats_data[c].type), ntohl(ats_data[c].value));
6128 /* check if peer is already known */
6129 if (!GNUNET_CONTAINER_multihashmap_contains (ats->peers,&peer->hashPubKey))
6131 struct ATS_peer * p = GNUNET_malloc (sizeof (struct ATS_peer));
6132 memcpy(&p->peer, peer, sizeof (struct GNUNET_PeerIdentity));
6133 GNUNET_CONTAINER_multihashmap_put(ats->peers, &p->peer.hashPubKey, p, GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6136 ats_calculate_bandwidth_distribution(ats);
6139 void ats_notify_peer_disconnect (
6140 const struct GNUNET_PeerIdentity *peer)
6143 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_disconnect: %s\n",GNUNET_i2s(peer));
6146 if (GNUNET_CONTAINER_multihashmap_contains (ats->peers, &peer->hashPubKey))
6148 ats_map_remove_peer(NULL, &peer->hashPubKey, GNUNET_CONTAINER_multihashmap_get (ats->peers, &peer->hashPubKey));
6149 GNUNET_CONTAINER_multihashmap_remove_all (ats->peers, &peer->hashPubKey);
6152 ats_calculate_bandwidth_distribution (ats);
6156 void ats_notify_ats_data (
6157 const struct GNUNET_PeerIdentity *peer,
6158 const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
6161 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
6163 ats_calculate_bandwidth_distribution(ats);
6166 struct ForeignAddressList * ats_get_preferred_address (
6167 struct NeighbourList *n)
6170 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ats_get_prefered_transport for peer: %s\n",GNUNET_i2s(&n->id));
6172 struct ReadyList *next = n->plugins;
6173 while (next != NULL)
6176 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "plugin: %s %i\n",next->plugin->short_name,strcmp(next->plugin->short_name,"unix"));
6180 return find_ready_address(n);
6184 * Initiate transport service.
6186 * @param cls closure
6187 * @param server the initialized server
6188 * @param c configuration to use
6192 struct GNUNET_SERVER_Handle *server,
6193 const struct GNUNET_CONFIGURATION_Handle *c)
6195 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
6196 {&handle_start, NULL,
6197 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
6198 {&handle_hello, NULL,
6199 GNUNET_MESSAGE_TYPE_HELLO, 0},
6200 {&handle_send, NULL,
6201 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
6202 {&handle_request_connect, NULL,
6203 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
6204 {&handle_set_quota, NULL,
6205 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
6206 {&handle_address_lookup, NULL,
6207 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
6209 {&handle_blacklist_init, NULL,
6210 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
6211 {&handle_blacklist_reply, NULL,
6212 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
6218 unsigned long long tneigh;
6222 stats = GNUNET_STATISTICS_create ("transport", cfg);
6223 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
6224 /* parse configuration */
6226 GNUNET_CONFIGURATION_get_value_number (c,
6231 GNUNET_CONFIGURATION_get_value_filename (c,
6233 "HOSTKEY", &keyfile)))
6235 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6237 ("Transport service is lacking key configuration settings. Exiting.\n"));
6238 GNUNET_SCHEDULER_shutdown ();
6241 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6244 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6245 validation_map = NULL;
6250 max_connect_per_transport = (uint32_t) tneigh;
6251 peerinfo = GNUNET_PEERINFO_connect (cfg);
6252 if (peerinfo == NULL)
6254 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6255 _("Could not access PEERINFO service. Exiting.\n"));
6256 GNUNET_SCHEDULER_shutdown ();
6259 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6262 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6263 validation_map = NULL;
6264 GNUNET_free (keyfile);
6267 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
6268 GNUNET_free (keyfile);
6269 if (my_private_key == NULL)
6271 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6273 ("Transport service could not access hostkey. Exiting.\n"));
6274 GNUNET_SCHEDULER_shutdown ();
6277 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6280 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6281 validation_map = NULL;
6284 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
6285 GNUNET_CRYPTO_hash (&my_public_key,
6286 sizeof (my_public_key), &my_identity.hashPubKey);
6287 /* setup notification */
6288 GNUNET_SERVER_disconnect_notify (server,
6289 &client_disconnect_notification, NULL);
6290 /* load plugins... */
6293 GNUNET_CONFIGURATION_get_value_string (c,
6294 "TRANSPORT", "PLUGINS", &plugs))
6296 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6297 _("Starting transport plugins `%s'\n"), plugs);
6298 pos = strtok (plugs, " ");
6301 start_transport (server, pos);
6303 pos = strtok (NULL, " ");
6305 GNUNET_free (plugs);
6307 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
6308 &shutdown_task, NULL);
6313 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
6315 /* If we have a blacklist file, read from it */
6316 read_blacklist_file(cfg);
6317 /* process client requests */
6318 GNUNET_SERVER_add_handlers (server, handlers);
6323 * The main function for the transport service.
6325 * @param argc number of arguments from the command line
6326 * @param argv command line arguments
6327 * @return 0 ok, 1 on error
6330 main (int argc, char *const *argv)
6332 a2s (NULL, NULL, 0); /* make compiler happy */
6333 return (GNUNET_OK ==
6334 GNUNET_SERVICE_run (argc,
6337 GNUNET_SERVICE_OPTION_NONE,
6338 &run, NULL)) ? 0 : 1;
6341 /* end of gnunet-service-transport.c */