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
53 #define VERBOSE_ATS GNUNET_NO
56 * Should we do some additional checks (to validate behavior
59 #define EXTRA_CHECKS GNUNET_YES
62 * How many messages can we have pending for a given client process
63 * before we start to drop incoming messages? We typically should
64 * have only one client and so this would be the primary buffer for
65 * messages, so the number should be chosen rather generously.
67 * The expectation here is that most of the time the queue is large
68 * enough so that a drop is virtually never required. Note that
69 * this value must be about as large as 'TOTAL_MSGS' in the
70 * 'test_transport_api_reliability.c', otherwise that testcase may
73 #define MAX_PENDING (128 * 1024)
76 * Size of the per-transport blacklist hash maps.
78 #define TRANSPORT_BLACKLIST_HT_SIZE 16
81 * How often should we try to reconnect to a peer using a particular
82 * transport plugin before giving up? Note that the plugin may be
83 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
85 #define MAX_CONNECT_RETRY 3
88 * Limit on the number of ready-to-run tasks when validating
89 * HELLOs. If more tasks are ready to run, we will drop
90 * HELLOs instead of validating them.
92 #define MAX_HELLO_LOAD 4
95 * How often must a peer violate bandwidth quotas before we start
96 * to simply drop its messages?
98 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
101 * How long until a HELLO verification attempt should time out?
102 * Must be rather small, otherwise a partially successful HELLO
103 * validation (some addresses working) might not be available
104 * before a client's request for a connection fails for good.
105 * Besides, if a single request to an address takes a long time,
106 * then the peer is unlikely worthwhile anyway.
108 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
111 * How long is a PONG signature valid? We'll recycle a signature until
112 * 1/4 of this time is remaining. PONGs should expire so that if our
113 * external addresses change an adversary cannot replay them indefinitely.
114 * OTOH, we don't want to spend too much time generating PONG signatures,
115 * so they must have some lifetime to reduce our CPU usage.
117 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
120 * Priority to use for PONG messages.
122 #define TRANSPORT_PONG_PRIORITY 4
125 * How often do we re-add (cheaper) plugins to our list of plugins
126 * to try for a given connected peer?
128 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
131 * After how long do we expire an address in a HELLO that we just
132 * validated? This value is also used for our own addresses when we
135 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
139 * How long before an existing address expires should we again try to
140 * validate it? Must be (significantly) smaller than
141 * HELLO_ADDRESS_EXPIRATION.
143 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
146 * Maximum frequency for re-evaluating latencies for all transport addresses.
148 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
151 * Maximum frequency for re-evaluating latencies for connected addresses.
153 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
155 #define VERY_BIG_DOUBLE_VALUE 100000000000LL
158 #define ATS_Q_UPDATED 1
159 #define ATS_C_UPDATED 2
160 #define ATS_QC_UPDATED 3
161 #define ATS_UNMODIFIED 4
164 * List of addresses of other peers
166 struct ForeignAddressList
169 * This is a linked list.
171 struct ForeignAddressList *next;
174 * Which ready list does this entry belong to.
176 struct ReadyList *ready_list;
179 * How long until we auto-expire this address (unless it is
180 * re-confirmed by the transport)?
182 struct GNUNET_TIME_Absolute expires;
185 * Task used to re-validate addresses, updates latencies and
188 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
196 * Session (or NULL if no valid session currently exists or if the
197 * plugin does not use sessions).
199 struct Session *session;
201 struct ATS_ressource_entry * ressources;
203 struct ATS_quality_entry * quality;
206 * What was the last latency observed for this address, plugin and peer?
208 struct GNUNET_TIME_Relative latency;
211 * If we did not successfully transmit a message to the given peer
212 * via this connection during the specified time, we should consider
213 * the connection to be dead. This is used in the case that a TCP
214 * transport simply stalls writing to the stream but does not
215 * formerly get a signal that the other peer died.
217 struct GNUNET_TIME_Absolute timeout;
220 * How often have we tried to connect using this plugin? Used to
221 * discriminate against addresses that do not work well.
222 * FIXME: not yet used, but should be!
224 unsigned int connect_attempts;
227 * DV distance to this peer (1 if no DV is used).
228 * FIXME: need to set this from transport plugins!
238 * Have we ever estimated the latency of this address? Used to
239 * ensure that the first time we add an address, we immediately
245 * Are we currently connected via this address? The first time we
246 * successfully transmit or receive data to a peer via a particular
247 * address, we set this to GNUNET_YES. If we later get an error
248 * (disconnect notification, transmission failure, timeout), we set
249 * it back to GNUNET_NO.
254 * Is this plugin currently busy transmitting to the specific target?
255 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
256 * messages do not count as 'in transmit'.
261 * Has this address been validated yet?
269 * Entry in linked list of network addresses for ourselves. Also
270 * includes a cached signature for 'struct TransportPongMessage's.
272 struct OwnAddressList
275 * This is a linked list.
277 struct OwnAddressList *next;
280 * How long until the current signature expires? (ZERO if the
281 * signature was never created).
283 struct GNUNET_TIME_Absolute pong_sig_expires;
286 * Signature for a 'struct TransportPongMessage' for this address.
288 struct GNUNET_CRYPTO_RsaSignature pong_signature;
299 * Entry in linked list of all of our plugins.
301 struct TransportPlugin
305 * This is a linked list.
307 struct TransportPlugin *next;
310 * API of the transport as returned by the plugin's
311 * initialization function.
313 struct GNUNET_TRANSPORT_PluginFunctions *api;
316 * Short name for the plugin (i.e. "tcp").
321 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
326 * List of our known addresses for this transport.
328 struct OwnAddressList *addresses;
331 * Environment this transport service is using
334 struct GNUNET_TRANSPORT_PluginEnvironment env;
337 * ID of task that is used to clean up expired addresses.
339 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
342 * Set to GNUNET_YES if we need to scrap the existing list of
343 * "addresses" and start fresh when we receive the next address
344 * update from a transport. Set to GNUNET_NO if we should just add
345 * the new address to the list and wait for the commit call.
349 struct ATS_plugin * rc;
352 * Hashmap of blacklisted peers for this particular transport.
354 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
357 struct NeighbourList;
360 * For each neighbour we keep a list of messages
361 * that we still want to transmit to the neighbour.
367 * This is a doubly linked list.
369 struct MessageQueue *next;
372 * This is a doubly linked list.
374 struct MessageQueue *prev;
377 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
378 * stuck together in memory. Allocated at the end of this struct.
380 const char *message_buf;
383 * Size of the message buf
385 size_t message_buf_size;
388 * Client responsible for queueing the message;
389 * used to check that a client has no two messages
390 * pending for the same target. Can be NULL.
392 struct TransportClient *client;
395 * Using which specific address should we send this message?
397 struct ForeignAddressList *specific_address;
400 * Peer ID of the Neighbour this entry belongs to.
402 struct GNUNET_PeerIdentity neighbour_id;
405 * Plugin that we used for the transmission.
406 * NULL until we scheduled a transmission.
408 struct TransportPlugin *plugin;
411 * At what time should we fail?
413 struct GNUNET_TIME_Absolute timeout;
416 * Internal message of the transport system that should not be
417 * included in the usual SEND-SEND_OK transmission confirmation
418 * traffic management scheme. Typically, "internal_msg" will
419 * be set whenever "client" is NULL (but it is not strictly
425 * How important is the message?
427 unsigned int priority;
433 * For a given Neighbour, which plugins are available
434 * to talk to this peer and what are their costs?
439 * This is a linked list.
441 struct ReadyList *next;
444 * Which of our transport plugins does this entry
447 struct TransportPlugin *plugin;
450 * Transport addresses, latency, and readiness for
451 * this particular plugin.
453 struct ForeignAddressList *addresses;
456 * To which neighbour does this ready list belong to?
458 struct NeighbourList *neighbour;
463 * Entry in linked list of all of our current neighbours.
469 * This is a linked list.
471 struct NeighbourList *next;
474 * Which of our transports is connected to this peer
475 * and what is their status?
477 struct ReadyList *plugins;
480 * Head of list of messages we would like to send to this peer;
481 * must contain at most one message per client.
483 struct MessageQueue *messages_head;
486 * Tail of list of messages we would like to send to this peer; must
487 * contain at most one message per client.
489 struct MessageQueue *messages_tail;
492 * Head of list of messages of messages we expected the continuation
493 * to be called to destroy the message
495 struct MessageQueue *cont_head;
498 * Tail of list of messages of messages we expected the continuation
499 * to be called to destroy the message
501 struct MessageQueue *cont_tail;
504 * Buffer for at most one payload message used when we receive
505 * payload data before our PING-PONG has succeeded. We then
506 * store such messages in this intermediary buffer until the
507 * connection is fully up.
509 struct GNUNET_MessageHeader *pre_connect_message_buffer;
512 * Context for peerinfo iteration.
513 * NULL after we are done processing peerinfo's information.
515 struct GNUNET_PEERINFO_IteratorContext *piter;
518 * Public key for this peer. Valid only if the respective flag is set below.
520 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
523 * Identity of this neighbour.
525 struct GNUNET_PeerIdentity id;
528 * ID of task scheduled to run when this peer is about to
529 * time out (will free resources associated with the peer).
531 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
534 * ID of task scheduled to run when we should retry transmitting
535 * the head of the message queue. Actually triggered when the
536 * transmission is timing out (we trigger instantly when we have
537 * a chance of success).
539 GNUNET_SCHEDULER_TaskIdentifier retry_task;
542 * How long until we should consider this peer dead
543 * (if we don't receive another message in the
546 struct GNUNET_TIME_Absolute peer_timeout;
549 * Tracker for inbound bandwidth.
551 struct GNUNET_BANDWIDTH_Tracker in_tracker;
554 * The latency we have seen for this particular address for
555 * this particular peer. This latency may have been calculated
556 * over multiple transports. This value reflects how long it took
557 * us to receive a response when SENDING via this particular
558 * transport/neighbour/address combination!
560 * FIXME: we need to periodically send PINGs to update this
561 * latency (at least more often than the current "huge" (11h?)
564 struct GNUNET_TIME_Relative latency;
567 * How often has the other peer (recently) violated the
568 * inbound traffic limit? Incremented by 10 per violation,
569 * decremented by 1 per non-violation (for each
572 unsigned int quota_violation_count;
575 * DV distance to this peer (1 if no DV is used).
580 * Have we seen an PONG from this neighbour in the past (and
581 * not had a disconnect since)?
586 * Do we have a valid public key for this neighbour?
588 int public_key_valid;
591 * Performance data for the peer.
593 struct GNUNET_TRANSPORT_ATS_Information *ats;
596 * Identity of the neighbour.
598 struct GNUNET_PeerIdentity peer;
603 * Message used to ask a peer to validate receipt (to check an address
604 * from a HELLO). Followed by the address we are trying to validate,
605 * or an empty address if we are just sending a PING to confirm that a
606 * connection which the receiver (of the PING) initiated is still valid.
608 struct TransportPingMessage
612 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
614 struct GNUNET_MessageHeader header;
617 * Challenge code (to ensure fresh reply).
619 uint32_t challenge GNUNET_PACKED;
622 * Who is the intended recipient?
624 struct GNUNET_PeerIdentity target;
630 * Message used to validate a HELLO. The challenge is included in the
631 * confirmation to make matching of replies to requests possible. The
632 * signature signs our public key, an expiration time and our address.<p>
634 * This message is followed by our transport address that the PING tried
635 * to confirm (if we liked it). The address can be empty (zero bytes)
636 * if the PING had not address either (and we received the request via
637 * a connection that we initiated).
639 struct TransportPongMessage
643 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
645 struct GNUNET_MessageHeader header;
648 * Challenge code from PING (showing freshness). Not part of what
649 * is signed so that we can re-use signatures.
651 uint32_t challenge GNUNET_PACKED;
656 struct GNUNET_CRYPTO_RsaSignature signature;
659 * What are we signing and why? Two possible reason codes can be here:
660 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
661 * plausible address for this peer (pid is set to identity of signer); or
662 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
663 * an address we used to connect to the peer with the given pid.
665 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
668 * When does this signature expire?
670 struct GNUNET_TIME_AbsoluteNBO expiration;
673 * Either the identity of the peer Who signed this message, or the
674 * identity of the peer that we're connected to using the given
675 * address (depending on purpose.type).
677 struct GNUNET_PeerIdentity pid;
680 * Size of address appended to this message (part of what is
681 * being signed, hence not redundant).
689 * Linked list of messages to be transmitted to the client. Each
690 * entry is followed by the actual message.
692 struct ClientMessageQueueEntry
695 * This is a doubly-linked list.
697 struct ClientMessageQueueEntry *next;
700 * This is a doubly-linked list.
702 struct ClientMessageQueueEntry *prev;
707 * Client connected to the transport service.
709 struct TransportClient
713 * This is a linked list.
715 struct TransportClient *next;
718 * Handle to the client.
720 struct GNUNET_SERVER_Client *client;
723 * Linked list of messages yet to be transmitted to
726 struct ClientMessageQueueEntry *message_queue_head;
729 * Tail of linked list of messages yet to be transmitted to the
732 struct ClientMessageQueueEntry *message_queue_tail;
735 * Current transmit request handle.
737 struct GNUNET_CONNECTION_TransmitHandle *th;
740 * Is a call to "transmit_send_continuation" pending? If so, we
741 * must not free this struct (even if the corresponding client
742 * disconnects) and instead only remove it from the linked list and
743 * set the "client" field to NULL.
748 * Length of the list of messages pending for this client.
750 unsigned int message_count;
756 * Context of currently active requests to peerinfo
757 * for validation of HELLOs.
759 struct CheckHelloValidatedContext;
763 * Entry in map of all HELLOs awaiting validation.
765 struct ValidationEntry
769 * NULL if this entry is not part of a larger HELLO validation.
771 struct CheckHelloValidatedContext *chvc;
774 * The address, actually a pointer to the end
775 * of this struct. Do not free!
780 * Name of the transport.
782 char *transport_name;
785 * The public key of the peer.
787 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
790 * ID of task that will clean up this entry if we don't succeed
791 * with the validation first.
793 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
796 * At what time did we send this validation?
798 struct GNUNET_TIME_Absolute send_time;
801 * Session being validated (or NULL for none).
803 struct Session *session;
806 * Challenge number we used.
819 * Context of currently active requests to peerinfo
820 * for validation of HELLOs.
822 struct CheckHelloValidatedContext
826 * This is a doubly-linked list.
828 struct CheckHelloValidatedContext *next;
831 * This is a doubly-linked list.
833 struct CheckHelloValidatedContext *prev;
836 * Hello that we are validating.
838 const struct GNUNET_HELLO_Message *hello;
841 * Context for peerinfo iteration.
842 * NULL after we are done processing peerinfo's information.
844 struct GNUNET_PEERINFO_IteratorContext *piter;
847 * Was a HELLO known for this peer to peerinfo?
852 * Number of validation entries currently referring to this
855 unsigned int ve_count;
858 struct ATS_quality_metric
867 struct ATS_mechanism * prev;
868 struct ATS_mechanism * next;
869 struct ForeignAddressList * addr;
870 struct TransportPlugin * plugin;
871 struct ATS_peer * peer;
874 struct ATS_ressource_cost * rc;
880 struct GNUNET_PeerIdentity peer;
881 struct NeighbourList * n;
882 struct ATS_mechanism * m_head;
883 struct ATS_mechanism * m_tail;
885 /* preference value f */
893 * result of last GLPK run
899 * Ressource costs or quality metrics changed
900 * update problem before solving
902 int modified_resources;
905 * Ressource costs or quality metrics changed, update matrix
906 * update problem before solving
908 int modified_quality;
911 * Peers have connected or disconnected
912 * problem has to be recreated
914 int recreate_problem;
917 * Was the available basis invalid and we needed to rerun simplex?
919 int simplex_rerun_required;
922 * is problem currently valid and can it be solved
927 * Number of transport mechanisms in the problem
932 * Number of transport mechanisms in the problem
937 * row index where quality related rows start
942 * row index where quality related rows end
947 * row index where ressource cost related rows start
952 * row index where ressource cost related rows end
957 * column index for objective function value d
962 * column index for objective function value u
967 * column index for objective function value r
972 * column index for objective function value quality metrics
977 * column index for objective function value cost ressources
982 struct ATS_ressource_entry
984 /* index in ressources array */
986 /* depending ATSi parameter to calculcate limits */
995 /* index in ressources array */
997 /* depending ATSi parameter to calculcate limits */
999 /* cfg option to load limits */
1006 /* cofficients for the specific plugins */
1016 static struct ATS_ressource ressources[] =
1018 /* FIXME: the coefficients for the specific plugins */
1019 {1, 7, "LAN_BW_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 1, 1, 2, 2, 1, 3},
1020 {2, 7, "WAN_BW_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 1, 1, 2, 2, 2, 3},
1021 {3, 4, "WLAN_ENERGY_LIMIT", 0, VERY_BIG_DOUBLE_VALUE, 0, 0, 0, 0, 0, 2, 1}
1023 {4, 4, "COST_ENERGY_CONSUMPTION", VERY_BIG_DOUBLE_VALUE},
1024 {5, 5, "COST_CONNECT", VERY_BIG_DOUBLE_VALUE},
1025 {6, 6, "COST_BANDWITH_AVAILABLE", VERY_BIG_DOUBLE_VALUE},
1026 {7, 7, "COST_NETWORK_OVERHEAD", VERY_BIG_DOUBLE_VALUE},*/
1029 static int available_ressources = 3;
1037 * Time of last execution
1039 struct GNUNET_TIME_Absolute last;
1041 * Minimum intervall between two executions
1043 struct GNUNET_TIME_Relative min_delta;
1045 * Regular intervall when execution is triggered
1047 struct GNUNET_TIME_Relative exec_interval;
1049 * Maximum execution time per calculation
1051 struct GNUNET_TIME_Relative max_exec_duration;
1055 * GLPK (MLP) problem object
1061 * task to recalculate the bandwidth assignment
1063 GNUNET_SCHEDULER_TaskIdentifier ats_task;
1066 * Current state of the GLPK problem
1068 struct ATS_stat stat;
1071 * mechanisms used in current problem
1072 * needed for problem modification
1074 struct ATS_mechanism * mechanisms;
1077 * peers used in current problem
1078 * needed for problem modification
1080 struct ATS_peer * peers;
1083 * number of successful executions
1085 int successful_executions;
1088 * number with an invalid result
1090 int invalid_executions;
1093 * Maximum number of LP iterations per calculation
1098 * Dump problem to a file?
1103 * Dump solution to a file
1108 * Dump solution when minimum peers:
1113 * Dump solution when minimum addresses:
1118 * Dump solution overwrite file:
1138 * Minimum bandwidth per peer
1143 * Minimum number of connections per peer
1150 * Our HELLO message.
1152 static struct GNUNET_HELLO_Message *our_hello;
1157 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
1162 static struct GNUNET_PeerIdentity my_identity;
1167 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
1170 * Our configuration.
1172 const struct GNUNET_CONFIGURATION_Handle *cfg;
1175 * Linked list of all clients to this service.
1177 static struct TransportClient *clients;
1180 * All loaded plugins.
1182 static struct TransportPlugin *plugins;
1185 * Handle to peerinfo service.
1187 static struct GNUNET_PEERINFO_Handle *peerinfo;
1190 * All known neighbours and their HELLOs.
1192 static struct NeighbourList *neighbours;
1195 * Number of neighbours we'd like to have.
1197 static uint32_t max_connect_per_transport;
1200 * Head of linked list.
1202 static struct CheckHelloValidatedContext *chvc_head;
1205 * Tail of linked list.
1207 static struct CheckHelloValidatedContext *chvc_tail;
1210 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
1211 * of the given peer that we are currently validating).
1213 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
1216 * Handle for reporting statistics.
1218 static struct GNUNET_STATISTICS_Handle *stats;
1221 * Identifier of 'refresh_hello' task.
1223 static GNUNET_SCHEDULER_TaskIdentifier hello_task;
1226 * Is transport service shutting down ?
1228 static int shutdown_in_progress;
1231 * Handle for ats information
1233 static struct ATS_info *ats;
1235 struct ATS_quality_entry
1243 static struct ATS_quality_metric qm[] =
1245 {1, 1028, "QUALITY_NET_DISTANCE"},
1246 {2, 1034, "QUALITY_NET_DELAY"},
1248 static int available_quality_metrics = 2;
1252 * The peer specified by the given neighbour has timed-out or a plugin
1253 * has disconnected. We may either need to do nothing (other plugins
1254 * still up), or trigger a full disconnect and clean up. This
1255 * function updates our state and do the necessary notifications.
1256 * Also notifies our clients that the neighbour is now officially
1259 * @param n the neighbour list entry for the peer
1260 * @param check should we just check if all plugins
1261 * disconnected or must we ask all plugins to
1264 static void disconnect_neighbour (struct NeighbourList *n, int check);
1267 * Check the ready list for the given neighbour and if a plugin is
1268 * ready for transmission (and if we have a message), do so!
1270 * @param nexi target peer for which to transmit
1272 static void try_transmission_to_peer (struct NeighbourList *n);
1274 static void ats_shutdown ( );
1276 static void ats_notify_peer_connect (
1277 const struct GNUNET_PeerIdentity *peer,
1278 const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count);
1280 static void ats_notify_peer_disconnect (
1281 const struct GNUNET_PeerIdentity *peer);
1284 static void ats_notify_ats_data (
1285 const struct GNUNET_PeerIdentity *peer,
1286 const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
1289 struct ForeignAddressList * ats_get_preferred_address (
1290 struct NeighbourList *n);
1293 ats_calculate_bandwidth_distribution ();
1296 * Find an entry in the neighbour list for a particular peer.
1298 * @return NULL if not found.
1300 static struct NeighbourList *
1301 find_neighbour (const struct GNUNET_PeerIdentity *key)
1303 struct NeighbourList *head = neighbours;
1305 while ((head != NULL) &&
1306 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
1311 static int update_addr_value (struct ForeignAddressList *fal, uint32_t value , int ats_index)
1314 int set = GNUNET_NO;
1315 for (c=0; c<available_quality_metrics; c++)
1317 if (ats_index == qm[c].atis_index)
1319 fal->quality[c].values[0] = fal->quality[c].values[1];
1320 fal->quality[c].values[1] = fal->quality[c].values[2];
1321 fal->quality[c].values[2] = value;
1323 ats->stat.modified_quality = GNUNET_YES;
1326 if (set == GNUNET_NO)
1328 for (c=0; c<available_ressources; c++)
1330 if (ats_index == ressources[c].atis_index)
1332 fal->ressources[c].c = value;
1334 ats->stat.modified_resources = GNUNET_YES;
1343 update_addr_ats (struct ForeignAddressList *fal,
1344 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
1349 for (c1=0; c1<ats_count; c1++)
1351 set = update_addr_value(fal, ntohl(ats_data[c1].value), ntohl(ats_data[c1].type));
1357 * Find an entry in the transport list for a particular transport.
1359 * @return NULL if not found.
1361 static struct TransportPlugin *
1362 find_transport (const char *short_name)
1364 struct TransportPlugin *head = plugins;
1365 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
1371 * Is a particular peer blacklisted for a particular transport?
1373 * @param peer the peer to check for
1374 * @param plugin the plugin used to connect to the peer
1376 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
1379 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
1382 if (plugin->blacklist != NULL)
1384 if (GNUNET_CONTAINER_multihashmap_contains (plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
1387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1388 "Peer `%s:%s' is blacklisted!\n",
1389 plugin->short_name, GNUNET_i2s (peer));
1392 GNUNET_STATISTICS_update (stats, "# blacklisted peers refused", 1, GNUNET_NO);
1402 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer,
1403 char *transport_name)
1405 struct TransportPlugin *plugin;
1407 plugin = find_transport(transport_name);
1408 if (plugin == NULL) /* Nothing to do */
1411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412 "Adding peer `%s' with plugin `%s' to blacklist\n",
1416 if (plugin->blacklist == NULL)
1417 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
1418 GNUNET_assert(plugin->blacklist != NULL);
1419 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
1421 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1426 * Read the blacklist file, containing transport:peer entries.
1427 * Provided the transport is loaded, set up hashmap with these
1428 * entries to blacklist peers by transport.
1432 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1439 struct GNUNET_PeerIdentity pid;
1441 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1442 unsigned int entries_found;
1443 char *transport_name;
1446 GNUNET_CONFIGURATION_get_value_filename (cfg,
1452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1453 "Option `%s' in section `%s' not specified!\n",
1459 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1460 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1461 | GNUNET_DISK_PERM_USER_WRITE);
1462 if (0 != STAT (fn, &frstat))
1464 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1465 _("Could not read blacklist file `%s'\n"), fn);
1469 if (frstat.st_size == 0)
1472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1473 _("Blacklist file `%s' is empty.\n"),
1479 /* FIXME: use mmap */
1480 data = GNUNET_malloc_large (frstat.st_size);
1481 GNUNET_assert(data != NULL);
1482 if (frstat.st_size !=
1483 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1485 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1486 _("Failed to read blacklist from `%s'\n"), fn);
1493 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1495 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1496 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1499 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1502 if (colon_pos >= frstat.st_size)
1504 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1505 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1506 (unsigned long long) colon_pos);
1512 if (isspace( (unsigned char) data[colon_pos]))
1514 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1515 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1516 (unsigned long long) colon_pos);
1518 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1522 tsize = colon_pos - pos;
1523 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1525 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1526 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1527 (unsigned long long) colon_pos);
1536 transport_name = GNUNET_malloc(tsize + 1);
1537 memcpy(transport_name, &data[pos], tsize);
1538 pos = colon_pos + 1;
1540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1541 "Read transport name %s in blacklist file.\n",
1544 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1545 if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1547 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1548 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1549 (unsigned long long) pos);
1551 while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1553 GNUNET_free_non_null(transport_name);
1556 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1557 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1559 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1560 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1561 (unsigned long long) pos,
1566 if (0 != memcmp (&pid,
1568 sizeof (struct GNUNET_PeerIdentity)))
1571 add_peer_to_blacklist (&pid,
1576 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1577 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1581 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1582 GNUNET_free_non_null(transport_name);
1583 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1586 GNUNET_STATISTICS_update (stats, "# Transport entries blacklisted", entries_found, GNUNET_NO);
1593 * Function called to notify a client about the socket being ready to
1594 * queue more data. "buf" will be NULL and "size" zero if the socket
1595 * was closed for writing in the meantime.
1597 * @param cls closure
1598 * @param size number of bytes available in buf
1599 * @param buf where the callee should write the message
1600 * @return number of bytes written to buf
1603 transmit_to_client_callback (void *cls, size_t size, void *buf)
1605 struct TransportClient *client = cls;
1606 struct ClientMessageQueueEntry *q;
1609 const struct GNUNET_MessageHeader *msg;
1616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617 "Transmission to client failed, closing connection.\n");
1619 /* fatal error with client, free message queue! */
1620 while (NULL != (q = client->message_queue_head))
1622 GNUNET_STATISTICS_update (stats,
1623 gettext_noop ("# bytes discarded (could not transmit to client)"),
1624 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1626 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1627 client->message_queue_tail,
1631 client->message_count = 0;
1636 while (NULL != (q = client->message_queue_head))
1638 msg = (const struct GNUNET_MessageHeader *) &q[1];
1639 msize = ntohs (msg->size);
1640 if (msize + tsize > size)
1643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1644 "Transmitting message of type %u to client.\n",
1647 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1648 client->message_queue_tail,
1650 memcpy (&cbuf[tsize], msg, msize);
1653 client->message_count--;
1657 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1658 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1660 GNUNET_TIME_UNIT_FOREVER_REL,
1661 &transmit_to_client_callback,
1663 GNUNET_assert (client->th != NULL);
1670 * Convert an address to a string.
1672 * @param plugin name of the plugin responsible for the address
1673 * @param addr binary address
1674 * @param addr_len number of bytes in addr
1675 * @return NULL on error, otherwise address string
1678 a2s (const char *plugin,
1682 struct TransportPlugin *p;
1686 p = find_transport (plugin);
1687 if ((p == NULL) || (addr_len == 0) || (addr == NULL))
1690 return p->api->address_to_string (NULL,
1700 * Iterator to free entries in the validation_map.
1702 * @param cls closure (unused)
1703 * @param key current key code
1704 * @param value value in the hash map (validation to abort)
1705 * @return GNUNET_YES (always)
1708 abort_validation (void *cls,
1709 const GNUNET_HashCode * key,
1712 struct ValidationEntry *va = value;
1714 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
1715 GNUNET_SCHEDULER_cancel (va->timeout_task);
1716 GNUNET_free (va->transport_name);
1717 if (va->chvc != NULL)
1719 va->chvc->ve_count--;
1720 if (va->chvc->ve_count == 0)
1722 GNUNET_CONTAINER_DLL_remove (chvc_head,
1725 GNUNET_free (va->chvc);
1735 * HELLO validation cleanup task (validation failed).
1737 * @param cls the 'struct ValidationEntry' that failed
1738 * @param tc scheduler context (unused)
1741 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1743 struct ValidationEntry *va = cls;
1744 struct GNUNET_PeerIdentity pid;
1746 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1747 GNUNET_STATISTICS_update (stats,
1748 gettext_noop ("# address validation timeouts"),
1751 GNUNET_CRYPTO_hash (&va->publicKey,
1753 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1755 GNUNET_break (GNUNET_OK ==
1756 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1759 abort_validation (NULL, NULL, va);
1765 * Send the specified message to the specified client. Since multiple
1766 * messages may be pending for the same client at a time, this code
1767 * makes sure that no message is lost.
1769 * @param client client to transmit the message to
1770 * @param msg the message to send
1771 * @param may_drop can this message be dropped if the
1772 * message queue for this client is getting far too large?
1775 transmit_to_client (struct TransportClient *client,
1776 const struct GNUNET_MessageHeader *msg, int may_drop)
1778 struct ClientMessageQueueEntry *q;
1781 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1783 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1785 ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1788 client->message_count,
1790 GNUNET_STATISTICS_update (stats,
1791 gettext_noop ("# messages dropped due to slow client"),
1796 msize = ntohs (msg->size);
1797 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1798 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1799 memcpy (&q[1], msg, msize);
1800 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1801 client->message_queue_tail,
1802 client->message_queue_tail,
1804 client->message_count++;
1805 if (client->th == NULL)
1807 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1809 GNUNET_TIME_UNIT_FOREVER_REL,
1810 &transmit_to_client_callback,
1812 GNUNET_assert (client->th != NULL);
1818 * Transmit a 'SEND_OK' notification to the given client for the
1821 * @param client who to notify
1822 * @param n neighbour to notify about, can be NULL (on failure)
1823 * @param target target of the transmission
1824 * @param result status code for the transmission request
1827 transmit_send_ok (struct TransportClient *client,
1828 struct NeighbourList *n,
1829 const struct GNUNET_PeerIdentity *target,
1832 struct SendOkMessage send_ok_msg;
1834 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1835 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1836 send_ok_msg.success = htonl (result);
1838 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1840 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1841 send_ok_msg.peer = *target;
1842 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1847 * Mark the given FAL entry as 'connected' (and hence preferred for
1848 * sending); also mark all others for the same peer as 'not connected'
1849 * (since only one can be preferred).
1851 * @param fal address to set to 'connected'
1854 mark_address_connected (struct ForeignAddressList *fal);
1858 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1859 * upon "completion" of a send request. This tells the API
1860 * that it is now legal to send another message to the given
1863 * @param cls closure, identifies the entry on the
1864 * message queue that was transmitted and the
1865 * client responsible for queuing the message
1866 * @param target the peer receiving the message
1867 * @param result GNUNET_OK on success, if the transmission
1868 * failed, we should not tell the client to transmit
1872 transmit_send_continuation (void *cls,
1873 const struct GNUNET_PeerIdentity *target,
1876 struct MessageQueue *mq = cls;
1877 struct NeighbourList *n;
1879 GNUNET_STATISTICS_update (stats,
1880 gettext_noop ("# bytes pending with plugins"),
1881 - (int64_t) mq->message_buf_size,
1883 if (result == GNUNET_OK)
1885 GNUNET_STATISTICS_update (stats,
1886 gettext_noop ("# bytes successfully transmitted by plugins"),
1887 mq->message_buf_size,
1892 GNUNET_STATISTICS_update (stats,
1893 gettext_noop ("# bytes with transmission failure by plugins"),
1894 mq->message_buf_size,
1897 if (mq->specific_address != NULL)
1899 if (result == GNUNET_OK)
1901 mq->specific_address->timeout =
1902 GNUNET_TIME_relative_to_absolute
1903 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1904 if (mq->specific_address->validated == GNUNET_YES)
1905 mark_address_connected (mq->specific_address);
1909 if (mq->specific_address->connected != GNUNET_NO)
1912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1913 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1914 a2s (mq->specific_address->ready_list->plugin->short_name,
1915 mq->specific_address->addr,
1916 mq->specific_address->addrlen));
1918 GNUNET_STATISTICS_update (stats,
1919 gettext_noop ("# connected addresses"),
1922 mq->specific_address->connected = GNUNET_NO;
1925 if (! mq->internal_msg)
1926 mq->specific_address->in_transmit = GNUNET_NO;
1928 n = find_neighbour(&mq->neighbour_id);
1929 if (mq->client != NULL)
1930 transmit_send_ok (mq->client, n, target, result);
1933 GNUNET_CONTAINER_DLL_remove (n->cont_head,
1939 try_transmission_to_peer (n);
1944 * We should re-try transmitting to the given peer,
1945 * hopefully we've learned something in the meantime.
1948 retry_transmission_task (void *cls,
1949 const struct GNUNET_SCHEDULER_TaskContext *tc)
1951 struct NeighbourList *n = cls;
1953 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1954 try_transmission_to_peer (n);
1959 * Check the ready list for the given neighbour and if a plugin is
1960 * ready for transmission (and if we have a message), do so!
1962 * @param neighbour target peer for which to transmit
1965 try_transmission_to_peer (struct NeighbourList *n)
1967 struct ReadyList *rl;
1968 struct MessageQueue *mq;
1969 struct GNUNET_TIME_Relative timeout;
1973 if (n->messages_head == NULL)
1976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1977 "Transmission queue for `%4s' is empty\n",
1978 GNUNET_i2s (&n->id));
1980 return; /* nothing to do */
1983 mq = n->messages_head;
1984 force_address = GNUNET_YES;
1985 if (mq->specific_address == NULL)
1988 mq->specific_address = ats_get_preferred_address(n);
1989 GNUNET_STATISTICS_update (stats,
1990 gettext_noop ("# transport selected peer address freely"),
1993 force_address = GNUNET_NO;
1995 if (mq->specific_address == NULL)
1997 GNUNET_STATISTICS_update (stats,
1998 gettext_noop ("# transport failed to selected peer address"),
2001 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
2002 if (timeout.rel_value == 0)
2005 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2006 "No destination address available to transmit message of size %u to peer `%4s'\n",
2007 mq->message_buf_size,
2008 GNUNET_i2s (&mq->neighbour_id));
2010 GNUNET_STATISTICS_update (stats,
2011 gettext_noop ("# bytes in message queue for other peers"),
2012 - (int64_t) mq->message_buf_size,
2014 GNUNET_STATISTICS_update (stats,
2015 gettext_noop ("# bytes discarded (no destination address available)"),
2016 mq->message_buf_size,
2018 if (mq->client != NULL)
2019 transmit_send_ok (mq->client, n, &n->id, GNUNET_NO);
2020 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2024 return; /* nobody ready */
2026 GNUNET_STATISTICS_update (stats,
2027 gettext_noop ("# message delivery deferred (no address)"),
2030 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2031 GNUNET_SCHEDULER_cancel (n->retry_task);
2032 n->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
2033 &retry_transmission_task,
2036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2037 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
2038 mq->message_buf_size,
2039 GNUNET_i2s (&mq->neighbour_id),
2042 /* FIXME: might want to trigger peerinfo lookup here
2043 (unless that's already pending...) */
2046 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2049 if (mq->specific_address->connected == GNUNET_NO)
2050 mq->specific_address->connect_attempts++;
2051 rl = mq->specific_address->ready_list;
2052 mq->plugin = rl->plugin;
2053 if (!mq->internal_msg)
2054 mq->specific_address->in_transmit = GNUNET_YES;
2056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2057 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
2058 mq->message_buf_size,
2059 GNUNET_i2s (&n->id),
2060 (mq->specific_address->addr != NULL)
2061 ? a2s (mq->plugin->short_name,
2062 mq->specific_address->addr,
2063 mq->specific_address->addrlen)
2065 rl->plugin->short_name);
2067 GNUNET_STATISTICS_update (stats,
2068 gettext_noop ("# bytes in message queue for other peers"),
2069 - (int64_t) mq->message_buf_size,
2071 GNUNET_STATISTICS_update (stats,
2072 gettext_noop ("# bytes pending with plugins"),
2073 mq->message_buf_size,
2076 GNUNET_CONTAINER_DLL_insert (n->cont_head,
2080 ret = rl->plugin->api->send (rl->plugin->api->cls,
2083 mq->message_buf_size,
2085 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2086 mq->specific_address->session,
2087 mq->specific_address->addr,
2088 mq->specific_address->addrlen,
2090 &transmit_send_continuation, mq);
2093 /* failure, but 'send' would not call continuation in this case,
2094 so we need to do it here! */
2095 transmit_send_continuation (mq,
2103 * Send the specified message to the specified peer.
2105 * @param client source of the transmission request (can be NULL)
2106 * @param peer_address ForeignAddressList where we should send this message
2107 * @param priority how important is the message
2108 * @param timeout how long do we have to transmit?
2109 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
2110 * @param message_buf_size total size of all messages in message_buf
2111 * @param is_internal is this an internal message; these are pre-pended and
2112 * also do not count for plugins being "ready" to transmit
2113 * @param neighbour handle to the neighbour for transmission
2116 transmit_to_peer (struct TransportClient *client,
2117 struct ForeignAddressList *peer_address,
2118 unsigned int priority,
2119 struct GNUNET_TIME_Relative timeout,
2120 const char *message_buf,
2121 size_t message_buf_size,
2122 int is_internal, struct NeighbourList *neighbour)
2124 struct MessageQueue *mq;
2129 /* check for duplicate submission */
2130 mq = neighbour->messages_head;
2133 if (mq->client == client)
2135 /* client transmitted to same peer twice
2136 before getting SEND_OK! */
2144 GNUNET_STATISTICS_update (stats,
2145 gettext_noop ("# bytes in message queue for other peers"),
2148 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
2149 mq->specific_address = peer_address;
2150 mq->client = client;
2151 /* FIXME: this memcpy can be up to 7% of our total runtime! */
2152 memcpy (&mq[1], message_buf, message_buf_size);
2153 mq->message_buf = (const char*) &mq[1];
2154 mq->message_buf_size = message_buf_size;
2155 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2156 mq->internal_msg = is_internal;
2157 mq->priority = priority;
2158 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2160 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
2161 neighbour->messages_tail,
2164 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
2165 neighbour->messages_tail,
2166 neighbour->messages_tail,
2168 try_transmission_to_peer (neighbour);
2173 * Send a plain PING (without address or our HELLO) to the given
2174 * foreign address to try to establish a connection (and validate
2175 * that the other peer is really who he claimed he is).
2177 * @param n neighbour to PING
2180 transmit_plain_ping (struct NeighbourList *n)
2182 struct ValidationEntry *ve;
2183 struct TransportPingMessage ping;
2184 struct ReadyList *rl;
2185 struct TransportPlugin *plugin;
2186 struct ForeignAddressList *fal;
2188 if (! n->public_key_valid)
2190 /* This should not happen since the other peer
2191 should send us a HELLO prior to sending his
2193 GNUNET_break_op (0);
2194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2195 "Could not transmit plain PING to `%s': public key not known\n",
2196 GNUNET_i2s (&n->id));
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "Looking for addresses to transmit plain PING to `%s'\n",
2201 GNUNET_i2s (&n->id));
2202 for (rl = n->plugins; rl != NULL; rl = rl->next)
2204 plugin = rl->plugin;
2205 for (fal = rl->addresses; fal != NULL; fal = fal->next)
2207 if (! fal->connected)
2209 ve = GNUNET_malloc (sizeof (struct ValidationEntry));
2210 ve->transport_name = GNUNET_strdup (plugin->short_name);
2211 ve->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2213 ve->send_time = GNUNET_TIME_absolute_get();
2214 ve->session = fal->session;
2215 memcpy(&ve->publicKey,
2217 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2218 ve->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
2219 &timeout_hello_validation,
2221 GNUNET_CONTAINER_multihashmap_put (validation_map,
2224 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2225 ping.header.size = htons(sizeof(struct TransportPingMessage));
2226 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2227 ping.challenge = htonl(ve->challenge);
2228 memcpy(&ping.target, &n->id, sizeof(struct GNUNET_PeerIdentity));
2229 GNUNET_STATISTICS_update (stats,
2230 gettext_noop ("# PING without HELLO messages sent"),
2233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234 "Transmitting plain PING to `%s'\n",
2235 GNUNET_i2s (&n->id));
2236 transmit_to_peer (NULL,
2238 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2239 HELLO_VERIFICATION_TIMEOUT,
2240 (const char*) &ping, sizeof (ping),
2248 * Mark the given FAL entry as 'connected' (and hence preferred for
2249 * sending); also mark all others for the same peer as 'not connected'
2250 * (since only one can be preferred).
2252 * @param fal address to set to 'connected'
2255 mark_address_connected (struct ForeignAddressList *fal)
2257 struct ForeignAddressList *pos;
2260 GNUNET_assert (GNUNET_YES == fal->validated);
2261 if (fal->connected == GNUNET_YES)
2262 return; /* nothing to do */
2264 pos = fal->ready_list->addresses;
2267 if (GNUNET_YES == pos->connected)
2270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2271 "Marking address `%s' as no longer connected (due to connect on other address)\n",
2272 a2s (pos->ready_list->plugin->short_name,
2276 GNUNET_break (cnt == GNUNET_YES);
2278 pos->connected = GNUNET_NO;
2279 GNUNET_STATISTICS_update (stats,
2280 gettext_noop ("# connected addresses"),
2286 fal->connected = GNUNET_YES;
2287 if (GNUNET_YES == cnt)
2289 GNUNET_STATISTICS_update (stats,
2290 gettext_noop ("# connected addresses"),
2298 * Find an address in any of the available transports for
2299 * the given neighbour that would be good for message
2300 * transmission. This is essentially the transport selection
2303 * @param neighbour for whom to select an address
2304 * @return selected address, NULL if we have none
2306 struct ForeignAddressList *
2307 find_ready_address(struct NeighbourList *neighbour)
2309 struct ReadyList *head = neighbour->plugins;
2310 struct ForeignAddressList *addresses;
2311 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
2312 struct ForeignAddressList *best_address;
2314 /* Hack to prefer unix domain sockets */
2315 struct ForeignAddressList *unix_address = NULL;
2317 best_address = NULL;
2318 while (head != NULL)
2320 addresses = head->addresses;
2321 while (addresses != NULL)
2323 if ( (addresses->timeout.abs_value < now.abs_value) &&
2324 (addresses->connected == GNUNET_YES) )
2327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328 "Marking long-time inactive connection to `%4s' as down.\n",
2329 GNUNET_i2s (&neighbour->id));
2331 GNUNET_STATISTICS_update (stats,
2332 gettext_noop ("# connected addresses"),
2335 addresses->connected = GNUNET_NO;
2337 addresses = addresses->next;
2340 addresses = head->addresses;
2341 while (addresses != NULL)
2344 if (addresses->addr != NULL)
2345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2346 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
2347 a2s (head->plugin->short_name,
2349 addresses->addrlen),
2350 GNUNET_i2s (&neighbour->id),
2351 addresses->connected,
2352 addresses->in_transmit,
2353 addresses->validated,
2354 addresses->connect_attempts,
2355 (unsigned long long) addresses->timeout.abs_value,
2356 (unsigned int) addresses->distance);
2358 if (0==strcmp(head->plugin->short_name,"unix"))
2360 if ( (unix_address == NULL) ||
2361 ( (unix_address != NULL) &&
2362 (addresses->latency.rel_value < unix_address->latency.rel_value) ) )
2363 unix_address = addresses;
2365 if ( ( (best_address == NULL) ||
2366 (addresses->connected == GNUNET_YES) ||
2367 (best_address->connected == GNUNET_NO) ) &&
2368 (addresses->in_transmit == GNUNET_NO) &&
2369 ( (best_address == NULL) ||
2370 (addresses->latency.rel_value < best_address->latency.rel_value)) )
2371 best_address = addresses;
2372 /* FIXME: also give lower-latency addresses that are not
2373 connected a chance some times... */
2374 addresses = addresses->next;
2376 if (unix_address != NULL)
2380 if (unix_address != NULL)
2382 best_address = unix_address;
2384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2385 "Found UNIX address, forced this address\n");
2388 if (best_address != NULL)
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392 "Best address found (`%s') has latency of %llu ms.\n",
2393 (best_address->addrlen > 0)
2394 ? a2s (best_address->ready_list->plugin->short_name,
2396 best_address->addrlen)
2398 best_address->latency.rel_value);
2403 GNUNET_STATISTICS_update (stats,
2404 gettext_noop ("# transmission attempts failed (no address)"),
2409 return best_address;
2417 struct GeneratorContext
2419 struct TransportPlugin *plug_pos;
2420 struct OwnAddressList *addr_pos;
2421 struct GNUNET_TIME_Absolute expiration;
2429 address_generator (void *cls, size_t max, void *buf)
2431 struct GeneratorContext *gc = cls;
2434 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
2436 gc->plug_pos = gc->plug_pos->next;
2437 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
2439 if (NULL == gc->plug_pos)
2444 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
2447 gc->addr_pos->addrlen, buf, max);
2448 gc->addr_pos = gc->addr_pos->next;
2454 * Construct our HELLO message from all of the addresses of
2455 * all of the transports.
2458 * @param tc scheduler context
2461 refresh_hello_task (void *cls,
2462 const struct GNUNET_SCHEDULER_TaskContext *tc)
2464 struct GNUNET_HELLO_Message *hello;
2465 struct TransportClient *cpos;
2466 struct NeighbourList *npos;
2467 struct GeneratorContext gc;
2469 hello_task = GNUNET_SCHEDULER_NO_TASK;
2470 gc.plug_pos = plugins;
2471 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
2472 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2473 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2476 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
2478 GNUNET_STATISTICS_update (stats,
2479 gettext_noop ("# refreshed my HELLO"),
2483 while (cpos != NULL)
2485 transmit_to_client (cpos,
2486 (const struct GNUNET_MessageHeader *) hello,
2491 GNUNET_free_non_null (our_hello);
2493 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
2494 for (npos = neighbours; npos != NULL; npos = npos->next)
2496 if (! npos->received_pong)
2499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2500 "Transmitting updated `%s' to neighbour `%4s'\n",
2501 "HELLO", GNUNET_i2s (&npos->id));
2503 GNUNET_STATISTICS_update (stats,
2504 gettext_noop ("# transmitted my HELLO to other peers"),
2507 transmit_to_peer (NULL, NULL, 0,
2508 HELLO_ADDRESS_EXPIRATION,
2509 (const char *) our_hello,
2510 GNUNET_HELLO_size(our_hello),
2517 * Schedule task to refresh hello (unless such a
2518 * task exists already).
2523 if (hello_task != GNUNET_SCHEDULER_NO_TASK)
2526 = GNUNET_SCHEDULER_add_now (&refresh_hello_task,
2532 * Iterator over hash map entries that NULLs the session of validation
2533 * entries that match the given session.
2535 * @param cls closure (the 'struct Session*' to match against)
2536 * @param key current key code (peer ID, not used)
2537 * @param value value in the hash map ('struct ValidationEntry*')
2538 * @return GNUNET_YES (we should continue to iterate)
2541 remove_session_validations (void *cls,
2542 const GNUNET_HashCode * key,
2545 struct Session *session = cls;
2546 struct ValidationEntry *ve = value;
2548 if (session == ve->session)
2555 * We've been disconnected from the other peer (for some
2556 * connection-oriented transport). Either quickly
2557 * re-establish the connection or signal the disconnect
2560 * Only signal CORE level disconnect if ALL addresses
2561 * for the peer are exhausted.
2563 * @param p overall plugin context
2564 * @param nl neighbour that was disconnected
2567 try_fast_reconnect (struct TransportPlugin *p,
2568 struct NeighbourList *nl)
2570 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2571 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2572 "try_fast_reconnect not implemented!\n");
2573 /* Note: the idea here is to hide problems with transports (or
2574 switching between plugins) from the core to eliminate the need to
2575 re-negotiate session keys and the like; OTOH, we should tell core
2576 quickly (much faster than timeout) `if a connection was lost and
2577 could not be re-established (i.e. other peer went down or is
2578 unable / refuses to communicate);
2580 So we should consider:
2581 1) ideally: our own willingness / need to connect
2582 2) prior failures to connect to this peer (by plugin)
2583 3) ideally: reasons why other peer terminated (as far as knowable)
2585 Most importantly, it must be POSSIBLE for another peer to terminate
2586 a connection for a while (without us instantly re-establishing it).
2587 Similarly, if another peer is gone we should quickly notify CORE.
2588 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2589 on the other end), we should reconnect in such a way that BOTH CORE
2590 services never even notice.
2591 Furthermore, the same mechanism (or small variation) could be used
2592 to switch to a better-performing plugin (ATS).
2594 Finally, this needs to be tested throughly... */
2597 * GNUNET_NO in the call below makes transport disconnect the peer,
2598 * even if only a single address (out of say, six) went away. This
2599 * function must be careful to ONLY disconnect if the peer is gone,
2600 * not just a specific address.
2602 * More specifically, half the places it was used had it WRONG.
2605 /* No reconnect, signal disconnect instead! */
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2609 "try_fast_reconnect");
2611 GNUNET_STATISTICS_update (stats,
2612 gettext_noop ("# disconnects due to try_fast_reconnect"),
2616 disconnect_neighbour (nl, GNUNET_YES);
2622 * Function that will be called whenever the plugin internally
2623 * cleans up a session pointer and hence the service needs to
2624 * discard all of those sessions as well. Plugins that do not
2625 * use sessions can simply omit calling this function and always
2626 * use NULL wherever a session pointer is needed.
2628 * @param cls closure
2629 * @param peer which peer was the session for
2630 * @param session which session is being destoyed
2633 plugin_env_session_end (void *cls,
2634 const struct GNUNET_PeerIdentity *peer,
2635 struct Session *session)
2637 struct TransportPlugin *p = cls;
2638 struct NeighbourList *nl;
2639 struct ReadyList *rl;
2640 struct ForeignAddressList *pos;
2641 struct ForeignAddressList *prev;
2644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645 "Session ended with peer `%4s', %s\n",
2647 "plugin_env_session_end");
2649 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2650 &remove_session_validations,
2652 nl = find_neighbour (peer);
2656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657 "No neighbour record found for peer `%4s'\n",
2660 return; /* was never marked as connected */
2665 if (rl->plugin == p)
2672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673 "Plugin was associated with peer `%4s'\n",
2676 GNUNET_STATISTICS_update (stats,
2677 gettext_noop ("# disconnects due to session end"),
2680 disconnect_neighbour (nl, GNUNET_YES);
2684 pos = rl->addresses;
2685 while ( (pos != NULL) &&
2686 (pos->session != session) )
2694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2695 "Session was never marked as ready for peer `%4s'\n",
2698 //FIXME: This conflicts with inbound tcp connections and tcp nat ... debugging in progress
2699 GNUNET_STATISTICS_update (stats,
2700 gettext_noop ("# disconnects due to unready session"),
2703 disconnect_neighbour (nl, GNUNET_YES);
2704 return; /* was never marked as connected */
2706 pos->session = NULL;
2707 pos->connected = GNUNET_NO;
2708 if (pos->addrlen != 0)
2710 if (nl->received_pong != GNUNET_NO)
2712 GNUNET_STATISTICS_update (stats,
2713 gettext_noop ("# try_fast_reconnect thanks to plugin_env_session_end"),
2716 if (GNUNET_YES == pos->connected)
2717 try_fast_reconnect (p, nl);
2721 GNUNET_STATISTICS_update (stats,
2722 gettext_noop ("# disconnects due to missing pong"),
2725 if (GNUNET_YES == pos->connected)
2726 disconnect_neighbour (nl, GNUNET_YES);
2730 /* was inbound connection, free 'pos' */
2732 rl->addresses = pos->next;
2734 prev->next = pos->next;
2735 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2737 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2738 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2740 GNUNET_free_non_null(pos->ressources);
2741 GNUNET_free_non_null(pos->quality);
2742 if (GNUNET_YES != pos->connected)
2744 /* nothing else to do, connection was never up... */
2749 ats->stat.recreate_problem = GNUNET_YES;
2750 if (nl->received_pong == GNUNET_NO)
2752 GNUNET_STATISTICS_update (stats,
2753 gettext_noop ("# disconnects due to NO pong"),
2756 disconnect_neighbour (nl, GNUNET_YES);
2757 return; /* nothing to do, never connected... */
2759 /* check if we have any validated addresses left */
2760 pos = rl->addresses;
2763 if (GNUNET_YES == pos->validated)
2765 GNUNET_STATISTICS_update (stats,
2766 gettext_noop ("# try_fast_reconnect thanks to validated_address"),
2769 try_fast_reconnect (p, nl);
2774 /* no valid addresses left, signal disconnect! */
2777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2778 "Disconnecting peer `%4s', %s\n",
2780 "plugin_env_session_end");
2782 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2783 * it means there aren't any left for this PLUGIN/PEER combination! So
2784 * calling disconnect_neighbour here with GNUNET_NO forces disconnect
2785 * when it isn't necessary. Using GNUNET_YES at least checks to see
2786 * if there are any addresses that work first, so as not to overdo it.
2789 GNUNET_STATISTICS_update (stats,
2790 gettext_noop ("# disconnects due to plugin_env_session_end"),
2793 disconnect_neighbour (nl, GNUNET_YES);
2798 * Function that must be called by each plugin to notify the
2799 * transport service about the addresses under which the transport
2800 * provided by the plugin can be reached.
2802 * @param cls closure
2803 * @param add_remove GNUNET_YES to add, GNUNET_NO to remove the address
2804 * @param addr one of the addresses of the host, NULL for the last address
2805 * the specific address format depends on the transport
2806 * @param addrlen length of the address
2809 plugin_env_notify_address (void *cls,
2814 struct TransportPlugin *p = cls;
2815 struct OwnAddressList *al;
2816 struct OwnAddressList *prev;
2818 GNUNET_assert (p->api != NULL);
2821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2822 (add_remove == GNUNET_YES)
2823 ? "Adding `%s':%s to the set of our addresses\n"
2824 : "Removing `%s':%s from the set of our addresses\n",
2829 GNUNET_assert (addr != NULL);
2830 if (GNUNET_NO == add_remove)
2836 if ( (addrlen == al->addrlen) &&
2837 (0 == memcmp (addr, &al[1], addrlen)) )
2840 p->addresses = al->next;
2842 prev->next = al->next;
2853 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2854 al->next = p->addresses;
2856 al->addrlen = addrlen;
2857 memcpy (&al[1], addr, addrlen);
2863 * Notify all of our clients about a peer connecting.
2866 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2867 struct GNUNET_TIME_Relative latency,
2870 struct ConnectInfoMessage * cim;
2871 struct TransportClient *cpos;
2875 if (0 == memcmp (peer,
2877 sizeof (struct GNUNET_PeerIdentity)))
2883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2884 "Notifying clients about connection with `%s'\n",
2887 GNUNET_STATISTICS_update (stats,
2888 gettext_noop ("# peers connected"),
2893 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2894 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2898 cim = GNUNET_malloc (size);
2899 cim->header.size = htons (size);
2900 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2901 cim->ats_count = htonl(2);
2902 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2903 (&(cim->ats))[0].value = htonl (distance);
2904 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2905 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2906 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2907 (&(cim->ats))[2].value = htonl (0);
2908 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2910 /* notify ats about connecting peer */
2911 if (shutdown_in_progress == GNUNET_NO)
2912 ats_notify_peer_connect (peer, &(cim->ats), 2);
2915 while (cpos != NULL)
2917 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2926 * Notify all of our clients about a peer disconnecting.
2929 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2931 struct DisconnectInfoMessage dim;
2932 struct TransportClient *cpos;
2934 if (0 == memcmp (peer,
2936 sizeof (struct GNUNET_PeerIdentity)))
2942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2943 "Notifying clients about lost connection to `%s'\n",
2946 GNUNET_STATISTICS_update (stats,
2947 gettext_noop ("# peers connected"),
2950 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2951 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2952 dim.reserved = htonl (0);
2953 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2955 /* notify ats about connecting peer */
2956 if (shutdown_in_progress == GNUNET_NO)
2957 ats_notify_peer_disconnect (peer);
2960 while (cpos != NULL)
2962 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2969 * Find a ForeignAddressList entry for the given neighbour
2970 * that matches the given address and transport.
2972 * @param neighbour which peer we care about
2973 * @param tname name of the transport plugin
2974 * @param session session to look for, NULL for 'any'; otherwise
2975 * can be used for the service to "learn" this session ID
2977 * @param addr binary address
2978 * @param addrlen length of addr
2979 * @return NULL if no such entry exists
2981 static struct ForeignAddressList *
2982 find_peer_address(struct NeighbourList *neighbour,
2984 struct Session *session,
2988 struct ReadyList *head;
2989 struct ForeignAddressList *pos;
2991 head = neighbour->plugins;
2992 while (head != NULL)
2994 if (0 == strcmp (tname, head->plugin->short_name))
3000 pos = head->addresses;
3001 while ( (pos != NULL) &&
3002 ( (pos->addrlen != addrlen) ||
3003 (memcmp(pos->addr, addr, addrlen) != 0) ) )
3005 if ( (session != NULL) &&
3006 (pos->session == session) )
3010 if ( (session != NULL) && (pos != NULL) )
3011 pos->session = session; /* learn it! */
3017 * Get the peer address struct for the given neighbour and
3018 * address. If it doesn't yet exist, create it.
3020 * @param neighbour which peer we care about
3021 * @param tname name of the transport plugin
3022 * @param session session of the plugin, or NULL for none
3023 * @param addr binary address
3024 * @param addrlen length of addr
3025 * @return NULL if we do not have a transport plugin for 'tname'
3027 static struct ForeignAddressList *
3028 add_peer_address (struct NeighbourList *neighbour,
3030 struct Session *session,
3034 struct ReadyList *head;
3035 struct ForeignAddressList *ret;
3038 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
3041 head = neighbour->plugins;
3043 while (head != NULL)
3045 if (0 == strcmp (tname, head->plugin->short_name))
3051 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
3052 ret->session = session;
3053 if ((addrlen > 0) && (addr != NULL))
3055 ret->addr = (const char*) &ret[1];
3056 memcpy (&ret[1], addr, addrlen);
3063 ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
3064 for (c=0; c<available_ressources; c++)
3066 struct ATS_ressource_entry *r = ret->ressources;
3068 r[c].atis_index = ressources[c].atis_index;
3069 if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
3071 r[c].c = ressources[c].c_unix;
3073 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
3075 r[c].c = ressources[c].c_udp;
3077 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
3079 r[c].c = ressources[c].c_tcp;
3081 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
3083 r[c].c = ressources[c].c_http;
3085 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
3087 r[c].c = ressources[c].c_https;
3089 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
3091 r[c].c = ressources[c].c_wlan;
3095 r[c].c = ressources[c].c_default;
3096 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3097 "Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!\n",
3098 GNUNET_i2s(&neighbour->peer),
3099 neighbour->plugins->plugin->short_name);
3103 ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
3104 ret->addrlen = addrlen;
3105 ret->expires = GNUNET_TIME_relative_to_absolute
3106 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3107 ret->latency = GNUNET_TIME_relative_get_forever();
3109 ret->timeout = GNUNET_TIME_relative_to_absolute
3110 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3111 ret->ready_list = head;
3112 ret->next = head->addresses;
3113 head->addresses = ret;
3119 * Closure for 'add_validated_address'.
3121 struct AddValidatedAddressContext
3124 * Entry that has been validated.
3126 const struct ValidationEntry *ve;
3129 * Flag set after we have added the address so
3130 * that we terminate the iteration next time.
3137 * Callback function used to fill a buffer of max bytes with a list of
3138 * addresses in the format used by HELLOs. Should use
3139 * "GNUNET_HELLO_add_address" as a helper function.
3141 * @param cls the 'struct AddValidatedAddressContext' with the validated address
3142 * @param max maximum number of bytes that can be written to buf
3143 * @param buf where to write the address information
3144 * @return number of bytes written, 0 to signal the
3145 * end of the iteration.
3148 add_validated_address (void *cls,
3149 size_t max, void *buf)
3151 struct AddValidatedAddressContext *avac = cls;
3152 const struct ValidationEntry *ve = avac->ve;
3154 if (GNUNET_YES == avac->done)
3156 avac->done = GNUNET_YES;
3157 return GNUNET_HELLO_add_address (ve->transport_name,
3158 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
3168 * Closure for 'check_address_exists'.
3170 struct CheckAddressExistsClosure
3173 * Address to check for.
3178 * Name of the transport.
3185 struct Session *session;
3188 * Set to GNUNET_YES if the address exists.
3201 * Iterator over hash map entries. Checks if the given
3202 * validation entry is for the same address as what is given
3205 * @param cls the 'struct CheckAddressExistsClosure*'
3206 * @param key current key code (ignored)
3207 * @param value value in the hash map ('struct ValidationEntry')
3208 * @return GNUNET_YES if we should continue to
3209 * iterate (mismatch), GNUNET_NO if not (entry matched)
3212 check_address_exists (void *cls,
3213 const GNUNET_HashCode * key,
3216 struct CheckAddressExistsClosure *caec = cls;
3217 struct ValidationEntry *ve = value;
3219 if ( (0 == strcmp (caec->tname,
3220 ve->transport_name)) &&
3221 (caec->addrlen == ve->addrlen) &&
3222 (0 == memcmp (caec->addr,
3226 caec->exists = GNUNET_YES;
3229 if ( (ve->session != NULL) &&
3230 (caec->session == ve->session) )
3232 caec->exists = GNUNET_YES;
3240 neighbour_timeout_task (void *cls,
3241 const struct GNUNET_SCHEDULER_TaskContext *tc)
3243 struct NeighbourList *n = cls;
3246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3247 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
3249 GNUNET_STATISTICS_update (stats,
3250 gettext_noop ("# disconnects due to timeout"),
3253 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3254 disconnect_neighbour (n, GNUNET_NO);
3259 * Schedule the job that will cause us to send a PING to the
3260 * foreign address to evaluate its validity and latency.
3262 * @param fal address to PING
3265 schedule_next_ping (struct ForeignAddressList *fal);
3269 * Add the given address to the list of foreign addresses
3270 * available for the given peer (check for duplicates).
3272 * @param cls the respective 'struct NeighbourList' to update
3273 * @param tname name of the transport
3274 * @param expiration expiration time
3275 * @param addr the address
3276 * @param addrlen length of the address
3277 * @return GNUNET_OK (always)
3280 add_to_foreign_address_list (void *cls,
3282 struct GNUNET_TIME_Absolute expiration,
3286 struct NeighbourList *n = cls;
3287 struct ForeignAddressList *fal;
3290 GNUNET_STATISTICS_update (stats,
3291 gettext_noop ("# valid peer addresses returned by PEERINFO"),
3295 fal = find_peer_address (n, tname, NULL, addr, addrlen);
3298 #if DEBUG_TRANSPORT_HELLO
3299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3300 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
3301 a2s (tname, addr, addrlen),
3303 GNUNET_i2s (&n->id),
3304 expiration.abs_value);
3306 fal = add_peer_address (n, tname, NULL, addr, addrlen);
3309 GNUNET_STATISTICS_update (stats,
3310 gettext_noop ("# previously validated addresses lacking transport"),
3316 fal->expires = GNUNET_TIME_absolute_max (expiration,
3318 schedule_next_ping (fal);
3324 fal->expires = GNUNET_TIME_absolute_max (expiration,
3330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3331 "Failed to add new address for `%4s'\n",
3332 GNUNET_i2s (&n->id));
3336 if (fal->validated == GNUNET_NO)
3338 fal->validated = GNUNET_YES;
3339 GNUNET_STATISTICS_update (stats,
3340 gettext_noop ("# peer addresses considered valid"),
3344 if (try == GNUNET_YES)
3347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3348 "Have new addresses, will try to trigger transmissions.\n");
3350 try_transmission_to_peer (n);
3357 * Add addresses in validated HELLO "h" to the set of addresses
3358 * we have for this peer.
3360 * @param cls closure ('struct NeighbourList*')
3361 * @param peer id of the peer, NULL for last call
3362 * @param h hello message for the peer (can be NULL)
3363 * @param err_msg NULL if successful, otherwise contains error message
3366 add_hello_for_peer (void *cls,
3367 const struct GNUNET_PeerIdentity *peer,
3368 const struct GNUNET_HELLO_Message *h,
3369 const char *err_msg)
3371 struct NeighbourList *n = cls;
3373 if (err_msg != NULL)
3376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3377 _("Error in communication with PEERINFO service: %s\n"),
3384 GNUNET_STATISTICS_update (stats,
3385 gettext_noop ("# outstanding peerinfo iterate requests"),
3392 return; /* no HELLO available */
3394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3395 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
3399 if (GNUNET_YES != n->public_key_valid)
3401 GNUNET_HELLO_get_key (h, &n->publicKey);
3402 n->public_key_valid = GNUNET_YES;
3404 GNUNET_HELLO_iterate_addresses (h,
3406 &add_to_foreign_address_list,
3412 * Create a fresh entry in our neighbour list for the given peer.
3413 * Will try to transmit our current HELLO to the new neighbour.
3414 * Do not call this function directly, use 'setup_peer_check_blacklist.
3416 * @param peer the peer for which we create the entry
3417 * @param do_hello should we schedule transmitting a HELLO
3418 * @return the new neighbour list entry
3420 static struct NeighbourList *
3421 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
3424 struct NeighbourList *n;
3425 struct TransportPlugin *tp;
3426 struct ReadyList *rl;
3428 GNUNET_assert (0 != memcmp (peer,
3430 sizeof (struct GNUNET_PeerIdentity)));
3432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3433 "Setting up state for neighbour `%4s'\n",
3436 GNUNET_STATISTICS_update (stats,
3437 gettext_noop ("# active neighbours"),
3440 n = GNUNET_malloc (sizeof (struct NeighbourList));
3441 n->next = neighbours;
3445 GNUNET_TIME_relative_to_absolute
3446 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3447 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
3448 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
3449 MAX_BANDWIDTH_CARRY_S);
3453 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
3455 rl = GNUNET_malloc (sizeof (struct ReadyList));
3457 rl->next = n->plugins;
3460 rl->addresses = NULL;
3464 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
3466 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3467 &neighbour_timeout_task, n);
3470 GNUNET_STATISTICS_update (stats,
3471 gettext_noop ("# peerinfo new neighbor iterate requests"),
3474 GNUNET_STATISTICS_update (stats,
3475 gettext_noop ("# outstanding peerinfo iterate requests"),
3478 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
3479 GNUNET_TIME_UNIT_FOREVER_REL,
3480 &add_hello_for_peer, n);
3482 GNUNET_STATISTICS_update (stats,
3483 gettext_noop ("# HELLO's sent to new neighbors"),
3486 if (NULL != our_hello)
3487 transmit_to_peer (NULL, NULL, 0,
3488 HELLO_ADDRESS_EXPIRATION,
3489 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
3497 * Function called after we have checked if communicating
3498 * with a given peer is acceptable.
3500 * @param cls closure
3501 * @param n NULL if communication is not acceptable
3503 typedef void (*SetupContinuation)(void *cls,
3504 struct NeighbourList *n);
3508 * Information kept for each client registered to perform
3514 * This is a linked list.
3516 struct Blacklisters *next;
3519 * This is a linked list.
3521 struct Blacklisters *prev;
3524 * Client responsible for this entry.
3526 struct GNUNET_SERVER_Client *client;
3529 * Blacklist check that we're currently performing.
3531 struct BlacklistCheck *bc;
3537 * Head of DLL of blacklisting clients.
3539 static struct Blacklisters *bl_head;
3542 * Tail of DLL of blacklisting clients.
3544 static struct Blacklisters *bl_tail;
3548 * Context we use when performing a blacklist check.
3550 struct BlacklistCheck
3554 * This is a linked list.
3556 struct BlacklistCheck *next;
3559 * This is a linked list.
3561 struct BlacklistCheck *prev;
3564 * Peer being checked.
3566 struct GNUNET_PeerIdentity peer;
3569 * Option for setup neighbour afterwards.
3574 * Continuation to call with the result.
3576 SetupContinuation cont;
3584 * Current transmission request handle for this client, or NULL if no
3585 * request is pending.
3587 struct GNUNET_CONNECTION_TransmitHandle *th;
3590 * Our current position in the blacklisters list.
3592 struct Blacklisters *bl_pos;
3595 * Current task performing the check.
3597 GNUNET_SCHEDULER_TaskIdentifier task;
3602 * Head of DLL of active blacklisting queries.
3604 static struct BlacklistCheck *bc_head;
3607 * Tail of DLL of active blacklisting queries.
3609 static struct BlacklistCheck *bc_tail;
3613 * Perform next action in the blacklist check.
3615 * @param cls the 'struct BlacklistCheck*'
3619 do_blacklist_check (void *cls,
3620 const struct GNUNET_SCHEDULER_TaskContext *tc);
3623 * Transmit blacklist query to the client.
3625 * @param cls the 'struct BlacklistCheck'
3626 * @param size number of bytes allowed
3627 * @param buf where to copy the message
3628 * @return number of bytes copied to buf
3631 transmit_blacklist_message (void *cls,
3635 struct BlacklistCheck *bc = cls;
3636 struct Blacklisters *bl;
3637 struct BlacklistMessage bm;
3642 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3643 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3645 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3646 "Failed to send blacklist test for peer `%s' to client\n",
3647 GNUNET_i2s (&bc->peer));
3651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3652 "Sending blacklist test for peer `%s' to client\n",
3653 GNUNET_i2s (&bc->peer));
3656 bm.header.size = htons (sizeof (struct BlacklistMessage));
3657 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3658 bm.is_allowed = htonl (0);
3660 memcpy (buf, &bm, sizeof (bm));
3661 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3667 * Perform next action in the blacklist check.
3669 * @param cls the 'struct BlacklistCheck*'
3673 do_blacklist_check (void *cls,
3674 const struct GNUNET_SCHEDULER_TaskContext *tc)
3676 struct BlacklistCheck *bc = cls;
3677 struct Blacklisters *bl;
3679 bc->task = GNUNET_SCHEDULER_NO_TASK;
3684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3685 "No blacklist clients active, will now setup neighbour record for peer `%s'\n",
3686 GNUNET_i2s (&bc->peer));
3688 bc->cont (bc->cont_cls,
3689 setup_new_neighbour (&bc->peer, bc->do_hello));
3696 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3697 sizeof (struct BlacklistMessage),
3698 GNUNET_TIME_UNIT_FOREVER_REL,
3699 &transmit_blacklist_message,
3706 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3707 * does not yet exist, check the blacklist. If the blacklist says creating
3708 * one is acceptable, create one and call the continuation; otherwise
3709 * call the continuation with NULL.
3711 * @param peer peer to setup or look up a struct NeighbourList for
3712 * @param do_hello should we also schedule sending our HELLO to the peer
3713 * if this is a new record
3714 * @param cont function to call with the 'struct NeigbhbourList*'
3715 * @param cont_cls closure for cont
3718 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3720 SetupContinuation cont,
3723 struct NeighbourList *n;
3724 struct BlacklistCheck *bc;
3726 n = find_neighbour(peer);
3730 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3731 "Neighbour record exists for peer `%s'\n",
3738 if (bl_head == NULL)
3741 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3743 setup_new_neighbour(peer, do_hello);
3746 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3747 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3749 bc->do_hello = do_hello;
3751 bc->cont_cls = cont_cls;
3752 bc->bl_pos = bl_head;
3753 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3759 * Function called with the result of querying a new blacklister about
3760 * it being allowed (or not) to continue to talk to an existing neighbour.
3762 * @param cls the original 'struct NeighbourList'
3763 * @param n NULL if we need to disconnect
3766 confirm_or_drop_neighbour (void *cls,
3767 struct NeighbourList *n)
3769 struct NeighbourList * orig = cls;
3774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3775 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3776 "confirm_or_drop_neighboUr");
3778 GNUNET_STATISTICS_update (stats,
3779 gettext_noop ("# disconnects due to blacklist"),
3782 disconnect_neighbour (orig, GNUNET_NO);
3788 * Handle a request to start a blacklist.
3790 * @param cls closure (always NULL)
3791 * @param client identification of the client
3792 * @param message the actual message
3795 handle_blacklist_init (void *cls,
3796 struct GNUNET_SERVER_Client *client,
3797 const struct GNUNET_MessageHeader *message)
3799 struct Blacklisters *bl;
3800 struct BlacklistCheck *bc;
3801 struct NeighbourList *n;
3806 if (bl->client == client)
3809 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3814 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3815 bl->client = client;
3816 GNUNET_SERVER_client_keep (client);
3817 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3818 /* confirm that all existing connections are OK! */
3822 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3823 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3825 bc->do_hello = GNUNET_NO;
3826 bc->cont = &confirm_or_drop_neighbour;
3829 if (n == neighbours) /* all would wait for the same client, no need to
3830 create more than just the first task right now */
3831 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3839 * Handle a request to blacklist a peer.
3841 * @param cls closure (always NULL)
3842 * @param client identification of the client
3843 * @param message the actual message
3846 handle_blacklist_reply (void *cls,
3847 struct GNUNET_SERVER_Client *client,
3848 const struct GNUNET_MessageHeader *message)
3850 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3851 struct Blacklisters *bl;
3852 struct BlacklistCheck *bc;
3855 while ( (bl != NULL) &&
3856 (bl->client != client) )
3861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3862 "Blacklist client disconnected\n");
3864 /* FIXME: other error handling here!? */
3865 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3870 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3874 "Blacklist check failed, peer not allowed\n");
3876 bc->cont (bc->cont_cls, NULL);
3877 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3884 "Blacklist check succeeded, continuing with checks\n");
3886 bc->bl_pos = bc->bl_pos->next;
3887 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3890 /* check if any other bc's are waiting for this blacklister */
3894 if ( (bc->bl_pos == bl) &&
3895 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3896 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3904 * Send periodic PING messages to a given foreign address.
3906 * @param cls our 'struct PeriodicValidationContext*'
3907 * @param tc task context
3910 send_periodic_ping (void *cls,
3911 const struct GNUNET_SCHEDULER_TaskContext *tc)
3913 struct ForeignAddressList *peer_address = cls;
3914 struct TransportPlugin *tp;
3915 struct ValidationEntry *va;
3916 struct NeighbourList *neighbour;
3917 struct TransportPingMessage ping;
3918 struct CheckAddressExistsClosure caec;
3920 uint16_t hello_size;
3924 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3925 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3927 tp = peer_address->ready_list->plugin;
3928 neighbour = peer_address->ready_list->neighbour;
3929 if (GNUNET_YES != neighbour->public_key_valid)
3931 /* no public key yet, try again later */
3932 schedule_next_ping (peer_address);
3935 caec.addr = peer_address->addr;
3936 caec.addrlen = peer_address->addrlen;
3937 caec.tname = tp->short_name;
3938 caec.session = peer_address->session;
3939 caec.exists = GNUNET_NO;
3940 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3941 &check_address_exists,
3943 if (caec.exists == GNUNET_YES)
3945 /* During validation attempts we will likely trigger the other
3946 peer trying to validate our address which in turn will cause
3947 it to send us its HELLO, so we expect to hit this case rather
3948 frequently. Only print something if we are very verbose. */
3949 #if DEBUG_TRANSPORT > 1
3950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3951 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3952 (peer_address->addr != NULL)
3953 ? a2s (tp->short_name,
3955 peer_address->addrlen)
3958 GNUNET_i2s (&neighbour->id));
3960 schedule_next_ping (peer_address);
3963 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3964 va->transport_name = GNUNET_strdup (tp->short_name);
3965 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3967 va->send_time = GNUNET_TIME_absolute_get();
3968 va->session = peer_address->session;
3969 if (peer_address->addr != NULL)
3971 va->addr = (const void*) &va[1];
3972 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3973 va->addrlen = peer_address->addrlen;
3975 memcpy(&va->publicKey,
3976 &neighbour->publicKey,
3977 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3979 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3980 &timeout_hello_validation,
3982 GNUNET_CONTAINER_multihashmap_put (validation_map,
3983 &neighbour->id.hashPubKey,
3985 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3987 if (peer_address->validated != GNUNET_YES)
3988 hello_size = GNUNET_HELLO_size(our_hello);
3992 tsize = sizeof(struct TransportPingMessage) + hello_size;
3994 if (peer_address->addr != NULL)
3996 slen = strlen (tp->short_name) + 1;
3997 tsize += slen + peer_address->addrlen;
4001 slen = 0; /* make gcc happy */
4003 message_buf = GNUNET_malloc(tsize);
4004 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4005 ping.challenge = htonl(va->challenge);
4006 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4007 if (peer_address->validated != GNUNET_YES)
4009 memcpy(message_buf, our_hello, hello_size);
4012 if (peer_address->addr != NULL)
4014 ping.header.size = htons(sizeof(struct TransportPingMessage) +
4015 peer_address->addrlen +
4017 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4020 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4022 peer_address->addrlen);
4026 ping.header.size = htons(sizeof(struct TransportPingMessage));
4029 memcpy(&message_buf[hello_size],
4031 sizeof(struct TransportPingMessage));
4033 #if DEBUG_TRANSPORT_REVALIDATION
4034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4035 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
4036 (peer_address->addr != NULL)
4037 ? a2s (peer_address->plugin->short_name,
4039 peer_address->addrlen)
4042 GNUNET_i2s (&neighbour->id),
4043 "HELLO", hello_size,
4046 if (peer_address->validated != GNUNET_YES)
4047 GNUNET_STATISTICS_update (stats,
4048 gettext_noop ("# PING with HELLO messages sent"),
4052 GNUNET_STATISTICS_update (stats,
4053 gettext_noop ("# PING without HELLO messages sent"),
4056 GNUNET_STATISTICS_update (stats,
4057 gettext_noop ("# PING messages sent for re-validation"),
4060 transmit_to_peer (NULL, peer_address,
4061 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4062 HELLO_VERIFICATION_TIMEOUT,
4064 GNUNET_YES, neighbour);
4065 GNUNET_free(message_buf);
4066 schedule_next_ping (peer_address);
4071 * Schedule the job that will cause us to send a PING to the
4072 * foreign address to evaluate its validity and latency.
4074 * @param fal address to PING
4077 schedule_next_ping (struct ForeignAddressList *fal)
4079 struct GNUNET_TIME_Relative delay;
4081 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
4083 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
4084 delay.rel_value /= 2; /* do before expiration */
4085 delay = GNUNET_TIME_relative_min (delay,
4086 LATENCY_EVALUATION_MAX_DELAY);
4087 if (GNUNET_YES != fal->estimated)
4089 delay = GNUNET_TIME_UNIT_ZERO;
4090 fal->estimated = GNUNET_YES;
4092 if (GNUNET_YES == fal->connected)
4094 delay = GNUNET_TIME_relative_min (delay,
4095 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
4097 /* FIXME: also adjust delay based on how close the last
4098 observed latency is to the latency of the best alternative */
4099 /* bound how fast we can go */
4100 delay = GNUNET_TIME_relative_max (delay,
4101 GNUNET_TIME_UNIT_SECONDS);
4102 /* randomize a bit (to avoid doing all at the same time) */
4103 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
4104 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
4105 &send_periodic_ping,
4113 * Function that will be called if we receive some payload
4114 * from another peer.
4116 * @param message the payload
4117 * @param n peer who claimed to be the sender
4120 handle_payload_message (const struct GNUNET_MessageHeader *message,
4121 struct NeighbourList *n)
4123 struct InboundMessage *im;
4124 struct TransportClient *cpos;
4127 msize = ntohs (message->size);
4128 if (n->received_pong == GNUNET_NO)
4131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132 "Received message of type %u and size %u from `%4s', but no pong yet!\n",
4133 ntohs (message->type),
4134 ntohs (message->size),
4135 GNUNET_i2s (&n->id));
4137 GNUNET_free_non_null (n->pre_connect_message_buffer);
4138 n->pre_connect_message_buffer = GNUNET_malloc (msize);
4139 memcpy (n->pre_connect_message_buffer, message, msize);
4144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4145 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4146 ntohs (message->type),
4147 ntohs (message->size),
4148 GNUNET_i2s (&n->id));
4150 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4153 n->quota_violation_count++;
4155 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4156 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
4157 n->in_tracker.available_bytes_per_s__,
4158 n->quota_violation_count);
4160 /* Discount 32k per violation */
4161 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4166 if (n->quota_violation_count > 0)
4168 /* try to add 32k back */
4169 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4171 n->quota_violation_count--;
4174 GNUNET_STATISTICS_update (stats,
4175 gettext_noop ("# payload received from other peers"),
4178 /* transmit message to all clients */
4179 uint32_t ats_count = 2;
4180 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
4181 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4184 im = GNUNET_malloc (size);
4185 im->header.size = htons (size);
4186 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
4188 im->ats_count = htonl(ats_count);
4189 /* Setting ATS data */
4190 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4191 (&(im->ats))[0].value = htonl (n->distance);
4192 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4193 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
4194 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4195 (&(im->ats))[ats_count].value = htonl (0);
4197 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
4199 while (cpos != NULL)
4201 transmit_to_client (cpos, &im->header, GNUNET_YES);
4209 * Iterator over hash map entries. Checks if the given validation
4210 * entry is for the same challenge as what is given in the PONG.
4212 * @param cls the 'struct TransportPongMessage*'
4213 * @param key peer identity
4214 * @param value value in the hash map ('struct ValidationEntry')
4215 * @return GNUNET_YES if we should continue to
4216 * iterate (mismatch), GNUNET_NO if not (entry matched)
4219 check_pending_validation (void *cls,
4220 const GNUNET_HashCode * key,
4223 const struct TransportPongMessage *pong = cls;
4224 struct ValidationEntry *ve = value;
4225 struct AddValidatedAddressContext avac;
4226 unsigned int challenge = ntohl(pong->challenge);
4227 struct GNUNET_HELLO_Message *hello;
4228 struct GNUNET_PeerIdentity target;
4229 struct NeighbourList *n;
4230 struct ForeignAddressList *fal;
4231 struct OwnAddressList *oal;
4232 struct TransportPlugin *tp;
4233 struct GNUNET_MessageHeader *prem;
4239 ps = ntohs (pong->header.size);
4240 if (ps < sizeof (struct TransportPongMessage))
4242 GNUNET_break_op (0);
4245 addr = (const char*) &pong[1];
4246 slen = strlen (ve->transport_name) + 1;
4247 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
4248 (ve->challenge != challenge) ||
4249 (addr[slen-1] != '\0') ||
4250 (0 != strcmp (addr, ve->transport_name)) ||
4251 (ntohl (pong->purpose.size)
4252 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4254 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4255 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
4260 alen = ps - sizeof (struct TransportPongMessage) - slen;
4261 switch (ntohl (pong->purpose.purpose))
4263 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
4264 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
4265 (0 != memcmp (&addr[slen],
4269 return GNUNET_YES; /* different entry, keep trying! */
4271 if (0 != memcmp (&pong->pid,
4273 sizeof (struct GNUNET_PeerIdentity)))
4275 GNUNET_break_op (0);
4279 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
4284 GNUNET_break_op (0);
4289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4290 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
4292 a2s (ve->transport_name,
4293 (const struct sockaddr *) ve->addr,
4295 ve->transport_name);
4298 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
4299 if (0 != memcmp (&pong->pid,
4301 sizeof (struct GNUNET_PeerIdentity)))
4305 GNUNET_asprintf(&peer, "%s",GNUNET_i2s (&pong->pid));
4307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4308 "Received PONG for different identity: I am `%s', PONG identity: `%s'\n",
4309 GNUNET_i2s (&my_identity),
4315 if (ve->addrlen != 0)
4317 /* must have been for a different validation entry */
4320 tp = find_transport (ve->transport_name);
4326 oal = tp->addresses;
4329 if ( (oal->addrlen == alen) &&
4330 (0 == memcmp (&oal[1],
4338 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4339 _("Not accepting PONG from `%s' with address `%s' since I cannot confirm using this address.\n"),
4340 GNUNET_i2s (&pong->pid),
4341 a2s (ve->transport_name,
4344 /* FIXME: since the sender of the PONG currently uses the
4345 wrong address (see FIMXE there!), we cannot run a
4346 proper check here... */
4352 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
4357 GNUNET_break_op (0);
4362 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4363 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
4365 a2s (ve->transport_name,
4368 ve->transport_name);
4372 GNUNET_break_op (0);
4375 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
4377 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4378 _("Received expired signature. Check system time.\n"));
4381 GNUNET_STATISTICS_update (stats,
4382 gettext_noop ("# address validation successes"),
4385 /* create the updated HELLO */
4386 GNUNET_CRYPTO_hash (&ve->publicKey,
4387 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4388 &target.hashPubKey);
4389 if (ve->addr != NULL)
4391 avac.done = GNUNET_NO;
4393 hello = GNUNET_HELLO_create (&ve->publicKey,
4394 &add_validated_address,
4396 GNUNET_PEERINFO_add_peer (peerinfo,
4398 GNUNET_free (hello);
4400 n = find_neighbour (&target);
4403 n->publicKey = ve->publicKey;
4404 n->public_key_valid = GNUNET_YES;
4405 fal = add_peer_address (n,
4410 GNUNET_assert (fal != NULL);
4411 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
4412 fal->validated = GNUNET_YES;
4413 mark_address_connected (fal);
4414 GNUNET_STATISTICS_update (stats,
4415 gettext_noop ("# peer addresses considered valid"),
4418 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
4419 update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4421 schedule_next_ping (fal);
4422 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
4423 n->latency = fal->latency;
4425 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
4427 n->distance = fal->distance;
4428 if (GNUNET_NO == n->received_pong)
4430 n->received_pong = GNUNET_YES;
4431 notify_clients_connect (&target, n->latency, n->distance);
4432 if (NULL != (prem = n->pre_connect_message_buffer))
4434 n->pre_connect_message_buffer = NULL;
4435 handle_payload_message (prem, n);
4439 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4441 GNUNET_SCHEDULER_cancel (n->retry_task);
4442 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4443 try_transmission_to_peer (n);
4447 /* clean up validation entry */
4448 GNUNET_assert (GNUNET_YES ==
4449 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4452 abort_validation (NULL, NULL, ve);
4458 * Function that will be called if we receive a validation
4459 * of an address challenge that we transmitted to another
4460 * peer. Note that the validation should only be considered
4461 * acceptable if the challenge matches AND if the sender
4462 * address is at least a plausible address for this peer
4463 * (otherwise we may be seeing a MiM attack).
4465 * @param cls closure
4466 * @param message the pong message
4467 * @param peer who responded to our challenge
4468 * @param sender_address string describing our sender address (as observed
4469 * by the other peer in binary format)
4470 * @param sender_address_len number of bytes in 'sender_address'
4473 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
4474 const struct GNUNET_PeerIdentity *peer,
4475 const char *sender_address,
4476 size_t sender_address_len)
4478 if (0 == memcmp (peer,
4480 sizeof (struct GNUNET_PeerIdentity)))
4482 /* PONG send to self, ignore */
4483 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4484 "Receiving `%s' message from myself\n",
4488 #if DEBUG_TRANSPORT > 1
4489 /* we get tons of these that just get discarded, only log
4490 if we are quite verbose */
4491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4492 "Receiving `%s' message from `%4s'.\n", "PONG",
4495 GNUNET_STATISTICS_update (stats,
4496 gettext_noop ("# PONG messages received"),
4499 if (GNUNET_SYSERR !=
4500 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
4502 &check_pending_validation,
4505 /* This is *expected* to happen a lot since we send
4506 PONGs to *all* known addresses of the sender of
4507 the PING, so most likely we get multiple PONGs
4508 per PING, and all but the first PONG will end up
4509 here. So really we should not print anything here
4510 unless we want to be very, very verbose... */
4511 #if DEBUG_TRANSPORT > 2
4512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4513 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
4525 * Try to validate a neighbour's address by sending him our HELLO and a PING.
4527 * @param cls the 'struct ValidationEntry*'
4528 * @param neighbour neighbour to validate, NULL if validation failed
4531 transmit_hello_and_ping (void *cls,
4532 struct NeighbourList *neighbour)
4534 struct ValidationEntry *va = cls;
4535 struct ForeignAddressList *peer_address;
4536 struct TransportPingMessage ping;
4537 uint16_t hello_size;
4540 struct GNUNET_PeerIdentity id;
4543 GNUNET_CRYPTO_hash (&va->publicKey,
4544 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4546 if (neighbour == NULL)
4548 /* FIXME: stats... */
4549 GNUNET_break (GNUNET_OK ==
4550 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4553 abort_validation (NULL, NULL, va);
4556 neighbour->publicKey = va->publicKey;
4557 neighbour->public_key_valid = GNUNET_YES;
4558 peer_address = add_peer_address (neighbour,
4559 va->transport_name, NULL,
4560 (const void*) &va[1],
4562 if (peer_address == NULL)
4564 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4565 "Failed to add peer `%4s' for plugin `%s'\n",
4566 GNUNET_i2s (&neighbour->id),
4567 va->transport_name);
4568 GNUNET_break (GNUNET_OK ==
4569 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4572 abort_validation (NULL, NULL, va);
4575 if (NULL == our_hello)
4576 refresh_hello_task (NULL, NULL);
4577 hello_size = GNUNET_HELLO_size(our_hello);
4578 slen = strlen(va->transport_name) + 1;
4579 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
4580 message_buf = GNUNET_malloc(tsize);
4581 ping.challenge = htonl(va->challenge);
4582 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
4583 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4584 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4585 memcpy(message_buf, our_hello, hello_size);
4586 memcpy(&message_buf[hello_size],
4588 sizeof(struct TransportPingMessage));
4589 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4592 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4597 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
4600 : a2s (va->transport_name,
4601 (const void*) &va[1], va->addrlen),
4603 GNUNET_i2s (&neighbour->id),
4604 "HELLO", hello_size,
4605 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
4608 GNUNET_STATISTICS_update (stats,
4609 gettext_noop ("# PING messages sent for initial validation"),
4612 transmit_to_peer (NULL, peer_address,
4613 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4614 HELLO_VERIFICATION_TIMEOUT,
4616 GNUNET_YES, neighbour);
4617 GNUNET_free(message_buf);
4622 * Check if the given address is already being validated; if not,
4623 * append the given address to the list of entries that are being be
4624 * validated and initiate validation.
4626 * @param cls closure ('struct CheckHelloValidatedContext *')
4627 * @param tname name of the transport
4628 * @param expiration expiration time
4629 * @param addr the address
4630 * @param addrlen length of the address
4631 * @return GNUNET_OK (always)
4634 run_validation (void *cls,
4636 struct GNUNET_TIME_Absolute expiration,
4640 struct CheckHelloValidatedContext *chvc = cls;
4641 struct GNUNET_PeerIdentity id;
4642 struct TransportPlugin *tp;
4643 struct ValidationEntry *va;
4644 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4645 struct CheckAddressExistsClosure caec;
4646 struct OwnAddressList *oal;
4648 GNUNET_assert (addr != NULL);
4650 GNUNET_STATISTICS_update (stats,
4651 gettext_noop ("# peer addresses scheduled for validation"),
4654 tp = find_transport (tname);
4657 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
4658 GNUNET_ERROR_TYPE_BULK,
4660 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4662 GNUNET_STATISTICS_update (stats,
4663 gettext_noop ("# peer addresses not validated (plugin not available)"),
4668 /* check if this is one of our own addresses */
4669 oal = tp->addresses;
4672 if ( (oal->addrlen == addrlen) &&
4673 (0 == memcmp (&oal[1],
4677 /* not plausible, this address is equivalent to our own address! */
4678 GNUNET_STATISTICS_update (stats,
4679 gettext_noop ("# peer addresses not validated (loopback)"),
4686 GNUNET_HELLO_get_key (chvc->hello, &pk);
4687 GNUNET_CRYPTO_hash (&pk,
4689 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4692 if (is_blacklisted(&id, tp))
4695 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4696 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4704 caec.addrlen = addrlen;
4705 caec.session = NULL;
4707 caec.exists = GNUNET_NO;
4708 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4709 &check_address_exists,
4711 if (caec.exists == GNUNET_YES)
4713 /* During validation attempts we will likely trigger the other
4714 peer trying to validate our address which in turn will cause
4715 it to send us its HELLO, so we expect to hit this case rather
4716 frequently. Only print something if we are very verbose. */
4717 #if DEBUG_TRANSPORT > 1
4718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4719 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4720 a2s (tname, addr, addrlen),
4724 GNUNET_STATISTICS_update (stats,
4725 gettext_noop ("# peer addresses not validated (in progress)"),
4730 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4733 va->transport_name = GNUNET_strdup (tname);
4734 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4736 va->send_time = GNUNET_TIME_absolute_get();
4737 va->addr = (const void*) &va[1];
4738 memcpy (&va[1], addr, addrlen);
4739 va->addrlen = addrlen;
4740 GNUNET_HELLO_get_key (chvc->hello,
4742 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4743 &timeout_hello_validation,
4745 GNUNET_CONTAINER_multihashmap_put (validation_map,
4748 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4749 setup_peer_check_blacklist (&id, GNUNET_NO,
4750 &transmit_hello_and_ping,
4757 * Check if addresses in validated hello "h" overlap with
4758 * those in "chvc->hello" and validate the rest.
4760 * @param cls closure
4761 * @param peer id of the peer, NULL for last call
4762 * @param h hello message for the peer (can be NULL)
4763 * @param err_msg NULL if successful, otherwise contains error message
4766 check_hello_validated (void *cls,
4767 const struct GNUNET_PeerIdentity *peer,
4768 const struct GNUNET_HELLO_Message *h,
4769 const char *err_msg)
4771 struct CheckHelloValidatedContext *chvc = cls;
4772 struct GNUNET_HELLO_Message *plain_hello;
4773 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4774 struct GNUNET_PeerIdentity target;
4775 struct NeighbourList *n;
4777 if (err_msg != NULL)
4780 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4781 _("Error in communication with PEERINFO service: %s\n"),
4789 GNUNET_STATISTICS_update (stats,
4790 gettext_noop ("# outstanding peerinfo iterate requests"),
4794 if (GNUNET_NO == chvc->hello_known)
4796 /* notify PEERINFO about the peer now, so that we at least
4797 have the public key if some other component needs it */
4798 GNUNET_HELLO_get_key (chvc->hello, &pk);
4799 GNUNET_CRYPTO_hash (&pk,
4800 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4801 &target.hashPubKey);
4802 plain_hello = GNUNET_HELLO_create (&pk,
4805 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4806 GNUNET_free (plain_hello);
4807 #if DEBUG_TRANSPORT_HELLO
4808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4809 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4811 GNUNET_i2s (&target));
4813 GNUNET_STATISTICS_update (stats,
4814 gettext_noop ("# new HELLOs requiring full validation"),
4817 GNUNET_HELLO_iterate_addresses (chvc->hello,
4824 GNUNET_STATISTICS_update (stats,
4825 gettext_noop ("# duplicate HELLO (peer known)"),
4830 if (chvc->ve_count == 0)
4832 GNUNET_CONTAINER_DLL_remove (chvc_head,
4841 #if DEBUG_TRANSPORT_HELLO
4842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4843 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4847 chvc->hello_known = GNUNET_YES;
4848 n = find_neighbour (peer);
4851 #if DEBUG_TRANSPORT_HELLO
4852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4853 "Calling hello_iterate_addresses for %s!\n",
4856 GNUNET_HELLO_iterate_addresses (h,
4858 &add_to_foreign_address_list,
4860 try_transmission_to_peer (n);
4864 #if DEBUG_TRANSPORT_HELLO
4865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4866 "No existing neighbor record for %s!\n",
4869 GNUNET_STATISTICS_update (stats,
4870 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4874 GNUNET_STATISTICS_update (stats,
4875 gettext_noop ("# HELLO validations (update case)"),
4878 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4880 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4887 * Process HELLO-message.
4889 * @param plugin transport involved, may be NULL
4890 * @param message the actual message
4891 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4894 process_hello (struct TransportPlugin *plugin,
4895 const struct GNUNET_MessageHeader *message)
4898 struct GNUNET_PeerIdentity target;
4899 const struct GNUNET_HELLO_Message *hello;
4900 struct CheckHelloValidatedContext *chvc;
4901 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4902 struct NeighbourList *n;
4903 #if DEBUG_TRANSPORT_HELLO > 2
4907 hsize = ntohs (message->size);
4908 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4909 (hsize < sizeof (struct GNUNET_MessageHeader)))
4912 return GNUNET_SYSERR;
4914 GNUNET_STATISTICS_update (stats,
4915 gettext_noop ("# HELLOs received for validation"),
4919 hello = (const struct GNUNET_HELLO_Message *) message;
4920 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4922 #if DEBUG_TRANSPORT_HELLO
4923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4924 "Unable to get public key from `%s' for `%4s'!\n",
4926 GNUNET_i2s (&target));
4928 GNUNET_break_op (0);
4929 return GNUNET_SYSERR;
4931 GNUNET_CRYPTO_hash (&publicKey,
4932 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4933 &target.hashPubKey);
4935 #if DEBUG_TRANSPORT_HELLO
4936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4937 "Received `%s' message for `%4s'\n",
4939 GNUNET_i2s (&target));
4941 if (0 == memcmp (&my_identity,
4943 sizeof (struct GNUNET_PeerIdentity)))
4945 GNUNET_STATISTICS_update (stats,
4946 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4951 n = find_neighbour (&target);
4953 (! n->public_key_valid) )
4955 GNUNET_HELLO_get_key (hello, &n->publicKey);
4956 n->public_key_valid = GNUNET_YES;
4959 /* check if load is too high before doing expensive stuff */
4960 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4962 GNUNET_STATISTICS_update (stats,
4963 gettext_noop ("# HELLOs ignored due to high load"),
4966 #if DEBUG_TRANSPORT_HELLO
4967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4968 "Ignoring `%s' for `%4s', load too high.\n",
4970 GNUNET_i2s (&target));
4977 while (NULL != chvc)
4979 if (GNUNET_HELLO_equals (hello,
4981 GNUNET_TIME_absolute_get ()).abs_value > 0)
4983 #if DEBUG_TRANSPORT_HELLO > 2
4984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4985 "Received duplicate `%s' message for `%4s'; ignored\n",
4987 GNUNET_i2s (&target));
4989 return GNUNET_OK; /* validation already pending */
4991 if (GNUNET_HELLO_size (hello) == GNUNET_HELLO_size (chvc->hello))
4992 GNUNET_break (0 != memcmp (hello, chvc->hello,
4993 GNUNET_HELLO_size(hello)));
4998 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4999 if ((NULL != temp_neighbor))
5001 fprintf(stderr, "Already know peer, ignoring hello\n");
5006 #if DEBUG_TRANSPORT_HELLO > 2
5009 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
5011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5012 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
5015 GNUNET_i2s (&target),
5017 GNUNET_HELLO_size(hello));
5022 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
5024 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
5025 memcpy (&chvc[1], hello, hsize);
5026 GNUNET_CONTAINER_DLL_insert (chvc_head,
5029 /* finally, check if HELLO was previously validated
5030 (continuation will then schedule actual validation) */
5031 GNUNET_STATISTICS_update (stats,
5032 gettext_noop ("# peerinfo process hello iterate requests"),
5035 GNUNET_STATISTICS_update (stats,
5036 gettext_noop ("# outstanding peerinfo iterate requests"),
5039 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
5041 HELLO_VERIFICATION_TIMEOUT,
5042 &check_hello_validated, chvc);
5048 * The peer specified by the given neighbour has timed-out or a plugin
5049 * has disconnected. We may either need to do nothing (other plugins
5050 * still up), or trigger a full disconnect and clean up. This
5051 * function updates our state and does the necessary notifications.
5052 * Also notifies our clients that the neighbour is now officially
5055 * @param n the neighbour list entry for the peer
5056 * @param check GNUNET_YES to check if ALL addresses for this peer
5057 * are gone, GNUNET_NO to force a disconnect of the peer
5058 * regardless of whether other addresses exist.
5061 disconnect_neighbour (struct NeighbourList *n, int check)
5063 struct ReadyList *rpos;
5064 struct NeighbourList *npos;
5065 struct NeighbourList *nprev;
5066 struct MessageQueue *mq;
5067 struct ForeignAddressList *peer_addresses;
5068 struct ForeignAddressList *peer_pos;
5070 if (GNUNET_YES == check)
5073 while (NULL != rpos)
5075 peer_addresses = rpos->addresses;
5076 while (peer_addresses != NULL)
5078 // Do not disconnect if: an address is connected or an inbound address exists
5079 if ((GNUNET_YES == peer_addresses->connected) || (peer_addresses->addrlen == 0))
5082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5083 "NOT Disconnecting from `%4s', still have live address `%s'!\n",
5084 GNUNET_i2s (&n->id),
5085 a2s (peer_addresses->ready_list->plugin->short_name,
5086 peer_addresses->addr,
5087 peer_addresses->addrlen));
5089 return; /* still connected */
5091 peer_addresses = peer_addresses->next;
5097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5098 "Disconnecting from `%4s'\n",
5099 GNUNET_i2s (&n->id));
5101 /* remove n from neighbours list */
5104 while ((npos != NULL) && (npos != n))
5109 GNUNET_assert (npos != NULL);
5111 neighbours = n->next;
5113 nprev->next = n->next;
5115 /* notify all clients about disconnect */
5116 if (GNUNET_YES == n->received_pong)
5117 notify_clients_disconnect (&n->id);
5119 /* clean up all plugins, cancel connections and pending transmissions */
5120 while (NULL != (rpos = n->plugins))
5122 n->plugins = rpos->next;
5123 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
5124 while (rpos->addresses != NULL)
5126 peer_pos = rpos->addresses;
5127 rpos->addresses = peer_pos->next;
5128 if (peer_pos->connected == GNUNET_YES)
5129 GNUNET_STATISTICS_update (stats,
5130 gettext_noop ("# connected addresses"),
5133 if (GNUNET_YES == peer_pos->validated)
5134 GNUNET_STATISTICS_update (stats,
5135 gettext_noop ("# peer addresses considered valid"),
5138 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
5140 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
5141 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
5143 GNUNET_free(peer_pos->ressources);
5144 peer_pos->ressources = NULL;
5145 GNUNET_free(peer_pos->quality);
5146 peer_pos->ressources = NULL;
5147 GNUNET_free(peer_pos);
5148 ats->stat.recreate_problem = GNUNET_YES;
5153 /* free all messages on the queue */
5154 while (NULL != (mq = n->messages_head))
5156 GNUNET_STATISTICS_update (stats,
5157 gettext_noop ("# bytes in message queue for other peers"),
5158 - (int64_t) mq->message_buf_size,
5160 GNUNET_STATISTICS_update (stats,
5161 gettext_noop ("# bytes discarded due to disconnect"),
5162 mq->message_buf_size,
5164 GNUNET_CONTAINER_DLL_remove (n->messages_head,
5167 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5169 sizeof(struct GNUNET_PeerIdentity)));
5173 while (NULL != (mq = n->cont_head))
5176 GNUNET_CONTAINER_DLL_remove (n->cont_head,
5179 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5181 sizeof(struct GNUNET_PeerIdentity)));
5185 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
5187 GNUNET_SCHEDULER_cancel (n->timeout_task);
5188 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
5190 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
5192 GNUNET_SCHEDULER_cancel (n->retry_task);
5193 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
5195 if (n->piter != NULL)
5197 GNUNET_PEERINFO_iterate_cancel (n->piter);
5198 GNUNET_STATISTICS_update (stats,
5199 gettext_noop ("# outstanding peerinfo iterate requests"),
5204 /* finally, free n itself */
5205 GNUNET_STATISTICS_update (stats,
5206 gettext_noop ("# active neighbours"),
5209 GNUNET_free_non_null (n->pre_connect_message_buffer);
5215 * We have received a PING message from someone. Need to send a PONG message
5216 * in response to the peer by any means necessary.
5219 handle_ping (void *cls, const struct GNUNET_MessageHeader *message,
5220 const struct GNUNET_PeerIdentity *peer,
5221 struct Session *session,
5222 const char *sender_address,
5223 uint16_t sender_address_len)
5225 struct TransportPlugin *plugin = cls;
5226 struct SessionHeader *session_header = (struct SessionHeader*) session;
5227 struct TransportPingMessage *ping;
5228 struct TransportPongMessage *pong;
5229 struct NeighbourList *n;
5230 struct ReadyList *rl;
5231 struct ForeignAddressList *fal;
5232 struct OwnAddressList *oal;
5238 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
5240 GNUNET_break_op (0);
5241 return GNUNET_SYSERR;
5244 ping = (struct TransportPingMessage *) message;
5245 if (0 != memcmp (&ping->target,
5246 plugin->env.my_identity,
5247 sizeof (struct GNUNET_PeerIdentity)))
5250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5251 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
5253 (sender_address != NULL)
5254 ? a2s (plugin->short_name,
5255 (const struct sockaddr *)sender_address,
5258 GNUNET_i2s (&ping->target));
5260 return GNUNET_SYSERR;
5263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5264 "Processing `%s' from `%s'\n",
5266 (sender_address != NULL)
5267 ? a2s (plugin->short_name,
5268 (const struct sockaddr *)sender_address,
5272 GNUNET_STATISTICS_update (stats,
5273 gettext_noop ("# PING messages received"),
5276 addr = (const char*) &ping[1];
5277 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
5278 slen = strlen (plugin->short_name) + 1;
5281 /* peer wants to confirm that we have an outbound connection to him */
5282 if (session == NULL)
5284 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5285 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
5287 return GNUNET_SYSERR;
5289 /* FIXME-urg: the use of 'sender_address' in the code below is doubly-wrong:
5290 1) it is NULL when we need to have a real value
5291 2) it is documented to be the address of the sender (source-IP), where
5292 what we actually want is our LISTEN IP (what we 'bound' to); which we don't even
5295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5296 "Creating PONG indicating that we received a connection at our address `%s' from `%s'.\n",
5297 a2s (plugin->short_name,
5299 sender_address_len),
5302 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5303 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5304 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5305 pong->purpose.size =
5306 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5308 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5309 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
5310 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
5311 pong->challenge = ping->challenge;
5312 pong->addrlen = htonl(sender_address_len + slen);
5315 sizeof(struct GNUNET_PeerIdentity));
5319 if ((sender_address!=NULL) && (sender_address_len > 0))
5320 memcpy (&((char*)&pong[1])[slen],
5322 sender_address_len);
5323 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
5325 /* create / update cached sig */
5327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5328 "Creating PONG signature to indicate active connection.\n");
5330 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5331 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5332 GNUNET_assert (GNUNET_OK ==
5333 GNUNET_CRYPTO_rsa_sign (my_private_key,
5335 &session_header->pong_signature));
5339 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5341 memcpy (&pong->signature,
5342 &session_header->pong_signature,
5343 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5349 /* peer wants to confirm that this is one of our addresses */
5353 plugin->api->check_address (plugin->api->cls,
5357 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5358 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
5359 a2s (plugin->short_name,
5364 oal = plugin->addresses;
5367 if ( (oal->addrlen == alen) &&
5374 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
5375 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
5376 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5377 pong->purpose.size =
5378 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5380 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5381 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
5382 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
5383 pong->challenge = ping->challenge;
5384 pong->addrlen = htonl(alen + slen);
5387 sizeof(struct GNUNET_PeerIdentity));
5388 memcpy (&pong[1], plugin->short_name, slen);
5389 memcpy (&((char*)&pong[1])[slen], addr, alen);
5390 if ( (oal != NULL) &&
5391 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
5393 /* create / update cached sig */
5395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5396 "Creating PONG signature to indicate ownership.\n");
5398 oal->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5399 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5400 GNUNET_assert (GNUNET_OK ==
5401 GNUNET_CRYPTO_rsa_sign (my_private_key,
5403 &oal->pong_signature));
5404 memcpy (&pong->signature,
5405 &oal->pong_signature,
5406 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5408 else if (oal == NULL)
5410 /* not using cache (typically DV-only) */
5411 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
5412 GNUNET_assert (GNUNET_OK ==
5413 GNUNET_CRYPTO_rsa_sign (my_private_key,
5419 /* can used cached version */
5420 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5421 memcpy (&pong->signature,
5422 &oal->pong_signature,
5423 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5426 n = find_neighbour(peer);
5427 GNUNET_assert (n != NULL);
5428 did_pong = GNUNET_NO;
5429 /* first try reliable response transmission */
5433 fal = rl->addresses;
5436 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
5439 ntohs (pong->header.size),
5440 TRANSPORT_PONG_PRIORITY,
5441 HELLO_VERIFICATION_TIMEOUT,
5448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5449 "Transmitted PONG to `%s' via reliable mechanism\n",
5452 GNUNET_STATISTICS_update (stats,
5453 gettext_noop ("# PONGs unicast via reliable transport"),
5459 did_pong = GNUNET_YES;
5464 /* no reliable method found, do multicast */
5465 GNUNET_STATISTICS_update (stats,
5466 gettext_noop ("# PONGs multicast to all available addresses"),
5472 fal = rl->addresses;
5475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5476 "Transmitting PONG to `%s' via unreliable mechanism `%s':%s\n",
5478 a2s (rl->plugin->short_name,
5481 rl->plugin->short_name);
5482 transmit_to_peer(NULL, fal,
5483 TRANSPORT_PONG_PRIORITY,
5484 HELLO_VERIFICATION_TIMEOUT,
5486 ntohs(pong->header.size),
5489 did_pong = GNUNET_YES;
5495 if (GNUNET_YES != did_pong)
5496 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5497 _("Could not send PONG to `%s': no address available\n"),
5504 * Function called by the plugin for each received message. Update
5505 * data volumes, possibly notify plugins about reducing the rate at
5506 * which they read from the socket and generally forward to our
5509 * @param cls the "struct TransportPlugin *" we gave to the plugin
5510 * @param peer (claimed) identity of the other peer
5511 * @param message the message, NULL if we only care about
5512 * learning about the delay until we should receive again
5513 * @param ats_data information for automatic transport selection
5514 * @param ats_count number of elements in ats not including 0-terminator
5515 * @param session identifier used for this session (can be NULL)
5516 * @param sender_address binary address of the sender (if observed)
5517 * @param sender_address_len number of bytes in sender_address
5518 * @return how long in ms the plugin should wait until receiving more data
5519 * (plugins that do not support this, can ignore the return value)
5521 static struct GNUNET_TIME_Relative
5522 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
5523 const struct GNUNET_MessageHeader *message,
5524 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
5526 struct Session *session,
5527 const char *sender_address,
5528 uint16_t sender_address_len)
5530 struct TransportPlugin *plugin = cls;
5531 struct ReadyList *service_context;
5532 struct ForeignAddressList *peer_address;
5534 struct NeighbourList *n;
5535 struct GNUNET_TIME_Relative ret;
5539 if (0 == memcmp (peer,
5541 sizeof (struct GNUNET_PeerIdentity)))
5543 /* refuse to receive from myself */
5545 return GNUNET_TIME_UNIT_FOREVER_REL;
5547 if (is_blacklisted (peer, plugin))
5548 return GNUNET_TIME_UNIT_FOREVER_REL;
5549 n = find_neighbour (peer);
5551 n = setup_new_neighbour (peer, GNUNET_YES);
5552 service_context = n->plugins;
5553 while ((service_context != NULL) && (plugin != service_context->plugin))
5554 service_context = service_context->next;
5555 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
5556 peer_address = NULL;
5559 for (c=0; c<ats_count; c++)
5560 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
5561 distance = ntohl(ats_data[c].value);
5563 /* notify ATS about incoming data */
5564 //ats_notify_ats_data(peer, ats_data);
5566 if (message != NULL)
5568 if ( (session != NULL) ||
5569 (sender_address != NULL) )
5570 peer_address = add_peer_address (n,
5574 sender_address_len);
5575 if (peer_address != NULL)
5577 update_addr_ats(peer_address, ats_data, ats_count);
5578 update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5580 peer_address->distance = distance;
5581 if (GNUNET_YES == peer_address->validated)
5582 mark_address_connected (peer_address);
5583 peer_address->timeout
5584 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5585 schedule_next_ping (peer_address);
5587 /* update traffic received amount ... */
5588 msize = ntohs (message->size);
5590 GNUNET_STATISTICS_update (stats,
5591 gettext_noop ("# bytes received from other peers"),
5594 n->distance = distance;
5596 GNUNET_TIME_relative_to_absolute
5597 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5598 GNUNET_SCHEDULER_cancel (n->timeout_task);
5600 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
5601 &neighbour_timeout_task, n);
5602 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
5604 /* dropping message due to frequent inbound volume violations! */
5605 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
5606 GNUNET_ERROR_TYPE_BULK,
5608 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
5609 n->in_tracker.available_bytes_per_s__,
5610 n->quota_violation_count);
5611 GNUNET_STATISTICS_update (stats,
5612 gettext_noop ("# bandwidth quota violations by other peers"),
5615 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
5617 if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
5618 (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
5620 uint32_t value = ntohl(*((uint32_t *) &message[1]));
5621 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
5622 /* Force ressource and quality update */
5625 ats->stat.modified_resources = GNUNET_YES;
5626 ats->stat.modified_quality = GNUNET_YES;
5628 /* Force cost update */
5630 ats->stat.modified_resources = GNUNET_YES;
5631 /* Force quality update */
5633 ats->stat.modified_quality = GNUNET_YES;
5634 /* Force full rebuild */
5636 ats->stat.recreate_problem = GNUNET_YES;
5640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5641 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
5642 ntohs (message->type),
5643 ntohs (message->size),
5646 switch (ntohs (message->type))
5648 case GNUNET_MESSAGE_TYPE_HELLO:
5649 GNUNET_STATISTICS_update (stats,
5650 gettext_noop ("# HELLO messages received from other peers"),
5653 process_hello (plugin, message);
5655 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
5656 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
5657 if (! n->received_pong)
5658 transmit_plain_ping (n);
5660 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
5661 handle_pong (plugin, message, peer, sender_address, sender_address_len);
5663 case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
5666 handle_payload_message (message, n);
5670 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
5671 if (ret.rel_value > 0)
5674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5675 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
5676 (unsigned long long) n->in_tracker.consumption_since_last_update__,
5677 (unsigned int) n->in_tracker.available_bytes_per_s__,
5678 (unsigned long long) ret.rel_value);
5680 GNUNET_STATISTICS_update (stats,
5681 gettext_noop ("# ms throttling suggested"),
5682 (int64_t) ret.rel_value,
5689 * Handle START-message. This is the first message sent to us
5690 * by any client which causes us to add it to our list.
5692 * @param cls closure (always NULL)
5693 * @param client identification of the client
5694 * @param message the actual message
5697 handle_start (void *cls,
5698 struct GNUNET_SERVER_Client *client,
5699 const struct GNUNET_MessageHeader *message)
5701 const struct StartMessage *start;
5702 struct TransportClient *c;
5703 struct ConnectInfoMessage * cim;
5704 struct NeighbourList *n;
5708 start = (const struct StartMessage*) message;
5710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5711 "Received `%s' request from client\n", "START");
5716 if (c->client == client)
5718 /* client already on our list! */
5720 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5725 if ( (GNUNET_NO != ntohl (start->do_check)) &&
5726 (0 != memcmp (&start->self,
5728 sizeof (struct GNUNET_PeerIdentity))) )
5730 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5731 _("Rejecting control connection from peer `%s', which is not me!\n"),
5732 GNUNET_i2s (&start->self));
5733 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5736 c = GNUNET_malloc (sizeof (struct TransportClient));
5740 if (our_hello != NULL)
5743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5744 "Sending our own `%s' to new client\n", "HELLO");
5746 transmit_to_client (c,
5747 (const struct GNUNET_MessageHeader *) our_hello,
5749 /* tell new client about all existing connections */
5751 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
5752 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
5756 cim = GNUNET_malloc (size);
5757 cim->header.size = htons (size);
5758 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
5759 cim->ats_count = htonl(ats_count);
5760 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
5761 (&(cim->ats))[2].value = htonl (0);
5765 if (GNUNET_YES == n->received_pong)
5767 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5768 (&(cim->ats))[0].value = htonl (n->distance);
5769 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5770 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
5772 transmit_to_client (c, &cim->header, GNUNET_NO);
5778 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5783 * Handle HELLO-message.
5785 * @param cls closure (always NULL)
5786 * @param client identification of the client
5787 * @param message the actual message
5790 handle_hello (void *cls,
5791 struct GNUNET_SERVER_Client *client,
5792 const struct GNUNET_MessageHeader *message)
5796 GNUNET_STATISTICS_update (stats,
5797 gettext_noop ("# HELLOs received from clients"),
5800 ret = process_hello (NULL, message);
5801 GNUNET_SERVER_receive_done (client, ret);
5806 * Closure for 'transmit_client_message'; followed by
5807 * 'msize' bytes of the actual message.
5809 struct TransmitClientMessageContext
5812 * Client on whom's behalf we are sending.
5814 struct GNUNET_SERVER_Client *client;
5817 * Timeout for the transmission.
5819 struct GNUNET_TIME_Absolute timeout;
5827 * Size of the message in bytes.
5834 * Schedule transmission of a message we got from a client to a peer.
5836 * @param cls the 'struct TransmitClientMessageContext*'
5837 * @param n destination, or NULL on error (in that case, drop the message)
5840 transmit_client_message (void *cls,
5841 struct NeighbourList *n)
5843 struct TransmitClientMessageContext *tcmc = cls;
5844 struct TransportClient *tc;
5847 while ((tc != NULL) && (tc->client != tcmc->client))
5852 transmit_to_peer (tc, NULL, tcmc->priority,
5853 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5855 tcmc->msize, GNUNET_NO, n);
5857 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5858 GNUNET_SERVER_client_drop (tcmc->client);
5864 * Handle SEND-message.
5866 * @param cls closure (always NULL)
5867 * @param client identification of the client
5868 * @param message the actual message
5871 handle_send (void *cls,
5872 struct GNUNET_SERVER_Client *client,
5873 const struct GNUNET_MessageHeader *message)
5875 const struct OutboundMessage *obm;
5876 const struct GNUNET_MessageHeader *obmm;
5877 struct TransmitClientMessageContext *tcmc;
5881 size = ntohs (message->size);
5883 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5886 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5889 GNUNET_STATISTICS_update (stats,
5890 gettext_noop ("# payload received for other peers"),
5893 obm = (const struct OutboundMessage *) message;
5894 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5895 msize = size - sizeof (struct OutboundMessage);
5897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5898 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5899 "SEND", GNUNET_i2s (&obm->peer),
5903 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5904 tcmc->client = client;
5905 tcmc->priority = ntohl (obm->priority);
5906 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5907 tcmc->msize = msize;
5908 /* FIXME: this memcpy can be up to 7% of our total runtime */
5909 memcpy (&tcmc[1], obmm, msize);
5910 GNUNET_SERVER_client_keep (client);
5911 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5912 &transmit_client_message,
5918 * Handle request connect message
5920 * @param cls closure (always NULL)
5921 * @param client identification of the client
5922 * @param message the actual message
5925 handle_request_connect (void *cls,
5926 struct GNUNET_SERVER_Client *client,
5927 const struct GNUNET_MessageHeader *message)
5929 const struct TransportRequestConnectMessage *trcm =
5930 (const struct TransportRequestConnectMessage *) message;
5932 GNUNET_STATISTICS_update (stats,
5933 gettext_noop ("# REQUEST CONNECT messages received"),
5937 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
5938 "Received a request connect message for peer `%s'\n",
5939 GNUNET_i2s(&trcm->peer));
5941 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5943 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5948 * Handle SET_QUOTA-message.
5950 * @param cls closure (always NULL)
5951 * @param client identification of the client
5952 * @param message the actual message
5955 handle_set_quota (void *cls,
5956 struct GNUNET_SERVER_Client *client,
5957 const struct GNUNET_MessageHeader *message)
5959 const struct QuotaSetMessage *qsm =
5960 (const struct QuotaSetMessage *) message;
5961 struct NeighbourList *n;
5963 GNUNET_STATISTICS_update (stats,
5964 gettext_noop ("# SET QUOTA messages received"),
5967 n = find_neighbour (&qsm->peer);
5970 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5971 GNUNET_STATISTICS_update (stats,
5972 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5979 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5981 (unsigned int) ntohl (qsm->quota.value__),
5982 (unsigned int) n->in_tracker.available_bytes_per_s__,
5983 GNUNET_i2s (&qsm->peer));
5985 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5987 if (0 == ntohl (qsm->quota.value__))
5990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5991 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5994 GNUNET_STATISTICS_update (stats,
5995 gettext_noop ("# disconnects due to quota of 0"),
5998 disconnect_neighbour (n, GNUNET_NO);
6000 GNUNET_SERVER_receive_done (client, GNUNET_OK);
6005 * Take the given address and append it to the set of results sent back to
6008 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
6009 * @param address the resolved name, NULL to indicate the last response
6012 transmit_address_to_client (void *cls, const char *address)
6014 struct GNUNET_SERVER_TransmitContext *tc = cls;
6017 if (NULL != address)
6019 slen = strlen (address) + 1;
6020 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
6021 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6025 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6031 * Handle AddressLookup-message.
6033 * @param cls closure (always NULL)
6034 * @param client identification of the client
6035 * @param message the actual message
6038 handle_address_lookup (void *cls,
6039 struct GNUNET_SERVER_Client *client,
6040 const struct GNUNET_MessageHeader *message)
6042 const struct AddressLookupMessage *alum;
6043 struct TransportPlugin *lsPlugin;
6044 const char *nameTransport;
6045 const char *address;
6047 struct GNUNET_SERVER_TransmitContext *tc;
6048 struct GNUNET_TIME_Absolute timeout;
6049 struct GNUNET_TIME_Relative rtimeout;
6052 size = ntohs (message->size);
6053 if (size < sizeof (struct AddressLookupMessage))
6055 GNUNET_break_op (0);
6056 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6059 alum = (const struct AddressLookupMessage *) message;
6060 uint32_t addressLen = ntohl (alum->addrlen);
6061 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
6063 GNUNET_break_op (0);
6064 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6067 address = (const char *) &alum[1];
6068 nameTransport = (const char *) &address[addressLen];
6070 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
6072 GNUNET_break_op (0);
6073 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6076 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
6077 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
6078 numeric = ntohl (alum->numeric_only);
6079 lsPlugin = find_transport (nameTransport);
6080 if (NULL == lsPlugin)
6082 tc = GNUNET_SERVER_transmit_context_create (client);
6083 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6084 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6085 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
6088 GNUNET_SERVER_disable_receive_done_warning (client);
6089 tc = GNUNET_SERVER_transmit_context_create (client);
6090 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
6092 address, addressLen,
6095 &transmit_address_to_client, tc);
6100 * Setup the environment for this plugin.
6103 create_environment (struct TransportPlugin *plug)
6105 plug->env.cfg = cfg;
6106 plug->env.my_identity = &my_identity;
6107 plug->env.our_hello = &our_hello;
6108 plug->env.cls = plug;
6109 plug->env.receive = &plugin_env_receive;
6110 plug->env.notify_address = &plugin_env_notify_address;
6111 plug->env.session_end = &plugin_env_session_end;
6112 plug->env.max_connections = max_connect_per_transport;
6113 plug->env.stats = stats;
6118 * Start the specified transport (load the plugin).
6121 start_transport (struct GNUNET_SERVER_Handle *server,
6124 struct TransportPlugin *plug;
6127 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6128 _("Loading `%s' transport plugin\n"), name);
6129 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
6130 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
6131 create_environment (plug);
6132 plug->short_name = GNUNET_strdup (name);
6133 plug->lib_name = libname;
6134 plug->next = plugins;
6136 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
6137 if (plug->api == NULL)
6139 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6140 _("Failed to load transport plugin for `%s'\n"), name);
6141 GNUNET_free (plug->short_name);
6142 plugins = plug->next;
6143 GNUNET_free (libname);
6150 * Called whenever a client is disconnected. Frees our
6151 * resources associated with that client.
6153 * @param cls closure
6154 * @param client identification of the client
6157 client_disconnect_notification (void *cls,
6158 struct GNUNET_SERVER_Client *client)
6160 struct TransportClient *pos;
6161 struct TransportClient *prev;
6162 struct ClientMessageQueueEntry *mqe;
6163 struct Blacklisters *bl;
6164 struct BlacklistCheck *bc;
6169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
6170 "Client disconnected, cleaning up.\n");
6172 /* clean up blacklister */
6176 if (bl->client == client)
6181 if (bc->bl_pos == bl)
6183 bc->bl_pos = bl->next;
6186 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
6189 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
6190 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
6196 GNUNET_CONTAINER_DLL_remove (bl_head,
6199 GNUNET_SERVER_client_drop (bl->client);
6205 /* clean up 'normal' clients */
6208 while ((pos != NULL) && (pos->client != client))
6215 while (NULL != (mqe = pos->message_queue_head))
6217 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
6218 pos->message_queue_tail,
6220 pos->message_count--;
6224 clients = pos->next;
6226 prev->next = pos->next;
6227 if (GNUNET_YES == pos->tcs_pending)
6232 if (pos->th != NULL)
6234 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
6237 GNUNET_break (0 == pos->message_count);
6243 * Function called when the service shuts down. Unloads our plugins
6244 * and cancels pending validations.
6246 * @param cls closure, unused
6247 * @param tc task context (unused)
6250 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6252 struct TransportPlugin *plug;
6253 struct OwnAddressList *al;
6254 struct CheckHelloValidatedContext *chvc;
6256 shutdown_in_progress = GNUNET_YES;
6257 while (neighbours != NULL)
6260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6261 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
6264 disconnect_neighbour (neighbours, GNUNET_NO);
6267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6268 "Transport service is unloading plugins...\n");
6270 while (NULL != (plug = plugins))
6272 plugins = plug->next;
6273 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
6275 GNUNET_SCHEDULER_cancel (plug->address_update_task);
6276 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
6278 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
6279 GNUNET_free (plug->lib_name);
6280 GNUNET_free (plug->short_name);
6281 while (NULL != (al = plug->addresses))
6283 plug->addresses = al->next;
6288 if (my_private_key != NULL)
6289 GNUNET_CRYPTO_rsa_key_free (my_private_key);
6290 GNUNET_free_non_null (our_hello);
6292 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
6295 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6296 validation_map = NULL;
6300 /* free 'chvc' data structure */
6301 while (NULL != (chvc = chvc_head))
6303 chvc_head = chvc->next;
6304 if (chvc->piter != NULL)
6306 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
6307 GNUNET_STATISTICS_update (stats,
6308 gettext_noop ("# outstanding peerinfo iterate requests"),
6315 GNUNET_assert (chvc->ve_count == 0);
6322 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6325 if (peerinfo != NULL)
6327 GNUNET_PEERINFO_disconnect (peerinfo);
6330 if (GNUNET_SCHEDULER_NO_TASK != hello_task)
6332 GNUNET_SCHEDULER_cancel (hello_task);
6333 hello_task = GNUNET_SCHEDULER_NO_TASK;
6335 /* Can we assume those are gone by now, or do we need to clean up
6337 GNUNET_break (bl_head == NULL);
6338 GNUNET_break (bc_head == NULL);
6342 static int ats_evaluate_results (int result, int solution, char * problem)
6344 int cont = GNUNET_NO;
6345 #if DEBUG_ATS || VERBOSE_ATS
6346 int error_kind = GNUNET_ERROR_TYPE_DEBUG;
6349 error_kind = GNUNET_ERROR_TYPE_ERROR;
6353 case GNUNET_SYSERR : /* GNUNET problem, not GLPK related */
6354 #if DEBUG_ATS || VERBOSE_ATS
6355 GNUNET_log (error_kind, "%s , GLPK solving not executed\n", problem);
6358 case GLP_ESTOP : /* search terminated by application */
6359 #if DEBUG_ATS || VERBOSE_ATS
6360 GNUNET_log (error_kind, "%s , Search terminated by application\n", problem);
6363 case GLP_EITLIM : /* iteration limit exceeded */
6364 #if DEBUG_ATS || VERBOSE_ATS
6365 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Iteration limit exceeded\n", problem);
6368 case GLP_ETMLIM : /* time limit exceeded */
6369 #if DEBUG_ATS || VERBOSE_ATS
6370 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Time limit exceeded\n", problem);
6373 case GLP_ENOPFS : /* no primal feasible solution */
6374 case GLP_ENODFS : /* no dual feasible solution */
6375 #if DEBUG_ATS || VERBOSE_ATS
6376 GNUNET_log (error_kind, "%s No feasible solution\n", problem);
6380 case GLP_EBADB : /* invalid basis */
6381 case GLP_ESING : /* singular matrix */
6382 case GLP_ECOND : /* ill-conditioned matrix */
6383 case GLP_EBOUND : /* invalid bounds */
6384 case GLP_EFAIL : /* solver failed */
6385 case GLP_EOBJLL : /* objective lower limit reached */
6386 case GLP_EOBJUL : /* objective upper limit reached */
6387 case GLP_EROOT : /* root LP optimum not provided */
6388 #if DEBUG_ATS || VERBOSE_ATS
6389 GNUNET_log (error_kind, "%s Invalid Input data: %i\n", problem, result);
6394 #if DEBUG_ATS || VERBOSE_ATS
6395 GNUNET_log (error_kind, "%s Problem has been solved\n", problem);
6402 #if DEBUG_ATS || VERBOSE_ATS
6403 GNUNET_log (error_kind, "%s solution is undefined\n", problem);
6407 #if DEBUG_ATS || VERBOSE_ATS
6408 GNUNET_log (error_kind, "%s solution is optimal\n", problem);
6413 #if DEBUG_ATS || VERBOSE_ATS
6414 GNUNET_log (error_kind, "%s solution is %s feasible, however, its optimality (or non-optimality) has not been proven, \n", problem, (0==strcmp(problem,"LP")?"":"integer"));
6419 #if DEBUG_ATS || VERBOSE_ATS
6420 GNUNET_log (error_kind, "%s problem has no %sfeasible solution\n", problem, (0==strcmp(problem,"LP")?"":"integer "));
6424 #if DEBUG_ATS || VERBOSE_ATS
6425 GNUNET_log (error_kind, "%s problem is infeasible \n", problem);
6429 #if DEBUG_ATS || VERBOSE_ATS
6430 GNUNET_log (error_kind, "%s problem is unbounded \n", problem);
6438 static void ats_solve_problem (unsigned int max_it, unsigned int max_dur, unsigned int c_peers, unsigned int c_mechs, struct ATS_stat *stat)
6440 int result = GNUNET_SYSERR;
6441 int lp_solution = GNUNET_SYSERR;
6442 int mlp_solution = GNUNET_SYSERR;
6446 glp_init_smcp(&opt_lp);
6448 opt_lp.msg_lev = GLP_MSG_ALL;
6450 opt_lp.msg_lev = GLP_MSG_OFF;
6453 // setting iteration limit
6454 opt_lp.it_lim = max_it;
6456 opt_lp.tm_lim = max_dur;
6458 if (ats->stat.recreate_problem == GNUNET_YES)
6459 opt_lp.presolve = GLP_ON;
6460 result = glp_simplex(ats->prob, &opt_lp);
6461 lp_solution = glp_get_status (ats->prob);
6463 if ((result == GLP_ETMLIM) || (result == GLP_EITLIM))
6465 ats->stat.valid = GNUNET_NO;
6466 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ATS exceeded time or iteration limit!\n");
6470 if (ats_evaluate_results(result, lp_solution, "LP") == GNUNET_YES)
6472 stat->valid = GNUNET_YES;
6476 ats->stat.simplex_rerun_required = GNUNET_YES;
6477 opt_lp.presolve = GLP_ON;
6478 result = glp_simplex(ats->prob, &opt_lp);
6479 lp_solution = glp_get_status (ats->prob);
6481 // TODO: Remove if this does not appear until release
6482 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "EXECUTED SIMPLEX WITH PRESOLVER! %i \n", lp_solution);
6484 if (ats_evaluate_results(result, lp_solution, "LP") != GNUNET_YES)
6486 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "After execution simplex with presolver: STILL INVALID!\n");
6488 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%llu.mlp",ats->stat.c_peers, ats->stat.c_mechs, GNUNET_TIME_absolute_get().abs_value);
6489 glp_write_lp (ats->prob, NULL, filename);
6490 GNUNET_free (filename);
6491 stat->valid = GNUNET_NO;
6492 ats->stat.recreate_problem = GNUNET_YES;
6495 stat->valid = GNUNET_YES;
6500 glp_init_iocp(&opt_mlp);
6502 opt_mlp.tm_lim = max_dur;
6505 opt_mlp.msg_lev = GLP_MSG_ALL;
6507 opt_mlp.msg_lev = GLP_MSG_OFF;
6510 result = glp_intopt (ats->prob, &opt_mlp);
6511 mlp_solution = glp_mip_status (ats->prob);
6512 stat->solution = mlp_solution;
6514 if (ats_evaluate_results(result, mlp_solution, "MLP") == GNUNET_YES)
6516 stat->valid = GNUNET_YES;
6520 // TODO: Remove if this does not appear until release
6521 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP solution for %i peers, %i mechs is invalid: %i\n", ats->stat.c_peers, ats->stat.c_mechs, mlp_solution);
6522 stat->valid = GNUNET_NO;
6527 int error = GNUNET_NO;
6529 struct ATS_mechanism *t = NULL;
6530 for (c=1; c<= (c_peers); c++ )
6533 t = peers[c].m_head;
6536 bw = glp_get_col_prim(prob, t->col_index);
6540 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[%i][%i] `%s' %s %s %f\n", c, t->col_index, GNUNET_h2s(&peers[c].peer.hashPubKey), t->plugin->short_name, glp_get_col_name(prob,t->col_index), bw);
6542 if (check ==GNUNET_YES)
6544 glp_write_sol(prob, "invalid_solution.mlp");
6545 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid solution, check invalid_solution.mlp");
6546 GNUNET_STATISTICS_update (stats, "ATS invalid solutions", 1, GNUNET_NO);
6549 if (check ==GNUNET_NO)
6557 if (glp_get_col_prim(ats->prob,2*c_mechs+1) != 1)
6560 for (c=1; c<= available_quality_metrics; c++ )
6562 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+3+c), glp_get_col_prim(ats->prob,2*c_mechs+3+c));
6564 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+1), glp_get_col_prim(ats->prob,2*c_mechs+1));
6565 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+2), glp_get_col_prim(ats->prob,2*c_mechs+2));
6566 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s %f\n", glp_get_col_name(ats->prob,2*c_mechs+3), glp_get_col_prim(ats->prob,2*c_mechs+3));
6567 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "objective value: %f\n", glp_mip_obj_val(ats->prob));
6572 static void ats_delete_problem ()
6575 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Deleting problem\n");
6579 for (c=0; c< (ats->stat).c_mechs; c++)
6580 GNUNET_free_non_null (ats->mechanisms[c].rc);
6583 if (ats->mechanisms!=NULL)
6585 GNUNET_free(ats->mechanisms);
6586 ats->mechanisms = NULL;
6589 if (ats->peers!=NULL)
6591 GNUNET_free(ats->peers);
6595 if (ats->prob != NULL)
6597 glp_delete_prob(ats->prob);
6601 ats->stat.begin_cr = GNUNET_SYSERR;
6602 ats->stat.begin_qm = GNUNET_SYSERR;
6603 ats->stat.c_mechs = 0;
6604 ats->stat.c_peers = 0;
6605 ats->stat.end_cr = GNUNET_SYSERR;
6606 ats->stat.end_qm = GNUNET_SYSERR;
6607 ats->stat.solution = GNUNET_SYSERR;
6608 ats->stat.valid = GNUNET_SYSERR;
6612 static void ats_update_problem_qm ()
6617 int c_q_metrics = available_quality_metrics;
6619 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6620 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6622 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6624 row_index = ats->stat.begin_qm;
6626 for (c=1; c <= c_q_metrics; c++)
6631 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6634 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6635 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6637 ja[array_index] = c2;
6639 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6640 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6642 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
6644 double v0 = 0, v1 = 0, v2 = 0;
6646 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6647 if (v1 < 1) v0 = 0.1;
6648 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6649 if (v1 < 1) v0 = 0.1;
6650 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6651 if (v1 < 1) v0 = 0.1;
6652 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
6655 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
6657 double v0 = 0, v1 = 0, v2 = 0;
6658 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6660 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6662 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6664 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
6666 value = (double) 10 / value;
6670 ar[array_index] = (ats->mechanisms[c2].peer->f) * value;
6672 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: %s [%i,%i]=%f \n",array_index, qm[c-1].name, row_index, ja[array_index], ar[array_index]);
6676 ja[array_index] = ats->stat.col_qm + c - 1;
6677 ar[array_index] = -1;
6680 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6682 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6688 GNUNET_free_non_null (ja);
6689 GNUNET_free_non_null (ar);
6693 static void ats_update_problem_cr ()
6699 double ct_max, ct_min;
6701 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6702 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6704 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6705 row_index = ats->stat.begin_cr;
6708 for (c=0; c<available_ressources; c++)
6710 ct_max = ressources[c].c_max;
6711 ct_min = ressources[c].c_min;
6713 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
6715 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
6717 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6721 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6722 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6724 ja[array_index] = c2;
6725 value = ats->mechanisms[c2].addr->ressources[c].c;
6726 ar[array_index] = value;
6728 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6732 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6738 GNUNET_free_non_null (ja);
6739 GNUNET_free_non_null (ar);
6744 static void ats_update_problem_qm_TEST ()
6749 int old_ja[ats->stat.c_mechs + 2];
6750 double old_ar[ats->stat.c_mechs + 2];
6754 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6755 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6757 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics TEST\n");
6759 if (ats->stat.begin_qm >0)
6760 row_index = ats->stat.begin_qm;
6765 for (c=0; c<available_quality_metrics; c++)
6768 c_old = glp_get_mat_row (ats->prob, row_index, old_ja, old_ar);
6770 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6772 for (c2=1; c2<=c_old; c2++)
6774 ja[c2] = old_ja[c2];
6775 if ((changed < 3) && (c2>2) && (old_ar[c2] != -1))
6777 ar[c2] = old_ar[c2] + 5 - changed;
6781 ar[c2] = old_ar[c2];
6783 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: old [%i,%i]=%f new [%i,%i]=%f\n",c2, row_index, old_ja[c2], old_ar[c2], row_index, ja[c2], ar[c2]);
6786 glp_set_mat_row (ats->prob, row_index, c_old, ja, ar);
6791 GNUNET_free_non_null (ja);
6792 GNUNET_free_non_null (ar);
6794 #endif //END: HAVE_LIBGLPK
6796 /** solve the bandwidth distribution problem
6797 * @param max_it maximum iterations
6798 * @param max_dur maximum duration in ms
6799 * @param D weight for diversity
6800 * @param U weight for utility
6801 * @param R weight for relativity
6802 * @param v_b_min minimal bandwidth per peer
6803 * @param v_n_min minimum number of connections
6804 * @param stat result struct
6805 * @return GNUNET_SYSERR if glpk is not available, number of mechanisms used
6807 static int ats_create_problem (double D, double U, double R, int v_b_min, int v_n_min, struct ATS_stat *stat)
6809 ats->prob = glp_create_prob();
6815 int c_c_ressources = available_ressources;
6816 int c_q_metrics = available_quality_metrics;
6818 double M = VERY_BIG_DOUBLE_VALUE;
6819 double Q[c_q_metrics+1];
6820 for (c=1; c<=c_q_metrics; c++)
6825 struct NeighbourList *next = neighbours;
6828 int found_addresses = GNUNET_NO;
6829 struct ReadyList *r_next = next->plugins;
6830 while (r_next != NULL)
6832 struct ForeignAddressList * a_next = r_next->addresses;
6833 while (a_next != NULL)
6836 found_addresses = GNUNET_YES;
6837 a_next = a_next->next;
6839 r_next = r_next->next;
6841 if (found_addresses) c_peers++;
6848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No addresses for bw distribution available\n", c_peers);
6850 stat->valid = GNUNET_NO;
6853 return GNUNET_SYSERR;
6856 GNUNET_assert (ats->mechanisms == NULL);
6857 ats->mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
6858 GNUNET_assert (ats->peers == NULL);
6859 ats->peers = GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
6861 struct ATS_mechanism * mechanisms = ats->mechanisms;
6862 struct ATS_peer * peers = ats->peers;
6870 int found_addresses = GNUNET_NO;
6871 struct ReadyList *r_next = next->plugins;
6872 while (r_next != NULL)
6874 struct ForeignAddressList * a_next = r_next->addresses;
6875 while (a_next != NULL)
6877 if (found_addresses == GNUNET_NO)
6879 peers[c_peers].peer = next->id;
6880 peers[c_peers].m_head = NULL;
6881 peers[c_peers].m_tail = NULL;
6882 peers[c_peers].f = 1.0 / c_mechs;
6885 mechanisms[c_mechs].addr = a_next;
6886 mechanisms[c_mechs].col_index = c_mechs;
6887 mechanisms[c_mechs].peer = &peers[c_peers];
6888 mechanisms[c_mechs].next = NULL;
6889 mechanisms[c_mechs].plugin = r_next->plugin;
6891 GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head, peers[c_peers].m_tail, &mechanisms[c_mechs]);
6892 found_addresses = GNUNET_YES;
6895 a_next = a_next->next;
6897 r_next = r_next->next;
6899 if (found_addresses == GNUNET_YES)
6906 if (v_n_min > c_peers)
6910 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Creating problem with: %i peers, %i mechanisms, %i resource entries, %i quality metrics \n", c_peers, c_mechs, c_c_ressources, c_q_metrics);
6913 int size = 1 + 3 + 10 *c_mechs + c_peers + (c_q_metrics*c_mechs)+ c_q_metrics + c_c_ressources * c_mechs ;
6916 int * ia = GNUNET_malloc (size * sizeof (int));
6917 int * ja = GNUNET_malloc (size * sizeof (int));
6918 double * ar = GNUNET_malloc(size* sizeof (double));
6920 glp_set_prob_name(ats->prob, "gnunet ats bandwidth distribution");
6921 glp_set_obj_dir(ats->prob, GLP_MAX);
6923 /* adding columns */
6925 glp_add_cols(ats->prob, 2 * c_mechs);
6926 /* adding b_t cols */
6927 for (c=1; c <= c_mechs; c++)
6930 GNUNET_asprintf(&name, "p_%s_b%i",GNUNET_i2s(&(mechanisms[c].peer->peer)), c);
6931 glp_set_col_name(ats->prob, c, name);
6933 glp_set_col_bnds(ats->prob, c, GLP_LO, 0.0, 0.0);
6934 glp_set_col_kind(ats->prob, c, GLP_CV);
6935 glp_set_obj_coef(ats->prob, c, 0);
6938 /* adding n_t cols */
6939 for (c=c_mechs+1; c <= 2*c_mechs; c++)
6941 GNUNET_asprintf(&name, "p_%s_n%i",GNUNET_i2s(&(mechanisms[c-c_mechs].peer->peer)),(c-c_mechs));
6942 glp_set_col_name(ats->prob, c, name);
6944 glp_set_col_bnds(ats->prob, c, GLP_DB, 0.0, 1.0);
6945 glp_set_col_kind(ats->prob, c, GLP_IV);
6946 glp_set_obj_coef(ats->prob, c, 0);
6949 /* feasibility constraints */
6950 /* Constraint 1: one address per peer*/
6952 glp_add_rows(ats->prob, c_peers);
6953 for (c=1; c<=c_peers; c++)
6956 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6958 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 1.0, 1.0);
6960 struct ATS_mechanism *m = peers[c].m_head;
6963 ia[array_index] = row_index;
6964 ja[array_index] = (c_mechs + m->col_index);
6965 ar[array_index] = 1;
6967 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6975 /* Constraint 2: only active mechanism gets bandwidth assigned */
6976 glp_add_rows(ats->prob, c_mechs);
6977 for (c=1; c<=c_mechs; c++)
6979 /* b_t - n_t * M <= 0 */
6981 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6983 glp_set_row_bnds(ats->prob, row_index, GLP_UP, 0.0, 0.0);
6985 ia[array_index] = row_index;
6986 ja[array_index] = mechanisms[c].col_index;
6987 ar[array_index] = 1;
6989 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6992 ia[array_index] = row_index;
6993 ja[array_index] = c_mechs + mechanisms[c].col_index;
6994 ar[array_index] = -M;
6996 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7002 /* Constraint 3: minimum bandwidth*/
7003 glp_add_rows(ats->prob, c_mechs);
7004 for (c=1; c<=c_mechs; c++)
7006 /* b_t - n_t * b_min <= 0 */
7008 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7010 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
7012 ia[array_index] = row_index;
7013 ja[array_index] = mechanisms[c].col_index;
7014 ar[array_index] = 1;
7016 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7019 ia[array_index] = row_index;
7020 ja[array_index] = c_mechs + mechanisms[c].col_index;
7021 ar[array_index] = -v_b_min;
7023 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7029 /* Constraint 4: max ressource capacity */
7030 /* V cr: bt * ct_r <= cr_max
7032 glp_add_rows(ats->prob, available_ressources);
7033 double ct_max = VERY_BIG_DOUBLE_VALUE;
7034 double ct_min = 0.0;
7036 stat->begin_cr = array_index;
7038 for (c=0; c<available_ressources; c++)
7040 ct_max = ressources[c].c_max;
7041 ct_min = ressources[c].c_min;
7043 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
7045 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
7047 for (c2=1; c2<=c_mechs; c2++)
7050 ia[array_index] = row_index;
7051 ja[array_index] = c2;
7052 value = mechanisms[c2].addr->ressources[c].c;
7053 ar[array_index] = value;
7055 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7061 stat->end_cr = array_index--;
7063 /* Constraint 5: min number of connections*/
7064 glp_add_rows(ats->prob, 1);
7065 for (c=1; c<=c_mechs; c++)
7067 // b_t - n_t * b_min >= 0
7069 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7071 glp_set_row_bnds(ats->prob, row_index, GLP_LO, v_n_min, 0.0);
7073 ia[array_index] = row_index;
7074 ja[array_index] = c_mechs + mechanisms[c].col_index;
7075 ar[array_index] = 1;
7077 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7083 // optimisation constraints
7087 // Constraint 6: optimize for diversity
7089 col_d = glp_add_cols(ats->prob, 1);
7090 stat->col_d = col_d;
7091 //GNUNET_assert (col_d == (2*c_mechs) + 1);
7092 glp_set_col_name(ats->prob, col_d, "d");
7093 glp_set_obj_coef(ats->prob, col_d, D);
7094 glp_set_col_bnds(ats->prob, col_d, GLP_LO, 0.0, 0.0);
7095 glp_add_rows(ats->prob, 1);
7097 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7099 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7100 for (c=1; c<=c_mechs; c++)
7102 ia[array_index] = row_index;
7103 ja[array_index] = c_mechs + mechanisms[c].col_index;
7104 ar[array_index] = 1;
7106 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7110 ia[array_index] = row_index;
7111 ja[array_index] = col_d;
7112 ar[array_index] = -1;
7114 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7120 // Constraint 7: optimize for quality
7122 col_qm = glp_add_cols(ats->prob, c_q_metrics);
7123 stat->col_qm = col_qm;
7124 //GNUNET_assert (col_qm == (2*c_mechs) + 3 + 1);
7125 for (c=0; c< c_q_metrics; c++)
7127 GNUNET_asprintf(&name, "Q_%s",qm[c].name);
7128 glp_set_col_name(ats->prob, col_qm + c, name);
7129 glp_set_col_bnds(ats->prob, col_qm + c, GLP_LO, 0.0, 0.0);
7131 glp_set_obj_coef(ats->prob, col_qm + c, Q[c]);
7133 glp_add_rows(ats->prob, available_quality_metrics);
7134 stat->begin_qm = row_index;
7135 for (c=1; c <= c_q_metrics; c++)
7138 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7141 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7142 for (c2=1; c2<=c_mechs; c2++)
7145 ia[array_index] = row_index;
7146 ja[array_index] = c2;
7147 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
7149 double v0 = 0, v1 = 0, v2 = 0;
7150 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7151 if (v1 < 1) v0 = 0.1;
7152 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7153 if (v1 < 1) v0 = 0.1;
7154 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7155 if (v1 < 1) v0 = 0.1;
7156 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
7159 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
7161 double v0 = 0, v1 = 0, v2 = 0;
7162 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7164 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7166 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7168 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
7170 value = (double) 10 / value;
7174 ar[array_index] = (mechanisms[c2].peer->f) * value ;
7176 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: %s [%i,%i]=%f \n",array_index, qm[c-1].name, ia[array_index], ja[array_index], ar[array_index]);
7181 ia[array_index] = row_index;
7182 ja[array_index] = col_qm + c - 1;
7183 ar[array_index] = -1;
7185 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7190 stat->end_qm = row_index-1;
7192 // Constraint 8: optimize bandwidth utility
7194 col_u = glp_add_cols(ats->prob, 1);
7195 stat->col_u = col_u;
7196 //GNUNET_assert (col_u == (2*c_mechs) + 2);
7197 glp_set_col_name(ats->prob, col_u, "u");
7198 glp_set_obj_coef(ats->prob, col_u, U);
7199 glp_set_col_bnds(ats->prob, col_u, GLP_LO, 0.0, 0.0);
7200 glp_add_rows(ats->prob, 1);
7202 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7204 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7205 for (c=1; c<=c_mechs; c++)
7207 ia[array_index] = row_index;
7208 ja[array_index] = c;
7209 ar[array_index] = mechanisms[c].peer->f;
7211 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7215 ia[array_index] = row_index;
7216 ja[array_index] = col_u;
7217 ar[array_index] = -1;
7219 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7225 // Constraint 9: optimize relativity
7227 col_r = glp_add_cols(ats->prob, 1);
7228 stat->col_r = col_r;
7229 //GNUNET_assert (col_r == (2*c_mechs) + 3);
7230 glp_set_col_name(ats->prob, col_r, "r");
7231 glp_set_obj_coef(ats->prob, col_r, R);
7232 glp_set_col_bnds(ats->prob, col_r, GLP_LO, 0.0, 0.0);
7233 glp_add_rows(ats->prob, c_peers);
7234 for (c=1; c<=c_peers; c++)
7236 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
7238 struct ATS_mechanism *m = peers[c].m_head;
7241 ia[array_index] = row_index;
7242 ja[array_index] = m->col_index;
7243 ar[array_index] = 1 / mechanisms[c].peer->f;
7245 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7250 ia[array_index] = row_index;
7251 ja[array_index] = col_r;
7252 ar[array_index] = -1;
7254 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7261 /* Loading the matrix */
7262 glp_load_matrix(ats->prob, array_index-1, ia, ja, ar);
7264 stat->c_mechs = c_mechs;
7265 stat->c_peers = c_peers;
7267 stat->valid = GNUNET_YES;
7279 void ats_notify_ats_data (
7280 const struct GNUNET_PeerIdentity *peer,
7281 const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
7284 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
7286 if (shutdown_in_progress == GNUNET_NO)
7287 ats_calculate_bandwidth_distribution();
7289 #endif //END: HAVE_LIBGLPK
7292 ats_calculate_bandwidth_distribution ()
7296 struct GNUNET_TIME_Absolute start;
7297 struct GNUNET_TIME_Relative creation;
7298 struct GNUNET_TIME_Relative solving;
7299 char *text = "unmodified";
7301 struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference (ats->last, GNUNET_TIME_absolute_get());
7302 if (delta.rel_value < ats->min_delta.rel_value)
7305 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
7310 if (shutdown_in_progress == GNUNET_YES)
7313 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Transport service is shutting down\n");
7320 if (INT_MAX < ats->max_exec_duration.rel_value)
7323 dur = (int) ats->max_exec_duration.rel_value;
7326 ats->stat.simplex_rerun_required = GNUNET_NO;
7327 start = GNUNET_TIME_absolute_get();
7328 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL) || (ats->stat.valid == GNUNET_NO))
7331 ats->stat.recreate_problem = GNUNET_YES;
7332 ats_delete_problem ();
7333 ats_create_problem (ats->D, ats->U, ats->R, ats->v_b_min, ats->v_n_min, &ats->stat);
7335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Peers/Addresses were modified... new problem: %i peer, %i mechs\n", ats->stat.c_peers, ats->stat.c_mechs);
7339 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_resources == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7341 text = "modified resources";
7342 ats_update_problem_cr();
7344 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_quality == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7346 text = "modified quality";
7347 ats_update_problem_qm();
7348 //ats_update_problem_qm_TEST ();
7352 else GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Problem is unmodified\n");
7355 creation = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7356 start = GNUNET_TIME_absolute_get();
7358 ats->stat.solution = GLP_UNDEF;
7359 if (ats->stat.valid == GNUNET_YES)
7361 ats_solve_problem(ats->max_iterations, ats->max_exec_duration.rel_value, ats->stat.c_peers, ats->stat.c_mechs, &ats->stat);
7363 solving = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7365 if (ats->stat.valid == GNUNET_YES)
7367 int msg_type = GNUNET_ERROR_TYPE_DEBUG;
7369 msg_type = GNUNET_ERROR_TYPE_ERROR;
7371 GNUNET_log (msg_type, "MLP %s: creation time: %llu, execution time: %llu, %i mechanisms, simplex rerun: %s, solution %s\n",
7372 text, creation.rel_value, solving.rel_value,
7374 (ats->stat.simplex_rerun_required == GNUNET_NO) ? "NO" : "YES", (ats->stat.solution == 5) ? "OPTIMAL" : "INVALID");
7375 ats->successful_executions ++;
7376 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7378 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL))
7379 GNUNET_STATISTICS_set (stats, "ATS state",ATS_NEW, GNUNET_NO);
7380 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7381 (ats->stat.modified_quality == GNUNET_NO))
7382 GNUNET_STATISTICS_set (stats, "ATS state", ATS_C_UPDATED, GNUNET_NO);
7383 else if ((ats->stat.modified_resources == GNUNET_NO) &&
7384 (ats->stat.modified_quality == GNUNET_YES) &&
7385 (ats->stat.simplex_rerun_required == GNUNET_NO))
7386 GNUNET_STATISTICS_set (stats, "ATS state", ATS_Q_UPDATED, GNUNET_NO);
7387 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7388 (ats->stat.modified_quality == GNUNET_YES) &&
7389 (ats->stat.simplex_rerun_required == GNUNET_NO))
7390 GNUNET_STATISTICS_set (stats, "ATS state", ATS_QC_UPDATED, GNUNET_NO);
7391 else if (ats->stat.simplex_rerun_required == GNUNET_NO)
7392 GNUNET_STATISTICS_set (stats, "ATS state", ATS_UNMODIFIED, GNUNET_NO);
7396 if (ats->stat.c_peers != 0)
7398 ats->invalid_executions ++;
7399 GNUNET_STATISTICS_set (stats, "# ATS invalid executions", ats->invalid_executions, GNUNET_NO);
7403 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7407 GNUNET_STATISTICS_set (stats, "ATS duration", solving.rel_value + creation.rel_value, GNUNET_NO);
7408 GNUNET_STATISTICS_set (stats, "ATS mechanisms", ats->stat.c_mechs, GNUNET_NO);
7409 GNUNET_STATISTICS_set (stats, "ATS peers", ats->stat.c_peers, GNUNET_NO);
7410 GNUNET_STATISTICS_set (stats, "ATS solution", ats->stat.solution, GNUNET_NO);
7411 GNUNET_STATISTICS_set (stats, "ATS timestamp", start.abs_value, GNUNET_NO);
7413 if ((ats->save_mlp == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7416 if (ats->dump_overwrite == GNUNET_NO)
7418 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.mlp",
7419 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7420 glp_write_lp (ats->prob, NULL, filename);
7424 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.mlp",
7425 ats->stat.c_peers, ats->stat.c_mechs );
7426 glp_write_lp (ats->prob, NULL, filename);
7428 GNUNET_free (filename);
7430 if ((ats->save_solution == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7433 if (ats->dump_overwrite == GNUNET_NO)
7435 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.sol",
7436 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7437 glp_print_sol (ats->prob, filename);
7441 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.sol",
7442 ats->stat.c_peers, ats->stat.c_mechs);
7443 glp_print_sol (ats->prob, filename);
7445 GNUNET_free (filename);
7448 ats->last = GNUNET_TIME_absolute_get();
7449 ats->stat.recreate_problem = GNUNET_NO;
7450 ats->stat.modified_resources = GNUNET_NO;
7451 ats->stat.modified_quality = GNUNET_NO;
7456 ats_schedule_calculation (void *cls,
7457 const struct GNUNET_SCHEDULER_TaskContext *tc)
7459 struct ATS_info *ats = (struct ATS_info *) cls;
7460 if (ats==NULL) return;
7462 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7463 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
7466 if (shutdown_in_progress == GNUNET_YES)
7470 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
7473 ats_calculate_bandwidth_distribution (ats);
7475 ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_interval,
7476 &ats_schedule_calculation, ats);
7482 unsigned long long value;
7485 ats = GNUNET_malloc(sizeof (struct ATS_info));
7487 ats->min_delta = ATS_MIN_INTERVAL;
7488 ats->exec_interval = ATS_EXEC_INTERVAL;
7489 ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
7490 ats->max_iterations = ATS_MAX_ITERATIONS;
7491 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS not active\n");
7501 ats->v_b_min = 64000;
7503 ats->dump_min_peers = 1;
7504 ats->dump_min_addr = 1;
7505 ats->dump_overwrite = GNUNET_NO;
7506 ats->mechanisms = NULL;
7508 ats->successful_executions = 0;
7509 ats->invalid_executions = 0;
7515 /* loading cost ressources */
7516 for (c=0; c<available_ressources; c++)
7518 GNUNET_asprintf(§ion,"%s_UP",ressources[c].cfg_param);
7519 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7521 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7524 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7526 ressources[c].c_max = value;
7529 GNUNET_free (section);
7530 GNUNET_asprintf(§ion,"%s_DOWN",ressources[c].cfg_param);
7531 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7533 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7536 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7538 ressources[c].c_min = value;
7541 GNUNET_free (section);
7544 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MLP"))
7545 ats->save_mlp = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_MLP");
7547 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_SOLUTION"))
7548 ats->save_solution = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_SOLUTION");
7549 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7550 ats->dump_overwrite = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_OVERWRITE");
7551 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_PEERS"))
7553 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_PEERS", &value);
7554 ats->dump_min_peers= value;
7556 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_ADDRS"))
7558 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_ADDRS", &value);
7559 ats->dump_min_addr= value;
7561 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7563 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_OVERWRITE", &value);
7564 ats->min_delta.rel_value = value;
7567 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7569 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7570 ats->min_delta.rel_value = value;
7573 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_EXEC_INTERVAL"))
7575 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_EXEC_INTERVAL", &value);
7576 ats->exec_interval.rel_value = value;
7578 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7580 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7581 ats->min_delta.rel_value = value;
7584 ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
7588 static void ats_shutdown ()
7591 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_destroy\n");
7593 if (ats->ats_task != GNUNET_SCHEDULER_NO_TASK)
7594 GNUNET_SCHEDULER_cancel(ats->ats_task);
7595 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7598 ats_delete_problem ();
7605 void ats_notify_peer_connect (
7606 const struct GNUNET_PeerIdentity *peer,
7607 const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count)
7610 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_connect: %s\n",GNUNET_i2s(peer));
7612 //update_addr_ats();
7613 ats->stat.recreate_problem = GNUNET_YES;
7614 ats_calculate_bandwidth_distribution(ats);
7617 void ats_notify_peer_disconnect (
7618 const struct GNUNET_PeerIdentity *peer)
7621 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_disconnect: %s\n",GNUNET_i2s(peer));
7623 ats->stat.recreate_problem = GNUNET_YES;
7624 ats_calculate_bandwidth_distribution (ats);
7627 struct ForeignAddressList * ats_get_preferred_address (
7628 struct NeighbourList *n)
7631 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ats_get_prefered_transport for peer: %s\n",GNUNET_i2s(&n->id));
7633 struct ReadyList *next = n->plugins;
7634 while (next != NULL)
7637 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "plugin: %s %i\n",next->plugin->short_name,strcmp(next->plugin->short_name,"unix"));
7641 return find_ready_address(n);
7645 * Initiate transport service.
7647 * @param cls closure
7648 * @param server the initialized server
7649 * @param c configuration to use
7653 struct GNUNET_SERVER_Handle *server,
7654 const struct GNUNET_CONFIGURATION_Handle *c)
7656 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
7657 {&handle_start, NULL,
7658 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
7659 {&handle_hello, NULL,
7660 GNUNET_MESSAGE_TYPE_HELLO, 0},
7661 {&handle_send, NULL,
7662 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
7663 {&handle_request_connect, NULL,
7664 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
7665 {&handle_set_quota, NULL,
7666 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
7667 {&handle_address_lookup, NULL,
7668 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
7670 {&handle_blacklist_init, NULL,
7671 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
7672 {&handle_blacklist_reply, NULL,
7673 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
7679 unsigned long long tneigh;
7682 shutdown_in_progress = GNUNET_NO;
7684 stats = GNUNET_STATISTICS_create ("transport", cfg);
7685 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
7686 /* parse configuration */
7688 GNUNET_CONFIGURATION_get_value_number (c,
7693 GNUNET_CONFIGURATION_get_value_filename (c,
7695 "HOSTKEY", &keyfile)))
7697 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7699 ("Transport service is lacking key configuration settings. Exiting.\n"));
7700 GNUNET_SCHEDULER_shutdown ();
7703 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7706 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7707 validation_map = NULL;
7711 max_connect_per_transport = (uint32_t) tneigh;
7712 peerinfo = GNUNET_PEERINFO_connect (cfg);
7713 if (peerinfo == NULL)
7715 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7716 _("Could not access PEERINFO service. Exiting.\n"));
7717 GNUNET_SCHEDULER_shutdown ();
7720 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7723 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7724 validation_map = NULL;
7725 GNUNET_free (keyfile);
7728 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7729 GNUNET_free (keyfile);
7730 if (my_private_key == NULL)
7732 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7734 ("Transport service could not access hostkey. Exiting.\n"));
7735 GNUNET_SCHEDULER_shutdown ();
7738 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7741 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7742 validation_map = NULL;
7745 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7746 GNUNET_CRYPTO_hash (&my_public_key,
7747 sizeof (my_public_key), &my_identity.hashPubKey);
7748 /* setup notification */
7749 GNUNET_SERVER_disconnect_notify (server,
7750 &client_disconnect_notification, NULL);
7751 /* load plugins... */
7754 GNUNET_CONFIGURATION_get_value_string (c,
7755 "TRANSPORT", "PLUGINS", &plugs))
7757 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7758 _("Starting transport plugins `%s'\n"), plugs);
7759 pos = strtok (plugs, " ");
7762 start_transport (server, pos);
7764 pos = strtok (NULL, " ");
7766 GNUNET_free (plugs);
7768 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
7769 &shutdown_task, NULL);
7776 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7777 _("Transport service ready.\n"));
7779 /* If we have a blacklist file, read from it */
7780 read_blacklist_file(cfg);
7781 /* process client requests */
7782 GNUNET_SERVER_add_handlers (server, handlers);
7787 * The main function for the transport service.
7789 * @param argc number of arguments from the command line
7790 * @param argv command line arguments
7791 * @return 0 ok, 1 on error
7794 main (int argc, char *const *argv)
7796 a2s (NULL, NULL, 0); /* make compiler happy */
7797 return (GNUNET_OK ==
7798 GNUNET_SERVICE_run (argc,
7801 GNUNET_SERVICE_OPTION_NONE,
7802 &run, NULL)) ? 0 : 1;
7805 /* end of gnunet-service-transport.c */