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 * Is transport service shutting down ?
1223 static int shutdown_in_progress;
1226 * Handle for ats information
1228 static struct ATS_info *ats;
1230 struct ATS_quality_entry
1238 static struct ATS_quality_metric qm[] =
1240 {1, 1028, "QUALITY_NET_DISTANCE"},
1241 {2, 1034, "QUALITY_NET_DELAY"},
1243 static int available_quality_metrics = 2;
1247 * The peer specified by the given neighbour has timed-out or a plugin
1248 * has disconnected. We may either need to do nothing (other plugins
1249 * still up), or trigger a full disconnect and clean up. This
1250 * function updates our state and do the necessary notifications.
1251 * Also notifies our clients that the neighbour is now officially
1254 * @param n the neighbour list entry for the peer
1255 * @param check should we just check if all plugins
1256 * disconnected or must we ask all plugins to
1259 static void disconnect_neighbour (struct NeighbourList *n, int check);
1262 * Check the ready list for the given neighbour and if a plugin is
1263 * ready for transmission (and if we have a message), do so!
1265 * @param nexi target peer for which to transmit
1267 static void try_transmission_to_peer (struct NeighbourList *n);
1269 static void ats_shutdown ( );
1271 static void ats_notify_peer_connect (
1272 const struct GNUNET_PeerIdentity *peer,
1273 const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count);
1275 static void ats_notify_peer_disconnect (
1276 const struct GNUNET_PeerIdentity *peer);
1279 static void ats_notify_ats_data (
1280 const struct GNUNET_PeerIdentity *peer,
1281 const struct GNUNET_TRANSPORT_ATS_Information *ats_data);
1284 struct ForeignAddressList * ats_get_preferred_address (
1285 struct NeighbourList *n);
1288 ats_calculate_bandwidth_distribution ();
1291 * Find an entry in the neighbour list for a particular peer.
1293 * @return NULL if not found.
1295 static struct NeighbourList *
1296 find_neighbour (const struct GNUNET_PeerIdentity *key)
1298 struct NeighbourList *head = neighbours;
1300 while ((head != NULL) &&
1301 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
1306 static int update_addr_value (struct ForeignAddressList *fal, uint32_t value , int ats_index)
1309 int set = GNUNET_NO;
1310 for (c=0; c<available_quality_metrics; c++)
1312 if (ats_index == qm[c].atis_index)
1314 fal->quality[c].values[0] = fal->quality[c].values[1];
1315 fal->quality[c].values[1] = fal->quality[c].values[2];
1316 fal->quality[c].values[2] = value;
1318 ats->stat.modified_quality = GNUNET_YES;
1321 if (set == GNUNET_NO)
1323 for (c=0; c<available_ressources; c++)
1325 if (ats_index == ressources[c].atis_index)
1327 fal->ressources[c].c = value;
1329 ats->stat.modified_resources = GNUNET_YES;
1338 update_addr_ats (struct ForeignAddressList *fal,
1339 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
1344 for (c1=0; c1<ats_count; c1++)
1346 set = update_addr_value(fal, ntohl(ats_data[c1].value), ntohl(ats_data[c1].type));
1352 * Find an entry in the transport list for a particular transport.
1354 * @return NULL if not found.
1356 static struct TransportPlugin *
1357 find_transport (const char *short_name)
1359 struct TransportPlugin *head = plugins;
1360 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
1366 * Is a particular peer blacklisted for a particular transport?
1368 * @param peer the peer to check for
1369 * @param plugin the plugin used to connect to the peer
1371 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
1374 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
1377 if (plugin->blacklist != NULL)
1379 if (GNUNET_CONTAINER_multihashmap_contains (plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
1382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1383 "Peer `%s:%s' is blacklisted!\n",
1384 plugin->short_name, GNUNET_i2s (peer));
1387 GNUNET_STATISTICS_update (stats, "# blacklisted peers refused", 1, GNUNET_NO);
1397 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer,
1398 char *transport_name)
1400 struct TransportPlugin *plugin;
1402 plugin = find_transport(transport_name);
1403 if (plugin == NULL) /* Nothing to do */
1406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407 "Adding peer `%s' with plugin `%s' to blacklist\n",
1411 if (plugin->blacklist == NULL)
1412 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
1413 GNUNET_assert(plugin->blacklist != NULL);
1414 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
1416 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1421 * Read the blacklist file, containing transport:peer entries.
1422 * Provided the transport is loaded, set up hashmap with these
1423 * entries to blacklist peers by transport.
1427 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1434 struct GNUNET_PeerIdentity pid;
1436 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1437 unsigned int entries_found;
1438 char *transport_name;
1441 GNUNET_CONFIGURATION_get_value_filename (cfg,
1447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1448 "Option `%s' in section `%s' not specified!\n",
1454 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1455 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1456 | GNUNET_DISK_PERM_USER_WRITE);
1457 if (0 != STAT (fn, &frstat))
1459 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1460 _("Could not read blacklist file `%s'\n"), fn);
1464 if (frstat.st_size == 0)
1467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1468 _("Blacklist file `%s' is empty.\n"),
1474 /* FIXME: use mmap */
1475 data = GNUNET_malloc_large (frstat.st_size);
1476 GNUNET_assert(data != NULL);
1477 if (frstat.st_size !=
1478 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1480 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1481 _("Failed to read blacklist from `%s'\n"), fn);
1488 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1490 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1491 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1494 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1497 if (colon_pos >= frstat.st_size)
1499 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1500 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1501 (unsigned long long) colon_pos);
1507 if (isspace( (unsigned char) data[colon_pos]))
1509 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1510 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1511 (unsigned long long) colon_pos);
1513 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1517 tsize = colon_pos - pos;
1518 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1520 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1521 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1522 (unsigned long long) colon_pos);
1531 transport_name = GNUNET_malloc(tsize + 1);
1532 memcpy(transport_name, &data[pos], tsize);
1533 pos = colon_pos + 1;
1535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1536 "Read transport name %s in blacklist file.\n",
1539 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1540 if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1542 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1543 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1544 (unsigned long long) pos);
1546 while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1548 GNUNET_free_non_null(transport_name);
1551 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1552 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1554 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1555 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1556 (unsigned long long) pos,
1561 if (0 != memcmp (&pid,
1563 sizeof (struct GNUNET_PeerIdentity)))
1566 add_peer_to_blacklist (&pid,
1571 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1572 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1576 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1577 GNUNET_free_non_null(transport_name);
1578 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1581 GNUNET_STATISTICS_update (stats, "# Transport entries blacklisted", entries_found, GNUNET_NO);
1588 * Function called to notify a client about the socket being ready to
1589 * queue more data. "buf" will be NULL and "size" zero if the socket
1590 * was closed for writing in the meantime.
1592 * @param cls closure
1593 * @param size number of bytes available in buf
1594 * @param buf where the callee should write the message
1595 * @return number of bytes written to buf
1598 transmit_to_client_callback (void *cls, size_t size, void *buf)
1600 struct TransportClient *client = cls;
1601 struct ClientMessageQueueEntry *q;
1604 const struct GNUNET_MessageHeader *msg;
1611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612 "Transmission to client failed, closing connection.\n");
1614 /* fatal error with client, free message queue! */
1615 while (NULL != (q = client->message_queue_head))
1617 GNUNET_STATISTICS_update (stats,
1618 gettext_noop ("# bytes discarded (could not transmit to client)"),
1619 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1621 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1622 client->message_queue_tail,
1626 client->message_count = 0;
1631 while (NULL != (q = client->message_queue_head))
1633 msg = (const struct GNUNET_MessageHeader *) &q[1];
1634 msize = ntohs (msg->size);
1635 if (msize + tsize > size)
1638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1639 "Transmitting message of type %u to client.\n",
1642 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1643 client->message_queue_tail,
1645 memcpy (&cbuf[tsize], msg, msize);
1648 client->message_count--;
1652 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1653 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1655 GNUNET_TIME_UNIT_FOREVER_REL,
1656 &transmit_to_client_callback,
1658 GNUNET_assert (client->th != NULL);
1665 * Convert an address to a string.
1667 * @param plugin name of the plugin responsible for the address
1668 * @param addr binary address
1669 * @param addr_len number of bytes in addr
1670 * @return NULL on error, otherwise address string
1673 a2s (const char *plugin,
1677 struct TransportPlugin *p;
1681 p = find_transport (plugin);
1682 if ((p == NULL) || (addr_len == 0) || (addr == NULL))
1685 return p->api->address_to_string (NULL,
1695 * Iterator to free entries in the validation_map.
1697 * @param cls closure (unused)
1698 * @param key current key code
1699 * @param value value in the hash map (validation to abort)
1700 * @return GNUNET_YES (always)
1703 abort_validation (void *cls,
1704 const GNUNET_HashCode * key,
1707 struct ValidationEntry *va = value;
1709 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
1710 GNUNET_SCHEDULER_cancel (va->timeout_task);
1711 GNUNET_free (va->transport_name);
1712 if (va->chvc != NULL)
1714 va->chvc->ve_count--;
1715 if (va->chvc->ve_count == 0)
1717 GNUNET_CONTAINER_DLL_remove (chvc_head,
1720 GNUNET_free (va->chvc);
1730 * HELLO validation cleanup task (validation failed).
1732 * @param cls the 'struct ValidationEntry' that failed
1733 * @param tc scheduler context (unused)
1736 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1738 struct ValidationEntry *va = cls;
1739 struct GNUNET_PeerIdentity pid;
1741 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1742 GNUNET_STATISTICS_update (stats,
1743 gettext_noop ("# address validation timeouts"),
1746 GNUNET_CRYPTO_hash (&va->publicKey,
1748 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1750 GNUNET_break (GNUNET_OK ==
1751 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1754 abort_validation (NULL, NULL, va);
1760 * Send the specified message to the specified client. Since multiple
1761 * messages may be pending for the same client at a time, this code
1762 * makes sure that no message is lost.
1764 * @param client client to transmit the message to
1765 * @param msg the message to send
1766 * @param may_drop can this message be dropped if the
1767 * message queue for this client is getting far too large?
1770 transmit_to_client (struct TransportClient *client,
1771 const struct GNUNET_MessageHeader *msg, int may_drop)
1773 struct ClientMessageQueueEntry *q;
1776 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1778 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1780 ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1783 client->message_count,
1785 GNUNET_STATISTICS_update (stats,
1786 gettext_noop ("# messages dropped due to slow client"),
1791 msize = ntohs (msg->size);
1792 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1793 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1794 memcpy (&q[1], msg, msize);
1795 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1796 client->message_queue_tail,
1797 client->message_queue_tail,
1799 client->message_count++;
1800 if (client->th == NULL)
1802 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1804 GNUNET_TIME_UNIT_FOREVER_REL,
1805 &transmit_to_client_callback,
1807 GNUNET_assert (client->th != NULL);
1813 * Transmit a 'SEND_OK' notification to the given client for the
1816 * @param client who to notify
1817 * @param n neighbour to notify about, can be NULL (on failure)
1818 * @param target target of the transmission
1819 * @param result status code for the transmission request
1822 transmit_send_ok (struct TransportClient *client,
1823 struct NeighbourList *n,
1824 const struct GNUNET_PeerIdentity *target,
1827 struct SendOkMessage send_ok_msg;
1829 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1830 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1831 send_ok_msg.success = htonl (result);
1833 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1835 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1836 send_ok_msg.peer = *target;
1837 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1842 * Mark the given FAL entry as 'connected' (and hence preferred for
1843 * sending); also mark all others for the same peer as 'not connected'
1844 * (since only one can be preferred).
1846 * @param fal address to set to 'connected'
1849 mark_address_connected (struct ForeignAddressList *fal);
1853 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1854 * upon "completion" of a send request. This tells the API
1855 * that it is now legal to send another message to the given
1858 * @param cls closure, identifies the entry on the
1859 * message queue that was transmitted and the
1860 * client responsible for queuing the message
1861 * @param target the peer receiving the message
1862 * @param result GNUNET_OK on success, if the transmission
1863 * failed, we should not tell the client to transmit
1867 transmit_send_continuation (void *cls,
1868 const struct GNUNET_PeerIdentity *target,
1871 struct MessageQueue *mq = cls;
1872 struct NeighbourList *n;
1874 GNUNET_STATISTICS_update (stats,
1875 gettext_noop ("# bytes pending with plugins"),
1876 - (int64_t) mq->message_buf_size,
1878 if (result == GNUNET_OK)
1880 GNUNET_STATISTICS_update (stats,
1881 gettext_noop ("# bytes successfully transmitted by plugins"),
1882 mq->message_buf_size,
1887 GNUNET_STATISTICS_update (stats,
1888 gettext_noop ("# bytes with transmission failure by plugins"),
1889 mq->message_buf_size,
1892 if (mq->specific_address != NULL)
1894 if (result == GNUNET_OK)
1896 mq->specific_address->timeout =
1897 GNUNET_TIME_relative_to_absolute
1898 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1899 if (mq->specific_address->validated == GNUNET_YES)
1900 mark_address_connected (mq->specific_address);
1904 if (mq->specific_address->connected != GNUNET_NO)
1907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1909 a2s (mq->specific_address->ready_list->plugin->short_name,
1910 mq->specific_address->addr,
1911 mq->specific_address->addrlen));
1913 GNUNET_STATISTICS_update (stats,
1914 gettext_noop ("# connected addresses"),
1917 mq->specific_address->connected = GNUNET_NO;
1920 if (! mq->internal_msg)
1921 mq->specific_address->in_transmit = GNUNET_NO;
1923 n = find_neighbour(&mq->neighbour_id);
1924 if (mq->client != NULL)
1925 transmit_send_ok (mq->client, n, target, result);
1928 GNUNET_CONTAINER_DLL_remove (n->cont_head,
1934 try_transmission_to_peer (n);
1939 * We should re-try transmitting to the given peer,
1940 * hopefully we've learned something in the meantime.
1943 retry_transmission_task (void *cls,
1944 const struct GNUNET_SCHEDULER_TaskContext *tc)
1946 struct NeighbourList *n = cls;
1948 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1949 try_transmission_to_peer (n);
1954 * Check the ready list for the given neighbour and if a plugin is
1955 * ready for transmission (and if we have a message), do so!
1957 * @param neighbour target peer for which to transmit
1960 try_transmission_to_peer (struct NeighbourList *n)
1962 struct ReadyList *rl;
1963 struct MessageQueue *mq;
1964 struct GNUNET_TIME_Relative timeout;
1968 if (n->messages_head == NULL)
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "Transmission queue for `%4s' is empty\n",
1973 GNUNET_i2s (&n->id));
1975 return; /* nothing to do */
1978 mq = n->messages_head;
1979 force_address = GNUNET_YES;
1980 if (mq->specific_address == NULL)
1983 mq->specific_address = ats_get_preferred_address(n);
1984 GNUNET_STATISTICS_update (stats,
1985 gettext_noop ("# transport selected peer address freely"),
1988 force_address = GNUNET_NO;
1990 if (mq->specific_address == NULL)
1992 GNUNET_STATISTICS_update (stats,
1993 gettext_noop ("# transport failed to selected peer address"),
1996 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1997 if (timeout.rel_value == 0)
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "No destination address available to transmit message of size %u to peer `%4s'\n",
2002 mq->message_buf_size,
2003 GNUNET_i2s (&mq->neighbour_id));
2005 GNUNET_STATISTICS_update (stats,
2006 gettext_noop ("# bytes in message queue for other peers"),
2007 - (int64_t) mq->message_buf_size,
2009 GNUNET_STATISTICS_update (stats,
2010 gettext_noop ("# bytes discarded (no destination address available)"),
2011 mq->message_buf_size,
2013 if (mq->client != NULL)
2014 transmit_send_ok (mq->client, n, &n->id, GNUNET_NO);
2015 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2019 return; /* nobody ready */
2021 GNUNET_STATISTICS_update (stats,
2022 gettext_noop ("# message delivery deferred (no address)"),
2025 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2026 GNUNET_SCHEDULER_cancel (n->retry_task);
2027 n->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
2028 &retry_transmission_task,
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
2033 mq->message_buf_size,
2034 GNUNET_i2s (&mq->neighbour_id),
2037 /* FIXME: might want to trigger peerinfo lookup here
2038 (unless that's already pending...) */
2041 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2044 if (mq->specific_address->connected == GNUNET_NO)
2045 mq->specific_address->connect_attempts++;
2046 rl = mq->specific_address->ready_list;
2047 mq->plugin = rl->plugin;
2048 if (!mq->internal_msg)
2049 mq->specific_address->in_transmit = GNUNET_YES;
2051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2052 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
2053 mq->message_buf_size,
2054 GNUNET_i2s (&n->id),
2055 (mq->specific_address->addr != NULL)
2056 ? a2s (mq->plugin->short_name,
2057 mq->specific_address->addr,
2058 mq->specific_address->addrlen)
2060 rl->plugin->short_name);
2062 GNUNET_STATISTICS_update (stats,
2063 gettext_noop ("# bytes in message queue for other peers"),
2064 - (int64_t) mq->message_buf_size,
2066 GNUNET_STATISTICS_update (stats,
2067 gettext_noop ("# bytes pending with plugins"),
2068 mq->message_buf_size,
2071 GNUNET_CONTAINER_DLL_insert (n->cont_head,
2075 ret = rl->plugin->api->send (rl->plugin->api->cls,
2078 mq->message_buf_size,
2080 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2081 mq->specific_address->session,
2082 mq->specific_address->addr,
2083 mq->specific_address->addrlen,
2085 &transmit_send_continuation, mq);
2088 /* failure, but 'send' would not call continuation in this case,
2089 so we need to do it here! */
2090 transmit_send_continuation (mq,
2098 * Send the specified message to the specified peer.
2100 * @param client source of the transmission request (can be NULL)
2101 * @param peer_address ForeignAddressList where we should send this message
2102 * @param priority how important is the message
2103 * @param timeout how long do we have to transmit?
2104 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
2105 * @param message_buf_size total size of all messages in message_buf
2106 * @param is_internal is this an internal message; these are pre-pended and
2107 * also do not count for plugins being "ready" to transmit
2108 * @param neighbour handle to the neighbour for transmission
2111 transmit_to_peer (struct TransportClient *client,
2112 struct ForeignAddressList *peer_address,
2113 unsigned int priority,
2114 struct GNUNET_TIME_Relative timeout,
2115 const char *message_buf,
2116 size_t message_buf_size,
2117 int is_internal, struct NeighbourList *neighbour)
2119 struct MessageQueue *mq;
2124 /* check for duplicate submission */
2125 mq = neighbour->messages_head;
2128 if (mq->client == client)
2130 /* client transmitted to same peer twice
2131 before getting SEND_OK! */
2139 GNUNET_STATISTICS_update (stats,
2140 gettext_noop ("# bytes in message queue for other peers"),
2143 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
2144 mq->specific_address = peer_address;
2145 mq->client = client;
2146 /* FIXME: this memcpy can be up to 7% of our total runtime! */
2147 memcpy (&mq[1], message_buf, message_buf_size);
2148 mq->message_buf = (const char*) &mq[1];
2149 mq->message_buf_size = message_buf_size;
2150 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2151 mq->internal_msg = is_internal;
2152 mq->priority = priority;
2153 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2155 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
2156 neighbour->messages_tail,
2159 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
2160 neighbour->messages_tail,
2161 neighbour->messages_tail,
2163 try_transmission_to_peer (neighbour);
2168 * Send a plain PING (without address or our HELLO) to the given
2169 * foreign address to try to establish a connection (and validate
2170 * that the other peer is really who he claimed he is).
2172 * @param n neighbour to PING
2175 transmit_plain_ping (struct NeighbourList *n)
2177 struct ValidationEntry *ve;
2178 struct TransportPingMessage ping;
2179 struct ReadyList *rl;
2180 struct TransportPlugin *plugin;
2181 struct ForeignAddressList *fal;
2183 if (! n->public_key_valid)
2185 /* This should not happen since the other peer
2186 should send us a HELLO prior to sending his
2188 GNUNET_break_op (0);
2189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190 "Could not transmit plain PING to `%s': public key not known\n",
2191 GNUNET_i2s (&n->id));
2194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2195 "Looking for addresses to transmit plain PING to `%s'\n",
2196 GNUNET_i2s (&n->id));
2197 for (rl = n->plugins; rl != NULL; rl = rl->next)
2199 plugin = rl->plugin;
2200 for (fal = rl->addresses; fal != NULL; fal = fal->next)
2202 if (! fal->connected)
2204 ve = GNUNET_malloc (sizeof (struct ValidationEntry));
2205 ve->transport_name = GNUNET_strdup (plugin->short_name);
2206 ve->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
2208 ve->send_time = GNUNET_TIME_absolute_get();
2209 ve->session = fal->session;
2210 memcpy(&ve->publicKey,
2212 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2213 ve->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
2214 &timeout_hello_validation,
2216 GNUNET_CONTAINER_multihashmap_put (validation_map,
2219 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2220 ping.header.size = htons(sizeof(struct TransportPingMessage));
2221 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2222 ping.challenge = htonl(ve->challenge);
2223 memcpy(&ping.target, &n->id, sizeof(struct GNUNET_PeerIdentity));
2224 GNUNET_STATISTICS_update (stats,
2225 gettext_noop ("# PING without HELLO messages sent"),
2228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2229 "Transmitting plain PING to `%s'\n",
2230 GNUNET_i2s (&n->id));
2231 transmit_to_peer (NULL,
2233 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2234 HELLO_VERIFICATION_TIMEOUT,
2235 (const char*) &ping, sizeof (ping),
2243 * Mark the given FAL entry as 'connected' (and hence preferred for
2244 * sending); also mark all others for the same peer as 'not connected'
2245 * (since only one can be preferred).
2247 * @param fal address to set to 'connected'
2250 mark_address_connected (struct ForeignAddressList *fal)
2252 struct ForeignAddressList *pos;
2255 GNUNET_assert (GNUNET_YES == fal->validated);
2256 if (fal->connected == GNUNET_YES)
2257 return; /* nothing to do */
2259 pos = fal->ready_list->addresses;
2262 if (GNUNET_YES == pos->connected)
2265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2266 "Marking address `%s' as no longer connected (due to connect on other address)\n",
2267 a2s (pos->ready_list->plugin->short_name,
2271 GNUNET_break (cnt == GNUNET_YES);
2273 pos->connected = GNUNET_NO;
2274 GNUNET_STATISTICS_update (stats,
2275 gettext_noop ("# connected addresses"),
2281 fal->connected = GNUNET_YES;
2282 if (GNUNET_YES == cnt)
2284 GNUNET_STATISTICS_update (stats,
2285 gettext_noop ("# connected addresses"),
2293 * Find an address in any of the available transports for
2294 * the given neighbour that would be good for message
2295 * transmission. This is essentially the transport selection
2298 * @param neighbour for whom to select an address
2299 * @return selected address, NULL if we have none
2301 struct ForeignAddressList *
2302 find_ready_address(struct NeighbourList *neighbour)
2304 struct ReadyList *head = neighbour->plugins;
2305 struct ForeignAddressList *addresses;
2306 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
2307 struct ForeignAddressList *best_address;
2309 /* Hack to prefer unix domain sockets */
2310 struct ForeignAddressList *unix_address = NULL;
2312 best_address = NULL;
2313 while (head != NULL)
2315 addresses = head->addresses;
2316 while (addresses != NULL)
2318 if ( (addresses->timeout.abs_value < now.abs_value) &&
2319 (addresses->connected == GNUNET_YES) )
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "Marking long-time inactive connection to `%4s' as down.\n",
2324 GNUNET_i2s (&neighbour->id));
2326 GNUNET_STATISTICS_update (stats,
2327 gettext_noop ("# connected addresses"),
2330 addresses->connected = GNUNET_NO;
2332 addresses = addresses->next;
2335 addresses = head->addresses;
2336 while (addresses != NULL)
2339 if (addresses->addr != NULL)
2340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2341 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
2342 a2s (head->plugin->short_name,
2344 addresses->addrlen),
2345 GNUNET_i2s (&neighbour->id),
2346 addresses->connected,
2347 addresses->in_transmit,
2348 addresses->validated,
2349 addresses->connect_attempts,
2350 (unsigned long long) addresses->timeout.abs_value,
2351 (unsigned int) addresses->distance);
2353 if (0==strcmp(head->plugin->short_name,"unix"))
2355 if ( (unix_address == NULL) ||
2356 ( (unix_address != NULL) &&
2357 (addresses->latency.rel_value < unix_address->latency.rel_value) ) )
2358 unix_address = addresses;
2360 if ( ( (best_address == NULL) ||
2361 (addresses->connected == GNUNET_YES) ||
2362 (best_address->connected == GNUNET_NO) ) &&
2363 (addresses->in_transmit == GNUNET_NO) &&
2364 ( (best_address == NULL) ||
2365 (addresses->latency.rel_value < best_address->latency.rel_value)) )
2366 best_address = addresses;
2367 /* FIXME: also give lower-latency addresses that are not
2368 connected a chance some times... */
2369 addresses = addresses->next;
2371 if (unix_address != NULL)
2375 if (unix_address != NULL)
2377 best_address = unix_address;
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "Found UNIX address, forced this address\n");
2383 if (best_address != NULL)
2386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387 "Best address found (`%s') has latency of %llu ms.\n",
2388 (best_address->addrlen > 0)
2389 ? a2s (best_address->ready_list->plugin->short_name,
2391 best_address->addrlen)
2393 best_address->latency.rel_value);
2398 GNUNET_STATISTICS_update (stats,
2399 gettext_noop ("# transmission attempts failed (no address)"),
2404 return best_address;
2412 struct GeneratorContext
2414 struct TransportPlugin *plug_pos;
2415 struct OwnAddressList *addr_pos;
2416 struct GNUNET_TIME_Absolute expiration;
2424 address_generator (void *cls, size_t max, void *buf)
2426 struct GeneratorContext *gc = cls;
2429 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
2431 gc->plug_pos = gc->plug_pos->next;
2432 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
2434 if (NULL == gc->plug_pos)
2439 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
2442 gc->addr_pos->addrlen, buf, max);
2443 gc->addr_pos = gc->addr_pos->next;
2449 * Construct our HELLO message from all of the addresses of
2450 * all of the transports.
2455 struct GNUNET_HELLO_Message *hello;
2456 struct TransportClient *cpos;
2457 struct NeighbourList *npos;
2458 struct GeneratorContext gc;
2460 gc.plug_pos = plugins;
2461 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
2462 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2463 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2466 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
2468 GNUNET_STATISTICS_update (stats,
2469 gettext_noop ("# refreshed my HELLO"),
2473 while (cpos != NULL)
2475 transmit_to_client (cpos,
2476 (const struct GNUNET_MessageHeader *) hello,
2481 GNUNET_free_non_null (our_hello);
2483 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
2484 for (npos = neighbours; npos != NULL; npos = npos->next)
2486 if (! npos->received_pong)
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2490 "Transmitting updated `%s' to neighbour `%4s'\n",
2491 "HELLO", GNUNET_i2s (&npos->id));
2493 GNUNET_STATISTICS_update (stats,
2494 gettext_noop ("# transmitted my HELLO to other peers"),
2497 transmit_to_peer (NULL, NULL, 0,
2498 HELLO_ADDRESS_EXPIRATION,
2499 (const char *) our_hello,
2500 GNUNET_HELLO_size(our_hello),
2507 * Iterator over hash map entries that NULLs the session of validation
2508 * entries that match the given session.
2510 * @param cls closure (the 'struct Session*' to match against)
2511 * @param key current key code (peer ID, not used)
2512 * @param value value in the hash map ('struct ValidationEntry*')
2513 * @return GNUNET_YES (we should continue to iterate)
2516 remove_session_validations (void *cls,
2517 const GNUNET_HashCode * key,
2520 struct Session *session = cls;
2521 struct ValidationEntry *ve = value;
2523 if (session == ve->session)
2530 * We've been disconnected from the other peer (for some
2531 * connection-oriented transport). Either quickly
2532 * re-establish the connection or signal the disconnect
2535 * Only signal CORE level disconnect if ALL addresses
2536 * for the peer are exhausted.
2538 * @param p overall plugin context
2539 * @param nl neighbour that was disconnected
2542 try_fast_reconnect (struct TransportPlugin *p,
2543 struct NeighbourList *nl)
2545 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2546 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2547 "try_fast_reconnect not implemented!\n");
2548 /* Note: the idea here is to hide problems with transports (or
2549 switching between plugins) from the core to eliminate the need to
2550 re-negotiate session keys and the like; OTOH, we should tell core
2551 quickly (much faster than timeout) `if a connection was lost and
2552 could not be re-established (i.e. other peer went down or is
2553 unable / refuses to communicate);
2555 So we should consider:
2556 1) ideally: our own willingness / need to connect
2557 2) prior failures to connect to this peer (by plugin)
2558 3) ideally: reasons why other peer terminated (as far as knowable)
2560 Most importantly, it must be POSSIBLE for another peer to terminate
2561 a connection for a while (without us instantly re-establishing it).
2562 Similarly, if another peer is gone we should quickly notify CORE.
2563 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2564 on the other end), we should reconnect in such a way that BOTH CORE
2565 services never even notice.
2566 Furthermore, the same mechanism (or small variation) could be used
2567 to switch to a better-performing plugin (ATS).
2569 Finally, this needs to be tested throughly... */
2572 * GNUNET_NO in the call below makes transport disconnect the peer,
2573 * even if only a single address (out of say, six) went away. This
2574 * function must be careful to ONLY disconnect if the peer is gone,
2575 * not just a specific address.
2577 * More specifically, half the places it was used had it WRONG.
2580 /* No reconnect, signal disconnect instead! */
2582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2584 "try_fast_reconnect");
2586 GNUNET_STATISTICS_update (stats,
2587 gettext_noop ("# disconnects due to try_fast_reconnect"),
2591 disconnect_neighbour (nl, GNUNET_YES);
2597 * Function that will be called whenever the plugin internally
2598 * cleans up a session pointer and hence the service needs to
2599 * discard all of those sessions as well. Plugins that do not
2600 * use sessions can simply omit calling this function and always
2601 * use NULL wherever a session pointer is needed.
2603 * @param cls closure
2604 * @param peer which peer was the session for
2605 * @param session which session is being destoyed
2608 plugin_env_session_end (void *cls,
2609 const struct GNUNET_PeerIdentity *peer,
2610 struct Session *session)
2612 struct TransportPlugin *p = cls;
2613 struct NeighbourList *nl;
2614 struct ReadyList *rl;
2615 struct ForeignAddressList *pos;
2616 struct ForeignAddressList *prev;
2619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2620 "Session ended with peer `%4s', %s\n",
2622 "plugin_env_session_end");
2624 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2625 &remove_session_validations,
2627 nl = find_neighbour (peer);
2631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632 "No neighbour record found for peer `%4s'\n",
2635 return; /* was never marked as connected */
2640 if (rl->plugin == p)
2647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648 "Plugin was associated with peer `%4s'\n",
2651 GNUNET_STATISTICS_update (stats,
2652 gettext_noop ("# disconnects due to session end"),
2655 disconnect_neighbour (nl, GNUNET_YES);
2659 pos = rl->addresses;
2660 while ( (pos != NULL) &&
2661 (pos->session != session) )
2669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2670 "Session was never marked as ready for peer `%4s'\n",
2673 //FIXME: This conflicts with inbound tcp connections and tcp nat ... debugging in progress
2674 GNUNET_STATISTICS_update (stats,
2675 gettext_noop ("# disconnects due to unready session"),
2678 disconnect_neighbour (nl, GNUNET_YES);
2679 return; /* was never marked as connected */
2681 pos->session = NULL;
2682 pos->connected = GNUNET_NO;
2683 if (pos->addrlen != 0)
2685 if (nl->received_pong != GNUNET_NO)
2687 GNUNET_STATISTICS_update (stats,
2688 gettext_noop ("# try_fast_reconnect thanks to plugin_env_session_end"),
2691 if (GNUNET_YES == pos->connected)
2692 try_fast_reconnect (p, nl);
2696 GNUNET_STATISTICS_update (stats,
2697 gettext_noop ("# disconnects due to missing pong"),
2700 if (GNUNET_YES == pos->connected)
2701 disconnect_neighbour (nl, GNUNET_YES);
2705 /* was inbound connection, free 'pos' */
2707 rl->addresses = pos->next;
2709 prev->next = pos->next;
2710 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2712 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2713 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2715 GNUNET_free_non_null(pos->ressources);
2716 GNUNET_free_non_null(pos->quality);
2717 if (GNUNET_YES != pos->connected)
2719 /* nothing else to do, connection was never up... */
2724 ats->stat.recreate_problem = GNUNET_YES;
2725 if (nl->received_pong == GNUNET_NO)
2727 GNUNET_STATISTICS_update (stats,
2728 gettext_noop ("# disconnects due to NO pong"),
2731 disconnect_neighbour (nl, GNUNET_YES);
2732 return; /* nothing to do, never connected... */
2734 /* check if we have any validated addresses left */
2735 pos = rl->addresses;
2738 if (GNUNET_YES == pos->validated)
2740 GNUNET_STATISTICS_update (stats,
2741 gettext_noop ("# try_fast_reconnect thanks to validated_address"),
2744 try_fast_reconnect (p, nl);
2749 /* no valid addresses left, signal disconnect! */
2752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2753 "Disconnecting peer `%4s', %s\n",
2755 "plugin_env_session_end");
2757 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2758 * it means there aren't any left for this PLUGIN/PEER combination! So
2759 * calling disconnect_neighbour here with GNUNET_NO forces disconnect
2760 * when it isn't necessary. Using GNUNET_YES at least checks to see
2761 * if there are any addresses that work first, so as not to overdo it.
2764 GNUNET_STATISTICS_update (stats,
2765 gettext_noop ("# disconnects due to plugin_env_session_end"),
2768 disconnect_neighbour (nl, GNUNET_YES);
2773 * Function that must be called by each plugin to notify the
2774 * transport service about the addresses under which the transport
2775 * provided by the plugin can be reached.
2777 * @param cls closure
2778 * @param add_remove GNUNET_YES to add, GNUNET_NO to remove the address
2779 * @param addr one of the addresses of the host, NULL for the last address
2780 * the specific address format depends on the transport
2781 * @param addrlen length of the address
2784 plugin_env_notify_address (void *cls,
2789 struct TransportPlugin *p = cls;
2790 struct OwnAddressList *al;
2791 struct OwnAddressList *prev;
2793 GNUNET_assert (p->api != NULL);
2795 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2796 (add_remove == GNUNET_YES)
2797 ? "Adding `%s':%s to the set of our addresses\n"
2798 : "Removing `%s':%s from the set of our addresses\n",
2803 GNUNET_assert (addr != NULL);
2804 if (GNUNET_NO == add_remove)
2810 if ( (addrlen == al->addrlen) &&
2811 (0 == memcmp (addr, &al[1], addrlen)) )
2814 p->addresses = al->next;
2816 prev->next = al->next;
2827 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2828 al->next = p->addresses;
2830 al->addrlen = addrlen;
2831 memcpy (&al[1], addr, addrlen);
2837 * Notify all of our clients about a peer connecting.
2840 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2841 struct GNUNET_TIME_Relative latency,
2844 struct ConnectInfoMessage * cim;
2845 struct TransportClient *cpos;
2849 if (0 == memcmp (peer,
2851 sizeof (struct GNUNET_PeerIdentity)))
2857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2858 "Notifying clients about connection with `%s'\n",
2861 GNUNET_STATISTICS_update (stats,
2862 gettext_noop ("# peers connected"),
2867 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2868 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2872 cim = GNUNET_malloc (size);
2873 cim->header.size = htons (size);
2874 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2875 cim->ats_count = htonl(2);
2876 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2877 (&(cim->ats))[0].value = htonl (distance);
2878 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2879 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2880 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2881 (&(cim->ats))[2].value = htonl (0);
2882 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2884 /* notify ats about connecting peer */
2885 if (shutdown_in_progress == GNUNET_NO)
2886 ats_notify_peer_connect (peer, &(cim->ats), 2);
2889 while (cpos != NULL)
2891 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2900 * Notify all of our clients about a peer disconnecting.
2903 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2905 struct DisconnectInfoMessage dim;
2906 struct TransportClient *cpos;
2908 if (0 == memcmp (peer,
2910 sizeof (struct GNUNET_PeerIdentity)))
2916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917 "Notifying clients about lost connection to `%s'\n",
2920 GNUNET_STATISTICS_update (stats,
2921 gettext_noop ("# peers connected"),
2924 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2925 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2926 dim.reserved = htonl (0);
2927 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2929 /* notify ats about connecting peer */
2930 if (shutdown_in_progress == GNUNET_NO)
2931 ats_notify_peer_disconnect (peer);
2934 while (cpos != NULL)
2936 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2943 * Find a ForeignAddressList entry for the given neighbour
2944 * that matches the given address and transport.
2946 * @param neighbour which peer we care about
2947 * @param tname name of the transport plugin
2948 * @param session session to look for, NULL for 'any'; otherwise
2949 * can be used for the service to "learn" this session ID
2951 * @param addr binary address
2952 * @param addrlen length of addr
2953 * @return NULL if no such entry exists
2955 static struct ForeignAddressList *
2956 find_peer_address(struct NeighbourList *neighbour,
2958 struct Session *session,
2962 struct ReadyList *head;
2963 struct ForeignAddressList *pos;
2965 head = neighbour->plugins;
2966 while (head != NULL)
2968 if (0 == strcmp (tname, head->plugin->short_name))
2974 pos = head->addresses;
2975 while ( (pos != NULL) &&
2976 ( (pos->addrlen != addrlen) ||
2977 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2979 if ( (session != NULL) &&
2980 (pos->session == session) )
2984 if ( (session != NULL) && (pos != NULL) )
2985 pos->session = session; /* learn it! */
2991 * Get the peer address struct for the given neighbour and
2992 * address. If it doesn't yet exist, create it.
2994 * @param neighbour which peer we care about
2995 * @param tname name of the transport plugin
2996 * @param session session of the plugin, or NULL for none
2997 * @param addr binary address
2998 * @param addrlen length of addr
2999 * @return NULL if we do not have a transport plugin for 'tname'
3001 static struct ForeignAddressList *
3002 add_peer_address (struct NeighbourList *neighbour,
3004 struct Session *session,
3008 struct ReadyList *head;
3009 struct ForeignAddressList *ret;
3012 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
3015 head = neighbour->plugins;
3017 while (head != NULL)
3019 if (0 == strcmp (tname, head->plugin->short_name))
3025 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
3026 ret->session = session;
3027 if ((addrlen > 0) && (addr != NULL))
3029 ret->addr = (const char*) &ret[1];
3030 memcpy (&ret[1], addr, addrlen);
3037 ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
3038 for (c=0; c<available_ressources; c++)
3040 struct ATS_ressource_entry *r = ret->ressources;
3042 r[c].atis_index = ressources[c].atis_index;
3043 if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
3045 r[c].c = ressources[c].c_unix;
3047 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
3049 r[c].c = ressources[c].c_udp;
3051 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
3053 r[c].c = ressources[c].c_tcp;
3055 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
3057 r[c].c = ressources[c].c_http;
3059 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
3061 r[c].c = ressources[c].c_https;
3063 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
3065 r[c].c = ressources[c].c_wlan;
3069 r[c].c = ressources[c].c_default;
3070 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3071 "Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!\n",
3072 GNUNET_i2s(&neighbour->peer),
3073 neighbour->plugins->plugin->short_name);
3077 ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
3078 ret->addrlen = addrlen;
3079 ret->expires = GNUNET_TIME_relative_to_absolute
3080 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3081 ret->latency = GNUNET_TIME_relative_get_forever();
3083 ret->timeout = GNUNET_TIME_relative_to_absolute
3084 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3085 ret->ready_list = head;
3086 ret->next = head->addresses;
3087 head->addresses = ret;
3093 * Closure for 'add_validated_address'.
3095 struct AddValidatedAddressContext
3098 * Entry that has been validated.
3100 const struct ValidationEntry *ve;
3103 * Flag set after we have added the address so
3104 * that we terminate the iteration next time.
3111 * Callback function used to fill a buffer of max bytes with a list of
3112 * addresses in the format used by HELLOs. Should use
3113 * "GNUNET_HELLO_add_address" as a helper function.
3115 * @param cls the 'struct AddValidatedAddressContext' with the validated address
3116 * @param max maximum number of bytes that can be written to buf
3117 * @param buf where to write the address information
3118 * @return number of bytes written, 0 to signal the
3119 * end of the iteration.
3122 add_validated_address (void *cls,
3123 size_t max, void *buf)
3125 struct AddValidatedAddressContext *avac = cls;
3126 const struct ValidationEntry *ve = avac->ve;
3128 if (GNUNET_YES == avac->done)
3130 avac->done = GNUNET_YES;
3131 return GNUNET_HELLO_add_address (ve->transport_name,
3132 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
3142 * Closure for 'check_address_exists'.
3144 struct CheckAddressExistsClosure
3147 * Address to check for.
3152 * Name of the transport.
3159 struct Session *session;
3162 * Set to GNUNET_YES if the address exists.
3175 * Iterator over hash map entries. Checks if the given
3176 * validation entry is for the same address as what is given
3179 * @param cls the 'struct CheckAddressExistsClosure*'
3180 * @param key current key code (ignored)
3181 * @param value value in the hash map ('struct ValidationEntry')
3182 * @return GNUNET_YES if we should continue to
3183 * iterate (mismatch), GNUNET_NO if not (entry matched)
3186 check_address_exists (void *cls,
3187 const GNUNET_HashCode * key,
3190 struct CheckAddressExistsClosure *caec = cls;
3191 struct ValidationEntry *ve = value;
3193 if ( (0 == strcmp (caec->tname,
3194 ve->transport_name)) &&
3195 (caec->addrlen == ve->addrlen) &&
3196 (0 == memcmp (caec->addr,
3200 caec->exists = GNUNET_YES;
3203 if ( (ve->session != NULL) &&
3204 (caec->session == ve->session) )
3206 caec->exists = GNUNET_YES;
3214 neighbour_timeout_task (void *cls,
3215 const struct GNUNET_SCHEDULER_TaskContext *tc)
3217 struct NeighbourList *n = cls;
3220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3221 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
3223 GNUNET_STATISTICS_update (stats,
3224 gettext_noop ("# disconnects due to timeout"),
3227 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3228 disconnect_neighbour (n, GNUNET_NO);
3233 * Schedule the job that will cause us to send a PING to the
3234 * foreign address to evaluate its validity and latency.
3236 * @param fal address to PING
3239 schedule_next_ping (struct ForeignAddressList *fal);
3243 * Add the given address to the list of foreign addresses
3244 * available for the given peer (check for duplicates).
3246 * @param cls the respective 'struct NeighbourList' to update
3247 * @param tname name of the transport
3248 * @param expiration expiration time
3249 * @param addr the address
3250 * @param addrlen length of the address
3251 * @return GNUNET_OK (always)
3254 add_to_foreign_address_list (void *cls,
3256 struct GNUNET_TIME_Absolute expiration,
3260 struct NeighbourList *n = cls;
3261 struct ForeignAddressList *fal;
3264 GNUNET_STATISTICS_update (stats,
3265 gettext_noop ("# valid peer addresses returned by PEERINFO"),
3269 fal = find_peer_address (n, tname, NULL, addr, addrlen);
3272 #if DEBUG_TRANSPORT_HELLO
3273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3274 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
3275 a2s (tname, addr, addrlen),
3277 GNUNET_i2s (&n->id),
3278 expiration.abs_value);
3280 fal = add_peer_address (n, tname, NULL, addr, addrlen);
3283 GNUNET_STATISTICS_update (stats,
3284 gettext_noop ("# previously validated addresses lacking transport"),
3290 fal->expires = GNUNET_TIME_absolute_max (expiration,
3292 schedule_next_ping (fal);
3298 fal->expires = GNUNET_TIME_absolute_max (expiration,
3304 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3305 "Failed to add new address for `%4s'\n",
3306 GNUNET_i2s (&n->id));
3310 if (fal->validated == GNUNET_NO)
3312 fal->validated = GNUNET_YES;
3313 GNUNET_STATISTICS_update (stats,
3314 gettext_noop ("# peer addresses considered valid"),
3318 if (try == GNUNET_YES)
3321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3322 "Have new addresses, will try to trigger transmissions.\n");
3324 try_transmission_to_peer (n);
3331 * Add addresses in validated HELLO "h" to the set of addresses
3332 * we have for this peer.
3334 * @param cls closure ('struct NeighbourList*')
3335 * @param peer id of the peer, NULL for last call
3336 * @param h hello message for the peer (can be NULL)
3337 * @param err_msg NULL if successful, otherwise contains error message
3340 add_hello_for_peer (void *cls,
3341 const struct GNUNET_PeerIdentity *peer,
3342 const struct GNUNET_HELLO_Message *h,
3343 const char *err_msg)
3345 struct NeighbourList *n = cls;
3347 if (err_msg != NULL)
3350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3351 _("Error in communication with PEERINFO service: %s\n"),
3358 GNUNET_STATISTICS_update (stats,
3359 gettext_noop ("# outstanding peerinfo iterate requests"),
3366 return; /* no HELLO available */
3368 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3369 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
3373 if (GNUNET_YES != n->public_key_valid)
3375 GNUNET_HELLO_get_key (h, &n->publicKey);
3376 n->public_key_valid = GNUNET_YES;
3378 GNUNET_HELLO_iterate_addresses (h,
3380 &add_to_foreign_address_list,
3386 * Create a fresh entry in our neighbour list for the given peer.
3387 * Will try to transmit our current HELLO to the new neighbour.
3388 * Do not call this function directly, use 'setup_peer_check_blacklist.
3390 * @param peer the peer for which we create the entry
3391 * @param do_hello should we schedule transmitting a HELLO
3392 * @return the new neighbour list entry
3394 static struct NeighbourList *
3395 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
3398 struct NeighbourList *n;
3399 struct TransportPlugin *tp;
3400 struct ReadyList *rl;
3402 GNUNET_assert (0 != memcmp (peer,
3404 sizeof (struct GNUNET_PeerIdentity)));
3406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3407 "Setting up state for neighbour `%4s'\n",
3410 GNUNET_STATISTICS_update (stats,
3411 gettext_noop ("# active neighbours"),
3414 n = GNUNET_malloc (sizeof (struct NeighbourList));
3415 n->next = neighbours;
3419 GNUNET_TIME_relative_to_absolute
3420 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3421 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
3422 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
3423 MAX_BANDWIDTH_CARRY_S);
3427 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
3429 rl = GNUNET_malloc (sizeof (struct ReadyList));
3431 rl->next = n->plugins;
3434 rl->addresses = NULL;
3438 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
3440 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3441 &neighbour_timeout_task, n);
3444 GNUNET_STATISTICS_update (stats,
3445 gettext_noop ("# peerinfo new neighbor iterate requests"),
3448 GNUNET_STATISTICS_update (stats,
3449 gettext_noop ("# outstanding peerinfo iterate requests"),
3452 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
3453 GNUNET_TIME_UNIT_FOREVER_REL,
3454 &add_hello_for_peer, n);
3456 GNUNET_STATISTICS_update (stats,
3457 gettext_noop ("# HELLO's sent to new neighbors"),
3460 if (NULL != our_hello)
3461 transmit_to_peer (NULL, NULL, 0,
3462 HELLO_ADDRESS_EXPIRATION,
3463 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
3471 * Function called after we have checked if communicating
3472 * with a given peer is acceptable.
3474 * @param cls closure
3475 * @param n NULL if communication is not acceptable
3477 typedef void (*SetupContinuation)(void *cls,
3478 struct NeighbourList *n);
3482 * Information kept for each client registered to perform
3488 * This is a linked list.
3490 struct Blacklisters *next;
3493 * This is a linked list.
3495 struct Blacklisters *prev;
3498 * Client responsible for this entry.
3500 struct GNUNET_SERVER_Client *client;
3503 * Blacklist check that we're currently performing.
3505 struct BlacklistCheck *bc;
3511 * Head of DLL of blacklisting clients.
3513 static struct Blacklisters *bl_head;
3516 * Tail of DLL of blacklisting clients.
3518 static struct Blacklisters *bl_tail;
3522 * Context we use when performing a blacklist check.
3524 struct BlacklistCheck
3528 * This is a linked list.
3530 struct BlacklistCheck *next;
3533 * This is a linked list.
3535 struct BlacklistCheck *prev;
3538 * Peer being checked.
3540 struct GNUNET_PeerIdentity peer;
3543 * Option for setup neighbour afterwards.
3548 * Continuation to call with the result.
3550 SetupContinuation cont;
3558 * Current transmission request handle for this client, or NULL if no
3559 * request is pending.
3561 struct GNUNET_CONNECTION_TransmitHandle *th;
3564 * Our current position in the blacklisters list.
3566 struct Blacklisters *bl_pos;
3569 * Current task performing the check.
3571 GNUNET_SCHEDULER_TaskIdentifier task;
3576 * Head of DLL of active blacklisting queries.
3578 static struct BlacklistCheck *bc_head;
3581 * Tail of DLL of active blacklisting queries.
3583 static struct BlacklistCheck *bc_tail;
3587 * Perform next action in the blacklist check.
3589 * @param cls the 'struct BlacklistCheck*'
3593 do_blacklist_check (void *cls,
3594 const struct GNUNET_SCHEDULER_TaskContext *tc);
3597 * Transmit blacklist query to the client.
3599 * @param cls the 'struct BlacklistCheck'
3600 * @param size number of bytes allowed
3601 * @param buf where to copy the message
3602 * @return number of bytes copied to buf
3605 transmit_blacklist_message (void *cls,
3609 struct BlacklistCheck *bc = cls;
3610 struct Blacklisters *bl;
3611 struct BlacklistMessage bm;
3616 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3617 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3619 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3620 "Failed to send blacklist test for peer `%s' to client\n",
3621 GNUNET_i2s (&bc->peer));
3625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3626 "Sending blacklist test for peer `%s' to client\n",
3627 GNUNET_i2s (&bc->peer));
3630 bm.header.size = htons (sizeof (struct BlacklistMessage));
3631 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3632 bm.is_allowed = htonl (0);
3634 memcpy (buf, &bm, sizeof (bm));
3635 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3641 * Perform next action in the blacklist check.
3643 * @param cls the 'struct BlacklistCheck*'
3647 do_blacklist_check (void *cls,
3648 const struct GNUNET_SCHEDULER_TaskContext *tc)
3650 struct BlacklistCheck *bc = cls;
3651 struct Blacklisters *bl;
3653 bc->task = GNUNET_SCHEDULER_NO_TASK;
3658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3659 "No blacklist clients active, will now setup neighbour record for peer `%s'\n",
3660 GNUNET_i2s (&bc->peer));
3662 bc->cont (bc->cont_cls,
3663 setup_new_neighbour (&bc->peer, bc->do_hello));
3670 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3671 sizeof (struct BlacklistMessage),
3672 GNUNET_TIME_UNIT_FOREVER_REL,
3673 &transmit_blacklist_message,
3680 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3681 * does not yet exist, check the blacklist. If the blacklist says creating
3682 * one is acceptable, create one and call the continuation; otherwise
3683 * call the continuation with NULL.
3685 * @param peer peer to setup or look up a struct NeighbourList for
3686 * @param do_hello should we also schedule sending our HELLO to the peer
3687 * if this is a new record
3688 * @param cont function to call with the 'struct NeigbhbourList*'
3689 * @param cont_cls closure for cont
3692 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3694 SetupContinuation cont,
3697 struct NeighbourList *n;
3698 struct BlacklistCheck *bc;
3700 n = find_neighbour(peer);
3704 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3705 "Neighbour record exists for peer `%s'\n",
3712 if (bl_head == NULL)
3715 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3717 setup_new_neighbour(peer, do_hello);
3720 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3721 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3723 bc->do_hello = do_hello;
3725 bc->cont_cls = cont_cls;
3726 bc->bl_pos = bl_head;
3727 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3733 * Function called with the result of querying a new blacklister about
3734 * it being allowed (or not) to continue to talk to an existing neighbour.
3736 * @param cls the original 'struct NeighbourList'
3737 * @param n NULL if we need to disconnect
3740 confirm_or_drop_neighbour (void *cls,
3741 struct NeighbourList *n)
3743 struct NeighbourList * orig = cls;
3748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3749 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3750 "confirm_or_drop_neighboUr");
3752 GNUNET_STATISTICS_update (stats,
3753 gettext_noop ("# disconnects due to blacklist"),
3756 disconnect_neighbour (orig, GNUNET_NO);
3762 * Handle a request to start a blacklist.
3764 * @param cls closure (always NULL)
3765 * @param client identification of the client
3766 * @param message the actual message
3769 handle_blacklist_init (void *cls,
3770 struct GNUNET_SERVER_Client *client,
3771 const struct GNUNET_MessageHeader *message)
3773 struct Blacklisters *bl;
3774 struct BlacklistCheck *bc;
3775 struct NeighbourList *n;
3780 if (bl->client == client)
3783 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3788 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3789 bl->client = client;
3790 GNUNET_SERVER_client_keep (client);
3791 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3792 /* confirm that all existing connections are OK! */
3796 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3797 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3799 bc->do_hello = GNUNET_NO;
3800 bc->cont = &confirm_or_drop_neighbour;
3803 if (n == neighbours) /* all would wait for the same client, no need to
3804 create more than just the first task right now */
3805 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3813 * Handle a request to blacklist a peer.
3815 * @param cls closure (always NULL)
3816 * @param client identification of the client
3817 * @param message the actual message
3820 handle_blacklist_reply (void *cls,
3821 struct GNUNET_SERVER_Client *client,
3822 const struct GNUNET_MessageHeader *message)
3824 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3825 struct Blacklisters *bl;
3826 struct BlacklistCheck *bc;
3829 while ( (bl != NULL) &&
3830 (bl->client != client) )
3835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3836 "Blacklist client disconnected\n");
3838 /* FIXME: other error handling here!? */
3839 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3844 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848 "Blacklist check failed, peer not allowed\n");
3850 bc->cont (bc->cont_cls, NULL);
3851 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3858 "Blacklist check succeeded, continuing with checks\n");
3860 bc->bl_pos = bc->bl_pos->next;
3861 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3864 /* check if any other bc's are waiting for this blacklister */
3868 if ( (bc->bl_pos == bl) &&
3869 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3870 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3878 * Send periodic PING messages to a given foreign address.
3880 * @param cls our 'struct PeriodicValidationContext*'
3881 * @param tc task context
3884 send_periodic_ping (void *cls,
3885 const struct GNUNET_SCHEDULER_TaskContext *tc)
3887 struct ForeignAddressList *peer_address = cls;
3888 struct TransportPlugin *tp;
3889 struct ValidationEntry *va;
3890 struct NeighbourList *neighbour;
3891 struct TransportPingMessage ping;
3892 struct CheckAddressExistsClosure caec;
3894 uint16_t hello_size;
3898 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3899 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3901 tp = peer_address->ready_list->plugin;
3902 neighbour = peer_address->ready_list->neighbour;
3903 if (GNUNET_YES != neighbour->public_key_valid)
3905 /* no public key yet, try again later */
3906 schedule_next_ping (peer_address);
3909 caec.addr = peer_address->addr;
3910 caec.addrlen = peer_address->addrlen;
3911 caec.tname = tp->short_name;
3912 caec.session = peer_address->session;
3913 caec.exists = GNUNET_NO;
3914 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3915 &check_address_exists,
3917 if (caec.exists == GNUNET_YES)
3919 /* During validation attempts we will likely trigger the other
3920 peer trying to validate our address which in turn will cause
3921 it to send us its HELLO, so we expect to hit this case rather
3922 frequently. Only print something if we are very verbose. */
3923 #if DEBUG_TRANSPORT > 1
3924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3925 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3926 (peer_address->addr != NULL)
3927 ? a2s (tp->short_name,
3929 peer_address->addrlen)
3932 GNUNET_i2s (&neighbour->id));
3934 schedule_next_ping (peer_address);
3937 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3938 va->transport_name = GNUNET_strdup (tp->short_name);
3939 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3941 va->send_time = GNUNET_TIME_absolute_get();
3942 va->session = peer_address->session;
3943 if (peer_address->addr != NULL)
3945 va->addr = (const void*) &va[1];
3946 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3947 va->addrlen = peer_address->addrlen;
3949 memcpy(&va->publicKey,
3950 &neighbour->publicKey,
3951 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3953 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3954 &timeout_hello_validation,
3956 GNUNET_CONTAINER_multihashmap_put (validation_map,
3957 &neighbour->id.hashPubKey,
3959 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3961 if (peer_address->validated != GNUNET_YES)
3962 hello_size = GNUNET_HELLO_size(our_hello);
3966 tsize = sizeof(struct TransportPingMessage) + hello_size;
3968 if (peer_address->addr != NULL)
3970 slen = strlen (tp->short_name) + 1;
3971 tsize += slen + peer_address->addrlen;
3975 slen = 0; /* make gcc happy */
3977 message_buf = GNUNET_malloc(tsize);
3978 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3979 ping.challenge = htonl(va->challenge);
3980 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3981 if (peer_address->validated != GNUNET_YES)
3983 memcpy(message_buf, our_hello, hello_size);
3986 if (peer_address->addr != NULL)
3988 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3989 peer_address->addrlen +
3991 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3994 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3996 peer_address->addrlen);
4000 ping.header.size = htons(sizeof(struct TransportPingMessage));
4003 memcpy(&message_buf[hello_size],
4005 sizeof(struct TransportPingMessage));
4007 #if DEBUG_TRANSPORT_REVALIDATION
4008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4009 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
4010 (peer_address->addr != NULL)
4011 ? a2s (peer_address->plugin->short_name,
4013 peer_address->addrlen)
4016 GNUNET_i2s (&neighbour->id),
4017 "HELLO", hello_size,
4020 if (peer_address->validated != GNUNET_YES)
4021 GNUNET_STATISTICS_update (stats,
4022 gettext_noop ("# PING with HELLO messages sent"),
4026 GNUNET_STATISTICS_update (stats,
4027 gettext_noop ("# PING without HELLO messages sent"),
4030 GNUNET_STATISTICS_update (stats,
4031 gettext_noop ("# PING messages sent for re-validation"),
4034 transmit_to_peer (NULL, peer_address,
4035 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4036 HELLO_VERIFICATION_TIMEOUT,
4038 GNUNET_YES, neighbour);
4039 GNUNET_free(message_buf);
4040 schedule_next_ping (peer_address);
4045 * Schedule the job that will cause us to send a PING to the
4046 * foreign address to evaluate its validity and latency.
4048 * @param fal address to PING
4051 schedule_next_ping (struct ForeignAddressList *fal)
4053 struct GNUNET_TIME_Relative delay;
4055 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
4057 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
4058 delay.rel_value /= 2; /* do before expiration */
4059 delay = GNUNET_TIME_relative_min (delay,
4060 LATENCY_EVALUATION_MAX_DELAY);
4061 if (GNUNET_YES != fal->estimated)
4063 delay = GNUNET_TIME_UNIT_ZERO;
4064 fal->estimated = GNUNET_YES;
4066 if (GNUNET_YES == fal->connected)
4068 delay = GNUNET_TIME_relative_min (delay,
4069 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
4071 /* FIXME: also adjust delay based on how close the last
4072 observed latency is to the latency of the best alternative */
4073 /* bound how fast we can go */
4074 delay = GNUNET_TIME_relative_max (delay,
4075 GNUNET_TIME_UNIT_SECONDS);
4076 /* randomize a bit (to avoid doing all at the same time) */
4077 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
4078 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
4079 &send_periodic_ping,
4087 * Function that will be called if we receive some payload
4088 * from another peer.
4090 * @param message the payload
4091 * @param n peer who claimed to be the sender
4094 handle_payload_message (const struct GNUNET_MessageHeader *message,
4095 struct NeighbourList *n)
4097 struct InboundMessage *im;
4098 struct TransportClient *cpos;
4101 msize = ntohs (message->size);
4102 if (n->received_pong == GNUNET_NO)
4105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4106 "Received message of type %u and size %u from `%4s', but no pong yet!\n",
4107 ntohs (message->type),
4108 ntohs (message->size),
4109 GNUNET_i2s (&n->id));
4111 GNUNET_free_non_null (n->pre_connect_message_buffer);
4112 n->pre_connect_message_buffer = GNUNET_malloc (msize);
4113 memcpy (n->pre_connect_message_buffer, message, msize);
4118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4119 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4120 ntohs (message->type),
4121 ntohs (message->size),
4122 GNUNET_i2s (&n->id));
4124 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4127 n->quota_violation_count++;
4129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4130 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
4131 n->in_tracker.available_bytes_per_s__,
4132 n->quota_violation_count);
4134 /* Discount 32k per violation */
4135 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4140 if (n->quota_violation_count > 0)
4142 /* try to add 32k back */
4143 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4145 n->quota_violation_count--;
4148 GNUNET_STATISTICS_update (stats,
4149 gettext_noop ("# payload received from other peers"),
4152 /* transmit message to all clients */
4153 uint32_t ats_count = 2;
4154 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
4155 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4158 im = GNUNET_malloc (size);
4159 im->header.size = htons (size);
4160 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
4162 im->ats_count = htonl(ats_count);
4163 /* Setting ATS data */
4164 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4165 (&(im->ats))[0].value = htonl (n->distance);
4166 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4167 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
4168 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4169 (&(im->ats))[ats_count].value = htonl (0);
4171 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
4173 while (cpos != NULL)
4175 transmit_to_client (cpos, &im->header, GNUNET_YES);
4183 * Iterator over hash map entries. Checks if the given validation
4184 * entry is for the same challenge as what is given in the PONG.
4186 * @param cls the 'struct TransportPongMessage*'
4187 * @param key peer identity
4188 * @param value value in the hash map ('struct ValidationEntry')
4189 * @return GNUNET_YES if we should continue to
4190 * iterate (mismatch), GNUNET_NO if not (entry matched)
4193 check_pending_validation (void *cls,
4194 const GNUNET_HashCode * key,
4197 const struct TransportPongMessage *pong = cls;
4198 struct ValidationEntry *ve = value;
4199 struct AddValidatedAddressContext avac;
4200 unsigned int challenge = ntohl(pong->challenge);
4201 struct GNUNET_HELLO_Message *hello;
4202 struct GNUNET_PeerIdentity target;
4203 struct NeighbourList *n;
4204 struct ForeignAddressList *fal;
4205 struct OwnAddressList *oal;
4206 struct TransportPlugin *tp;
4207 struct GNUNET_MessageHeader *prem;
4213 ps = ntohs (pong->header.size);
4214 if (ps < sizeof (struct TransportPongMessage))
4216 GNUNET_break_op (0);
4219 addr = (const char*) &pong[1];
4220 slen = strlen (ve->transport_name) + 1;
4221 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
4222 (ve->challenge != challenge) ||
4223 (addr[slen-1] != '\0') ||
4224 (0 != strcmp (addr, ve->transport_name)) ||
4225 (ntohl (pong->purpose.size)
4226 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4228 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4229 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
4234 alen = ps - sizeof (struct TransportPongMessage) - slen;
4235 switch (ntohl (pong->purpose.purpose))
4237 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
4238 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
4239 (0 != memcmp (&addr[slen],
4243 return GNUNET_YES; /* different entry, keep trying! */
4245 if (0 != memcmp (&pong->pid,
4247 sizeof (struct GNUNET_PeerIdentity)))
4249 GNUNET_break_op (0);
4253 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
4258 GNUNET_break_op (0);
4263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4264 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
4266 a2s (ve->transport_name,
4267 (const struct sockaddr *) ve->addr,
4269 ve->transport_name);
4272 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
4273 if (0 != memcmp (&pong->pid,
4275 sizeof (struct GNUNET_PeerIdentity)))
4279 GNUNET_asprintf(&peer, "%s",GNUNET_i2s (&pong->pid));
4281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4282 "Received PONG for different identity: I am `%s', PONG identity: `%s'\n",
4283 GNUNET_i2s (&my_identity),
4289 if (ve->addrlen != 0)
4291 /* must have been for a different validation entry */
4294 tp = find_transport (ve->transport_name);
4300 oal = tp->addresses;
4303 if ( (oal->addrlen == alen) &&
4304 (0 == memcmp (&oal[1],
4312 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4313 _("Not accepting PONG from `%s' with address `%s' since I cannot confirm using this address.\n"),
4314 GNUNET_i2s (&pong->pid),
4315 a2s (ve->transport_name,
4318 /* FIXME: since the sender of the PONG currently uses the
4319 wrong address (see FIMXE there!), we cannot run a
4320 proper check here... */
4326 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
4331 GNUNET_break_op (0);
4336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4337 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
4339 a2s (ve->transport_name,
4342 ve->transport_name);
4346 GNUNET_break_op (0);
4349 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
4351 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4352 _("Received expired signature. Check system time.\n"));
4355 GNUNET_STATISTICS_update (stats,
4356 gettext_noop ("# address validation successes"),
4359 /* create the updated HELLO */
4360 GNUNET_CRYPTO_hash (&ve->publicKey,
4361 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4362 &target.hashPubKey);
4363 if (ve->addr != NULL)
4365 avac.done = GNUNET_NO;
4367 hello = GNUNET_HELLO_create (&ve->publicKey,
4368 &add_validated_address,
4370 GNUNET_PEERINFO_add_peer (peerinfo,
4372 GNUNET_free (hello);
4374 n = find_neighbour (&target);
4377 n->publicKey = ve->publicKey;
4378 n->public_key_valid = GNUNET_YES;
4379 fal = add_peer_address (n,
4384 GNUNET_assert (fal != NULL);
4385 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
4386 fal->validated = GNUNET_YES;
4387 mark_address_connected (fal);
4388 GNUNET_STATISTICS_update (stats,
4389 gettext_noop ("# peer addresses considered valid"),
4392 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
4393 update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4395 schedule_next_ping (fal);
4396 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
4397 n->latency = fal->latency;
4399 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
4401 n->distance = fal->distance;
4402 if (GNUNET_NO == n->received_pong)
4404 n->received_pong = GNUNET_YES;
4405 notify_clients_connect (&target, n->latency, n->distance);
4406 if (NULL != (prem = n->pre_connect_message_buffer))
4408 n->pre_connect_message_buffer = NULL;
4409 handle_payload_message (prem, n);
4413 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4415 GNUNET_SCHEDULER_cancel (n->retry_task);
4416 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4417 try_transmission_to_peer (n);
4421 /* clean up validation entry */
4422 GNUNET_assert (GNUNET_YES ==
4423 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4426 abort_validation (NULL, NULL, ve);
4432 * Function that will be called if we receive a validation
4433 * of an address challenge that we transmitted to another
4434 * peer. Note that the validation should only be considered
4435 * acceptable if the challenge matches AND if the sender
4436 * address is at least a plausible address for this peer
4437 * (otherwise we may be seeing a MiM attack).
4439 * @param cls closure
4440 * @param message the pong message
4441 * @param peer who responded to our challenge
4442 * @param sender_address string describing our sender address (as observed
4443 * by the other peer in binary format)
4444 * @param sender_address_len number of bytes in 'sender_address'
4447 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
4448 const struct GNUNET_PeerIdentity *peer,
4449 const char *sender_address,
4450 size_t sender_address_len)
4452 if (0 == memcmp (peer,
4454 sizeof (struct GNUNET_PeerIdentity)))
4456 /* PONG send to self, ignore */
4457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4458 "Receiving `%s' message from myself\n",
4462 #if DEBUG_TRANSPORT > 1
4463 /* we get tons of these that just get discarded, only log
4464 if we are quite verbose */
4465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4466 "Receiving `%s' message from `%4s'.\n", "PONG",
4469 GNUNET_STATISTICS_update (stats,
4470 gettext_noop ("# PONG messages received"),
4473 if (GNUNET_SYSERR !=
4474 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
4476 &check_pending_validation,
4479 /* This is *expected* to happen a lot since we send
4480 PONGs to *all* known addresses of the sender of
4481 the PING, so most likely we get multiple PONGs
4482 per PING, and all but the first PONG will end up
4483 here. So really we should not print anything here
4484 unless we want to be very, very verbose... */
4485 #if DEBUG_TRANSPORT > 2
4486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4487 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
4499 * Try to validate a neighbour's address by sending him our HELLO and a PING.
4501 * @param cls the 'struct ValidationEntry*'
4502 * @param neighbour neighbour to validate, NULL if validation failed
4505 transmit_hello_and_ping (void *cls,
4506 struct NeighbourList *neighbour)
4508 struct ValidationEntry *va = cls;
4509 struct ForeignAddressList *peer_address;
4510 struct TransportPingMessage ping;
4511 uint16_t hello_size;
4514 struct GNUNET_PeerIdentity id;
4517 GNUNET_CRYPTO_hash (&va->publicKey,
4518 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4520 if (neighbour == NULL)
4522 /* FIXME: stats... */
4523 GNUNET_break (GNUNET_OK ==
4524 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4527 abort_validation (NULL, NULL, va);
4530 neighbour->publicKey = va->publicKey;
4531 neighbour->public_key_valid = GNUNET_YES;
4532 peer_address = add_peer_address (neighbour,
4533 va->transport_name, NULL,
4534 (const void*) &va[1],
4536 if (peer_address == NULL)
4538 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4539 "Failed to add peer `%4s' for plugin `%s'\n",
4540 GNUNET_i2s (&neighbour->id),
4541 va->transport_name);
4542 GNUNET_break (GNUNET_OK ==
4543 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4546 abort_validation (NULL, NULL, va);
4549 if (NULL == our_hello)
4551 hello_size = GNUNET_HELLO_size(our_hello);
4552 slen = strlen(va->transport_name) + 1;
4553 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
4554 message_buf = GNUNET_malloc(tsize);
4555 ping.challenge = htonl(va->challenge);
4556 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
4557 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4558 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4559 memcpy(message_buf, our_hello, hello_size);
4560 memcpy(&message_buf[hello_size],
4562 sizeof(struct TransportPingMessage));
4563 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4566 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4571 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
4574 : a2s (va->transport_name,
4575 (const void*) &va[1], va->addrlen),
4577 GNUNET_i2s (&neighbour->id),
4578 "HELLO", hello_size,
4579 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
4582 GNUNET_STATISTICS_update (stats,
4583 gettext_noop ("# PING messages sent for initial validation"),
4586 transmit_to_peer (NULL, peer_address,
4587 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4588 HELLO_VERIFICATION_TIMEOUT,
4590 GNUNET_YES, neighbour);
4591 GNUNET_free(message_buf);
4596 * Check if the given address is already being validated; if not,
4597 * append the given address to the list of entries that are being be
4598 * validated and initiate validation.
4600 * @param cls closure ('struct CheckHelloValidatedContext *')
4601 * @param tname name of the transport
4602 * @param expiration expiration time
4603 * @param addr the address
4604 * @param addrlen length of the address
4605 * @return GNUNET_OK (always)
4608 run_validation (void *cls,
4610 struct GNUNET_TIME_Absolute expiration,
4614 struct CheckHelloValidatedContext *chvc = cls;
4615 struct GNUNET_PeerIdentity id;
4616 struct TransportPlugin *tp;
4617 struct ValidationEntry *va;
4618 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4619 struct CheckAddressExistsClosure caec;
4620 struct OwnAddressList *oal;
4622 GNUNET_assert (addr != NULL);
4624 GNUNET_STATISTICS_update (stats,
4625 gettext_noop ("# peer addresses scheduled for validation"),
4628 tp = find_transport (tname);
4631 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
4632 GNUNET_ERROR_TYPE_BULK,
4634 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4636 GNUNET_STATISTICS_update (stats,
4637 gettext_noop ("# peer addresses not validated (plugin not available)"),
4642 /* check if this is one of our own addresses */
4643 oal = tp->addresses;
4646 if ( (oal->addrlen == addrlen) &&
4647 (0 == memcmp (&oal[1],
4651 /* not plausible, this address is equivalent to our own address! */
4652 GNUNET_STATISTICS_update (stats,
4653 gettext_noop ("# peer addresses not validated (loopback)"),
4660 GNUNET_HELLO_get_key (chvc->hello, &pk);
4661 GNUNET_CRYPTO_hash (&pk,
4663 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4666 if (is_blacklisted(&id, tp))
4669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4670 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4678 caec.addrlen = addrlen;
4679 caec.session = NULL;
4681 caec.exists = GNUNET_NO;
4682 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4683 &check_address_exists,
4685 if (caec.exists == GNUNET_YES)
4687 /* During validation attempts we will likely trigger the other
4688 peer trying to validate our address which in turn will cause
4689 it to send us its HELLO, so we expect to hit this case rather
4690 frequently. Only print something if we are very verbose. */
4691 #if DEBUG_TRANSPORT > 1
4692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4693 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4694 a2s (tname, addr, addrlen),
4698 GNUNET_STATISTICS_update (stats,
4699 gettext_noop ("# peer addresses not validated (in progress)"),
4704 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4707 va->transport_name = GNUNET_strdup (tname);
4708 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4710 va->send_time = GNUNET_TIME_absolute_get();
4711 va->addr = (const void*) &va[1];
4712 memcpy (&va[1], addr, addrlen);
4713 va->addrlen = addrlen;
4714 GNUNET_HELLO_get_key (chvc->hello,
4716 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4717 &timeout_hello_validation,
4719 GNUNET_CONTAINER_multihashmap_put (validation_map,
4722 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4723 setup_peer_check_blacklist (&id, GNUNET_NO,
4724 &transmit_hello_and_ping,
4731 * Check if addresses in validated hello "h" overlap with
4732 * those in "chvc->hello" and validate the rest.
4734 * @param cls closure
4735 * @param peer id of the peer, NULL for last call
4736 * @param h hello message for the peer (can be NULL)
4737 * @param err_msg NULL if successful, otherwise contains error message
4740 check_hello_validated (void *cls,
4741 const struct GNUNET_PeerIdentity *peer,
4742 const struct GNUNET_HELLO_Message *h,
4743 const char *err_msg)
4745 struct CheckHelloValidatedContext *chvc = cls;
4746 struct GNUNET_HELLO_Message *plain_hello;
4747 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4748 struct GNUNET_PeerIdentity target;
4749 struct NeighbourList *n;
4751 if (err_msg != NULL)
4754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4755 _("Error in communication with PEERINFO service: %s\n"),
4763 GNUNET_STATISTICS_update (stats,
4764 gettext_noop ("# outstanding peerinfo iterate requests"),
4768 if (GNUNET_NO == chvc->hello_known)
4770 /* notify PEERINFO about the peer now, so that we at least
4771 have the public key if some other component needs it */
4772 GNUNET_HELLO_get_key (chvc->hello, &pk);
4773 GNUNET_CRYPTO_hash (&pk,
4774 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4775 &target.hashPubKey);
4776 plain_hello = GNUNET_HELLO_create (&pk,
4779 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4780 GNUNET_free (plain_hello);
4781 #if DEBUG_TRANSPORT_HELLO
4782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4783 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4785 GNUNET_i2s (&target));
4787 GNUNET_STATISTICS_update (stats,
4788 gettext_noop ("# new HELLOs requiring full validation"),
4791 GNUNET_HELLO_iterate_addresses (chvc->hello,
4798 GNUNET_STATISTICS_update (stats,
4799 gettext_noop ("# duplicate HELLO (peer known)"),
4804 if (chvc->ve_count == 0)
4806 GNUNET_CONTAINER_DLL_remove (chvc_head,
4815 #if DEBUG_TRANSPORT_HELLO
4816 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4817 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4821 chvc->hello_known = GNUNET_YES;
4822 n = find_neighbour (peer);
4825 #if DEBUG_TRANSPORT_HELLO
4826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4827 "Calling hello_iterate_addresses for %s!\n",
4830 GNUNET_HELLO_iterate_addresses (h,
4832 &add_to_foreign_address_list,
4834 try_transmission_to_peer (n);
4838 #if DEBUG_TRANSPORT_HELLO
4839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4840 "No existing neighbor record for %s!\n",
4843 GNUNET_STATISTICS_update (stats,
4844 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4848 GNUNET_STATISTICS_update (stats,
4849 gettext_noop ("# HELLO validations (update case)"),
4852 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4854 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4861 * Process HELLO-message.
4863 * @param plugin transport involved, may be NULL
4864 * @param message the actual message
4865 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4868 process_hello (struct TransportPlugin *plugin,
4869 const struct GNUNET_MessageHeader *message)
4872 struct GNUNET_PeerIdentity target;
4873 const struct GNUNET_HELLO_Message *hello;
4874 struct CheckHelloValidatedContext *chvc;
4875 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4876 struct NeighbourList *n;
4877 #if DEBUG_TRANSPORT_HELLO > 2
4881 hsize = ntohs (message->size);
4882 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4883 (hsize < sizeof (struct GNUNET_MessageHeader)))
4886 return GNUNET_SYSERR;
4888 GNUNET_STATISTICS_update (stats,
4889 gettext_noop ("# HELLOs received for validation"),
4893 hello = (const struct GNUNET_HELLO_Message *) message;
4894 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4896 #if DEBUG_TRANSPORT_HELLO
4897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4898 "Unable to get public key from `%s' for `%4s'!\n",
4900 GNUNET_i2s (&target));
4902 GNUNET_break_op (0);
4903 return GNUNET_SYSERR;
4905 GNUNET_CRYPTO_hash (&publicKey,
4906 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4907 &target.hashPubKey);
4909 #if DEBUG_TRANSPORT_HELLO
4910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4911 "Received `%s' message for `%4s'\n",
4913 GNUNET_i2s (&target));
4915 if (0 == memcmp (&my_identity,
4917 sizeof (struct GNUNET_PeerIdentity)))
4919 GNUNET_STATISTICS_update (stats,
4920 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4925 n = find_neighbour (&target);
4927 (! n->public_key_valid) )
4929 GNUNET_HELLO_get_key (hello, &n->publicKey);
4930 n->public_key_valid = GNUNET_YES;
4933 /* check if load is too high before doing expensive stuff */
4934 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4936 GNUNET_STATISTICS_update (stats,
4937 gettext_noop ("# HELLOs ignored due to high load"),
4940 #if DEBUG_TRANSPORT_HELLO
4941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4942 "Ignoring `%s' for `%4s', load too high.\n",
4944 GNUNET_i2s (&target));
4951 while (NULL != chvc)
4953 if (GNUNET_HELLO_equals (hello,
4955 GNUNET_TIME_absolute_get ()).abs_value > 0)
4957 #if DEBUG_TRANSPORT_HELLO > 2
4958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4959 "Received duplicate `%s' message for `%4s'; ignored\n",
4961 GNUNET_i2s (&target));
4963 return GNUNET_OK; /* validation already pending */
4965 if (GNUNET_HELLO_size (hello) == GNUNET_HELLO_size (chvc->hello))
4966 GNUNET_break (0 != memcmp (hello, chvc->hello,
4967 GNUNET_HELLO_size(hello)));
4972 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4973 if ((NULL != temp_neighbor))
4975 fprintf(stderr, "Already know peer, ignoring hello\n");
4980 #if DEBUG_TRANSPORT_HELLO > 2
4983 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4986 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4989 GNUNET_i2s (&target),
4991 GNUNET_HELLO_size(hello));
4996 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4998 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4999 memcpy (&chvc[1], hello, hsize);
5000 GNUNET_CONTAINER_DLL_insert (chvc_head,
5003 /* finally, check if HELLO was previously validated
5004 (continuation will then schedule actual validation) */
5005 GNUNET_STATISTICS_update (stats,
5006 gettext_noop ("# peerinfo process hello iterate requests"),
5009 GNUNET_STATISTICS_update (stats,
5010 gettext_noop ("# outstanding peerinfo iterate requests"),
5013 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
5015 HELLO_VERIFICATION_TIMEOUT,
5016 &check_hello_validated, chvc);
5022 * The peer specified by the given neighbour has timed-out or a plugin
5023 * has disconnected. We may either need to do nothing (other plugins
5024 * still up), or trigger a full disconnect and clean up. This
5025 * function updates our state and does the necessary notifications.
5026 * Also notifies our clients that the neighbour is now officially
5029 * @param n the neighbour list entry for the peer
5030 * @param check GNUNET_YES to check if ALL addresses for this peer
5031 * are gone, GNUNET_NO to force a disconnect of the peer
5032 * regardless of whether other addresses exist.
5035 disconnect_neighbour (struct NeighbourList *n, int check)
5037 struct ReadyList *rpos;
5038 struct NeighbourList *npos;
5039 struct NeighbourList *nprev;
5040 struct MessageQueue *mq;
5041 struct ForeignAddressList *peer_addresses;
5042 struct ForeignAddressList *peer_pos;
5044 if (GNUNET_YES == check)
5047 while (NULL != rpos)
5049 peer_addresses = rpos->addresses;
5050 while (peer_addresses != NULL)
5052 // Do not disconnect if: an address is connected or an inbound address exists
5053 if ((GNUNET_YES == peer_addresses->connected) || (peer_addresses->addrlen == 0))
5056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5057 "NOT Disconnecting from `%4s', still have live address `%s'!\n",
5058 GNUNET_i2s (&n->id),
5059 a2s (peer_addresses->ready_list->plugin->short_name,
5060 peer_addresses->addr,
5061 peer_addresses->addrlen));
5063 return; /* still connected */
5065 peer_addresses = peer_addresses->next;
5071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5072 "Disconnecting from `%4s'\n",
5073 GNUNET_i2s (&n->id));
5075 /* remove n from neighbours list */
5078 while ((npos != NULL) && (npos != n))
5083 GNUNET_assert (npos != NULL);
5085 neighbours = n->next;
5087 nprev->next = n->next;
5089 /* notify all clients about disconnect */
5090 if (GNUNET_YES == n->received_pong)
5091 notify_clients_disconnect (&n->id);
5093 /* clean up all plugins, cancel connections and pending transmissions */
5094 while (NULL != (rpos = n->plugins))
5096 n->plugins = rpos->next;
5097 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
5098 while (rpos->addresses != NULL)
5100 peer_pos = rpos->addresses;
5101 rpos->addresses = peer_pos->next;
5102 if (peer_pos->connected == GNUNET_YES)
5103 GNUNET_STATISTICS_update (stats,
5104 gettext_noop ("# connected addresses"),
5107 if (GNUNET_YES == peer_pos->validated)
5108 GNUNET_STATISTICS_update (stats,
5109 gettext_noop ("# peer addresses considered valid"),
5112 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
5114 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
5115 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
5117 GNUNET_free(peer_pos->ressources);
5118 peer_pos->ressources = NULL;
5119 GNUNET_free(peer_pos->quality);
5120 peer_pos->ressources = NULL;
5121 GNUNET_free(peer_pos);
5122 ats->stat.recreate_problem = GNUNET_YES;
5127 /* free all messages on the queue */
5128 while (NULL != (mq = n->messages_head))
5130 GNUNET_STATISTICS_update (stats,
5131 gettext_noop ("# bytes in message queue for other peers"),
5132 - (int64_t) mq->message_buf_size,
5134 GNUNET_STATISTICS_update (stats,
5135 gettext_noop ("# bytes discarded due to disconnect"),
5136 mq->message_buf_size,
5138 GNUNET_CONTAINER_DLL_remove (n->messages_head,
5141 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5143 sizeof(struct GNUNET_PeerIdentity)));
5147 while (NULL != (mq = n->cont_head))
5150 GNUNET_CONTAINER_DLL_remove (n->cont_head,
5153 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5155 sizeof(struct GNUNET_PeerIdentity)));
5159 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
5161 GNUNET_SCHEDULER_cancel (n->timeout_task);
5162 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
5164 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
5166 GNUNET_SCHEDULER_cancel (n->retry_task);
5167 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
5169 if (n->piter != NULL)
5171 GNUNET_PEERINFO_iterate_cancel (n->piter);
5172 GNUNET_STATISTICS_update (stats,
5173 gettext_noop ("# outstanding peerinfo iterate requests"),
5178 /* finally, free n itself */
5179 GNUNET_STATISTICS_update (stats,
5180 gettext_noop ("# active neighbours"),
5183 GNUNET_free_non_null (n->pre_connect_message_buffer);
5189 * We have received a PING message from someone. Need to send a PONG message
5190 * in response to the peer by any means necessary.
5193 handle_ping (void *cls, const struct GNUNET_MessageHeader *message,
5194 const struct GNUNET_PeerIdentity *peer,
5195 struct Session *session,
5196 const char *sender_address,
5197 uint16_t sender_address_len)
5199 struct TransportPlugin *plugin = cls;
5200 struct SessionHeader *session_header = (struct SessionHeader*) session;
5201 struct TransportPingMessage *ping;
5202 struct TransportPongMessage *pong;
5203 struct NeighbourList *n;
5204 struct ReadyList *rl;
5205 struct ForeignAddressList *fal;
5206 struct OwnAddressList *oal;
5212 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
5214 GNUNET_break_op (0);
5215 return GNUNET_SYSERR;
5218 ping = (struct TransportPingMessage *) message;
5219 if (0 != memcmp (&ping->target,
5220 plugin->env.my_identity,
5221 sizeof (struct GNUNET_PeerIdentity)))
5224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5225 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
5227 (sender_address != NULL)
5228 ? a2s (plugin->short_name,
5229 (const struct sockaddr *)sender_address,
5232 GNUNET_i2s (&ping->target));
5234 return GNUNET_SYSERR;
5237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5238 "Processing `%s' from `%s'\n",
5240 (sender_address != NULL)
5241 ? a2s (plugin->short_name,
5242 (const struct sockaddr *)sender_address,
5246 GNUNET_STATISTICS_update (stats,
5247 gettext_noop ("# PING messages received"),
5250 addr = (const char*) &ping[1];
5251 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
5252 slen = strlen (plugin->short_name) + 1;
5255 /* peer wants to confirm that we have an outbound connection to him */
5256 if (session == NULL)
5258 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5259 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
5261 return GNUNET_SYSERR;
5263 /* FIXME-urg: the use of 'sender_address' in the code below is doubly-wrong:
5264 1) it is NULL when we need to have a real value
5265 2) it is documented to be the address of the sender (source-IP), where
5266 what we actually want is our LISTEN IP (what we 'bound' to); which we don't even
5269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5270 "Creating PONG indicating that we received a connection at our address `%s' from `%s'.\n",
5271 a2s (plugin->short_name,
5273 sender_address_len),
5276 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5277 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5278 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5279 pong->purpose.size =
5280 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5282 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5283 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
5284 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
5285 pong->challenge = ping->challenge;
5286 pong->addrlen = htonl(sender_address_len + slen);
5289 sizeof(struct GNUNET_PeerIdentity));
5293 if ((sender_address!=NULL) && (sender_address_len > 0))
5294 memcpy (&((char*)&pong[1])[slen],
5296 sender_address_len);
5297 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
5299 /* create / update cached sig */
5301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5302 "Creating PONG signature to indicate active connection.\n");
5304 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5305 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5306 GNUNET_assert (GNUNET_OK ==
5307 GNUNET_CRYPTO_rsa_sign (my_private_key,
5309 &session_header->pong_signature));
5313 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5315 memcpy (&pong->signature,
5316 &session_header->pong_signature,
5317 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5323 /* peer wants to confirm that this is one of our addresses */
5327 plugin->api->check_address (plugin->api->cls,
5331 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5332 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
5333 a2s (plugin->short_name,
5338 oal = plugin->addresses;
5341 if ( (oal->addrlen == alen) &&
5348 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
5349 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
5350 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5351 pong->purpose.size =
5352 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5354 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5355 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
5356 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
5357 pong->challenge = ping->challenge;
5358 pong->addrlen = htonl(alen + slen);
5361 sizeof(struct GNUNET_PeerIdentity));
5362 memcpy (&pong[1], plugin->short_name, slen);
5363 memcpy (&((char*)&pong[1])[slen], addr, alen);
5364 if ( (oal != NULL) &&
5365 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
5367 /* create / update cached sig */
5369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5370 "Creating PONG signature to indicate ownership.\n");
5372 oal->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5373 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5374 GNUNET_assert (GNUNET_OK ==
5375 GNUNET_CRYPTO_rsa_sign (my_private_key,
5377 &oal->pong_signature));
5378 memcpy (&pong->signature,
5379 &oal->pong_signature,
5380 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5382 else if (oal == NULL)
5384 /* not using cache (typically DV-only) */
5385 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
5386 GNUNET_assert (GNUNET_OK ==
5387 GNUNET_CRYPTO_rsa_sign (my_private_key,
5393 /* can used cached version */
5394 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5395 memcpy (&pong->signature,
5396 &oal->pong_signature,
5397 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5400 n = find_neighbour(peer);
5401 GNUNET_assert (n != NULL);
5402 did_pong = GNUNET_NO;
5403 /* first try reliable response transmission */
5407 fal = rl->addresses;
5410 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
5413 ntohs (pong->header.size),
5414 TRANSPORT_PONG_PRIORITY,
5415 HELLO_VERIFICATION_TIMEOUT,
5422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5423 "Transmitted PONG to `%s' via reliable mechanism\n",
5426 GNUNET_STATISTICS_update (stats,
5427 gettext_noop ("# PONGs unicast via reliable transport"),
5433 did_pong = GNUNET_YES;
5438 /* no reliable method found, do multicast */
5439 GNUNET_STATISTICS_update (stats,
5440 gettext_noop ("# PONGs multicast to all available addresses"),
5446 fal = rl->addresses;
5449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5450 "Transmitting PONG to `%s' via unreliable mechanism `%s':%s\n",
5452 a2s (rl->plugin->short_name,
5455 rl->plugin->short_name);
5456 transmit_to_peer(NULL, fal,
5457 TRANSPORT_PONG_PRIORITY,
5458 HELLO_VERIFICATION_TIMEOUT,
5460 ntohs(pong->header.size),
5463 did_pong = GNUNET_YES;
5469 if (GNUNET_YES != did_pong)
5470 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5471 _("Could not send PONG to `%s': no address available\n"),
5478 * Function called by the plugin for each received message. Update
5479 * data volumes, possibly notify plugins about reducing the rate at
5480 * which they read from the socket and generally forward to our
5483 * @param cls the "struct TransportPlugin *" we gave to the plugin
5484 * @param peer (claimed) identity of the other peer
5485 * @param message the message, NULL if we only care about
5486 * learning about the delay until we should receive again
5487 * @param ats_data information for automatic transport selection
5488 * @param ats_count number of elements in ats not including 0-terminator
5489 * @param session identifier used for this session (can be NULL)
5490 * @param sender_address binary address of the sender (if observed)
5491 * @param sender_address_len number of bytes in sender_address
5492 * @return how long in ms the plugin should wait until receiving more data
5493 * (plugins that do not support this, can ignore the return value)
5495 static struct GNUNET_TIME_Relative
5496 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
5497 const struct GNUNET_MessageHeader *message,
5498 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
5500 struct Session *session,
5501 const char *sender_address,
5502 uint16_t sender_address_len)
5504 struct TransportPlugin *plugin = cls;
5505 struct ReadyList *service_context;
5506 struct ForeignAddressList *peer_address;
5508 struct NeighbourList *n;
5509 struct GNUNET_TIME_Relative ret;
5513 if (0 == memcmp (peer,
5515 sizeof (struct GNUNET_PeerIdentity)))
5517 /* refuse to receive from myself */
5519 return GNUNET_TIME_UNIT_FOREVER_REL;
5521 if (is_blacklisted (peer, plugin))
5522 return GNUNET_TIME_UNIT_FOREVER_REL;
5523 n = find_neighbour (peer);
5525 n = setup_new_neighbour (peer, GNUNET_YES);
5526 service_context = n->plugins;
5527 while ((service_context != NULL) && (plugin != service_context->plugin))
5528 service_context = service_context->next;
5529 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
5530 peer_address = NULL;
5533 for (c=0; c<ats_count; c++)
5534 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
5535 distance = ntohl(ats_data[c].value);
5537 /* notify ATS about incoming data */
5538 //ats_notify_ats_data(peer, ats_data);
5540 if (message != NULL)
5542 if ( (session != NULL) ||
5543 (sender_address != NULL) )
5544 peer_address = add_peer_address (n,
5548 sender_address_len);
5549 if (peer_address != NULL)
5551 update_addr_ats(peer_address, ats_data, ats_count);
5552 update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5554 peer_address->distance = distance;
5555 if (GNUNET_YES == peer_address->validated)
5556 mark_address_connected (peer_address);
5557 peer_address->timeout
5558 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5559 schedule_next_ping (peer_address);
5561 /* update traffic received amount ... */
5562 msize = ntohs (message->size);
5564 GNUNET_STATISTICS_update (stats,
5565 gettext_noop ("# bytes received from other peers"),
5568 n->distance = distance;
5570 GNUNET_TIME_relative_to_absolute
5571 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5572 GNUNET_SCHEDULER_cancel (n->timeout_task);
5574 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
5575 &neighbour_timeout_task, n);
5576 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
5578 /* dropping message due to frequent inbound volume violations! */
5579 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
5580 GNUNET_ERROR_TYPE_BULK,
5582 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
5583 n->in_tracker.available_bytes_per_s__,
5584 n->quota_violation_count);
5585 GNUNET_STATISTICS_update (stats,
5586 gettext_noop ("# bandwidth quota violations by other peers"),
5589 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
5591 if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
5592 (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
5594 uint32_t value = ntohl(*((uint32_t *) &message[1]));
5595 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
5596 /* Force ressource and quality update */
5599 ats->stat.modified_resources = GNUNET_YES;
5600 ats->stat.modified_quality = GNUNET_YES;
5602 /* Force cost update */
5604 ats->stat.modified_resources = GNUNET_YES;
5605 /* Force quality update */
5607 ats->stat.modified_quality = GNUNET_YES;
5608 /* Force full rebuild */
5610 ats->stat.recreate_problem = GNUNET_YES;
5614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5615 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
5616 ntohs (message->type),
5617 ntohs (message->size),
5620 switch (ntohs (message->type))
5622 case GNUNET_MESSAGE_TYPE_HELLO:
5623 GNUNET_STATISTICS_update (stats,
5624 gettext_noop ("# HELLO messages received from other peers"),
5627 process_hello (plugin, message);
5629 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
5630 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
5631 if (! n->received_pong)
5632 transmit_plain_ping (n);
5634 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
5635 handle_pong (plugin, message, peer, sender_address, sender_address_len);
5637 case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
5640 handle_payload_message (message, n);
5644 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
5645 if (ret.rel_value > 0)
5648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5649 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
5650 (unsigned long long) n->in_tracker.consumption_since_last_update__,
5651 (unsigned int) n->in_tracker.available_bytes_per_s__,
5652 (unsigned long long) ret.rel_value);
5654 GNUNET_STATISTICS_update (stats,
5655 gettext_noop ("# ms throttling suggested"),
5656 (int64_t) ret.rel_value,
5663 * Handle START-message. This is the first message sent to us
5664 * by any client which causes us to add it to our list.
5666 * @param cls closure (always NULL)
5667 * @param client identification of the client
5668 * @param message the actual message
5671 handle_start (void *cls,
5672 struct GNUNET_SERVER_Client *client,
5673 const struct GNUNET_MessageHeader *message)
5675 const struct StartMessage *start;
5676 struct TransportClient *c;
5677 struct ConnectInfoMessage * cim;
5678 struct NeighbourList *n;
5682 start = (const struct StartMessage*) message;
5684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5685 "Received `%s' request from client\n", "START");
5690 if (c->client == client)
5692 /* client already on our list! */
5694 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5699 if ( (GNUNET_NO != ntohl (start->do_check)) &&
5700 (0 != memcmp (&start->self,
5702 sizeof (struct GNUNET_PeerIdentity))) )
5704 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5705 _("Rejecting control connection from peer `%s', which is not me!\n"),
5706 GNUNET_i2s (&start->self));
5707 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5710 c = GNUNET_malloc (sizeof (struct TransportClient));
5714 if (our_hello != NULL)
5717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5718 "Sending our own `%s' to new client\n", "HELLO");
5720 transmit_to_client (c,
5721 (const struct GNUNET_MessageHeader *) our_hello,
5723 /* tell new client about all existing connections */
5725 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
5726 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
5730 cim = GNUNET_malloc (size);
5731 cim->header.size = htons (size);
5732 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
5733 cim->ats_count = htonl(ats_count);
5734 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
5735 (&(cim->ats))[2].value = htonl (0);
5739 if (GNUNET_YES == n->received_pong)
5741 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5742 (&(cim->ats))[0].value = htonl (n->distance);
5743 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5744 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
5746 transmit_to_client (c, &cim->header, GNUNET_NO);
5752 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5757 * Handle HELLO-message.
5759 * @param cls closure (always NULL)
5760 * @param client identification of the client
5761 * @param message the actual message
5764 handle_hello (void *cls,
5765 struct GNUNET_SERVER_Client *client,
5766 const struct GNUNET_MessageHeader *message)
5770 GNUNET_STATISTICS_update (stats,
5771 gettext_noop ("# HELLOs received from clients"),
5774 ret = process_hello (NULL, message);
5775 GNUNET_SERVER_receive_done (client, ret);
5780 * Closure for 'transmit_client_message'; followed by
5781 * 'msize' bytes of the actual message.
5783 struct TransmitClientMessageContext
5786 * Client on whom's behalf we are sending.
5788 struct GNUNET_SERVER_Client *client;
5791 * Timeout for the transmission.
5793 struct GNUNET_TIME_Absolute timeout;
5801 * Size of the message in bytes.
5808 * Schedule transmission of a message we got from a client to a peer.
5810 * @param cls the 'struct TransmitClientMessageContext*'
5811 * @param n destination, or NULL on error (in that case, drop the message)
5814 transmit_client_message (void *cls,
5815 struct NeighbourList *n)
5817 struct TransmitClientMessageContext *tcmc = cls;
5818 struct TransportClient *tc;
5821 while ((tc != NULL) && (tc->client != tcmc->client))
5826 transmit_to_peer (tc, NULL, tcmc->priority,
5827 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5829 tcmc->msize, GNUNET_NO, n);
5831 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5832 GNUNET_SERVER_client_drop (tcmc->client);
5838 * Handle SEND-message.
5840 * @param cls closure (always NULL)
5841 * @param client identification of the client
5842 * @param message the actual message
5845 handle_send (void *cls,
5846 struct GNUNET_SERVER_Client *client,
5847 const struct GNUNET_MessageHeader *message)
5849 const struct OutboundMessage *obm;
5850 const struct GNUNET_MessageHeader *obmm;
5851 struct TransmitClientMessageContext *tcmc;
5855 size = ntohs (message->size);
5857 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5860 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5863 GNUNET_STATISTICS_update (stats,
5864 gettext_noop ("# payload received for other peers"),
5867 obm = (const struct OutboundMessage *) message;
5868 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5869 msize = size - sizeof (struct OutboundMessage);
5871 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5872 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5873 "SEND", GNUNET_i2s (&obm->peer),
5877 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5878 tcmc->client = client;
5879 tcmc->priority = ntohl (obm->priority);
5880 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5881 tcmc->msize = msize;
5882 /* FIXME: this memcpy can be up to 7% of our total runtime */
5883 memcpy (&tcmc[1], obmm, msize);
5884 GNUNET_SERVER_client_keep (client);
5885 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5886 &transmit_client_message,
5892 * Handle request connect message
5894 * @param cls closure (always NULL)
5895 * @param client identification of the client
5896 * @param message the actual message
5899 handle_request_connect (void *cls,
5900 struct GNUNET_SERVER_Client *client,
5901 const struct GNUNET_MessageHeader *message)
5903 const struct TransportRequestConnectMessage *trcm =
5904 (const struct TransportRequestConnectMessage *) message;
5906 GNUNET_STATISTICS_update (stats,
5907 gettext_noop ("# REQUEST CONNECT messages received"),
5911 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
5912 "Received a request connect message for peer `%s'\n",
5913 GNUNET_i2s(&trcm->peer));
5915 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5917 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5922 * Handle SET_QUOTA-message.
5924 * @param cls closure (always NULL)
5925 * @param client identification of the client
5926 * @param message the actual message
5929 handle_set_quota (void *cls,
5930 struct GNUNET_SERVER_Client *client,
5931 const struct GNUNET_MessageHeader *message)
5933 const struct QuotaSetMessage *qsm =
5934 (const struct QuotaSetMessage *) message;
5935 struct NeighbourList *n;
5937 GNUNET_STATISTICS_update (stats,
5938 gettext_noop ("# SET QUOTA messages received"),
5941 n = find_neighbour (&qsm->peer);
5944 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5945 GNUNET_STATISTICS_update (stats,
5946 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5953 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5955 (unsigned int) ntohl (qsm->quota.value__),
5956 (unsigned int) n->in_tracker.available_bytes_per_s__,
5957 GNUNET_i2s (&qsm->peer));
5959 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5961 if (0 == ntohl (qsm->quota.value__))
5964 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5965 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5968 GNUNET_STATISTICS_update (stats,
5969 gettext_noop ("# disconnects due to quota of 0"),
5972 disconnect_neighbour (n, GNUNET_NO);
5974 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5979 * Take the given address and append it to the set of results sent back to
5982 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5983 * @param address the resolved name, NULL to indicate the last response
5986 transmit_address_to_client (void *cls, const char *address)
5988 struct GNUNET_SERVER_TransmitContext *tc = cls;
5991 if (NULL != address)
5993 slen = strlen (address) + 1;
5994 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5995 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5999 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6005 * Handle AddressLookup-message.
6007 * @param cls closure (always NULL)
6008 * @param client identification of the client
6009 * @param message the actual message
6012 handle_address_lookup (void *cls,
6013 struct GNUNET_SERVER_Client *client,
6014 const struct GNUNET_MessageHeader *message)
6016 const struct AddressLookupMessage *alum;
6017 struct TransportPlugin *lsPlugin;
6018 const char *nameTransport;
6019 const char *address;
6021 struct GNUNET_SERVER_TransmitContext *tc;
6022 struct GNUNET_TIME_Absolute timeout;
6023 struct GNUNET_TIME_Relative rtimeout;
6026 size = ntohs (message->size);
6027 if (size < sizeof (struct AddressLookupMessage))
6029 GNUNET_break_op (0);
6030 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6033 alum = (const struct AddressLookupMessage *) message;
6034 uint32_t addressLen = ntohl (alum->addrlen);
6035 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
6037 GNUNET_break_op (0);
6038 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6041 address = (const char *) &alum[1];
6042 nameTransport = (const char *) &address[addressLen];
6044 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
6046 GNUNET_break_op (0);
6047 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6050 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
6051 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
6052 numeric = ntohl (alum->numeric_only);
6053 lsPlugin = find_transport (nameTransport);
6054 if (NULL == lsPlugin)
6056 tc = GNUNET_SERVER_transmit_context_create (client);
6057 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6058 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6059 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
6062 GNUNET_SERVER_disable_receive_done_warning (client);
6063 tc = GNUNET_SERVER_transmit_context_create (client);
6064 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
6066 address, addressLen,
6069 &transmit_address_to_client, tc);
6074 * Setup the environment for this plugin.
6077 create_environment (struct TransportPlugin *plug)
6079 plug->env.cfg = cfg;
6080 plug->env.my_identity = &my_identity;
6081 plug->env.our_hello = &our_hello;
6082 plug->env.cls = plug;
6083 plug->env.receive = &plugin_env_receive;
6084 plug->env.notify_address = &plugin_env_notify_address;
6085 plug->env.session_end = &plugin_env_session_end;
6086 plug->env.max_connections = max_connect_per_transport;
6087 plug->env.stats = stats;
6092 * Start the specified transport (load the plugin).
6095 start_transport (struct GNUNET_SERVER_Handle *server,
6098 struct TransportPlugin *plug;
6101 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6102 _("Loading `%s' transport plugin\n"), name);
6103 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
6104 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
6105 create_environment (plug);
6106 plug->short_name = GNUNET_strdup (name);
6107 plug->lib_name = libname;
6108 plug->next = plugins;
6110 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
6111 if (plug->api == NULL)
6113 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6114 _("Failed to load transport plugin for `%s'\n"), name);
6115 GNUNET_free (plug->short_name);
6116 plugins = plug->next;
6117 GNUNET_free (libname);
6124 * Called whenever a client is disconnected. Frees our
6125 * resources associated with that client.
6127 * @param cls closure
6128 * @param client identification of the client
6131 client_disconnect_notification (void *cls,
6132 struct GNUNET_SERVER_Client *client)
6134 struct TransportClient *pos;
6135 struct TransportClient *prev;
6136 struct ClientMessageQueueEntry *mqe;
6137 struct Blacklisters *bl;
6138 struct BlacklistCheck *bc;
6143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
6144 "Client disconnected, cleaning up.\n");
6146 /* clean up blacklister */
6150 if (bl->client == client)
6155 if (bc->bl_pos == bl)
6157 bc->bl_pos = bl->next;
6160 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
6163 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
6164 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
6170 GNUNET_CONTAINER_DLL_remove (bl_head,
6173 GNUNET_SERVER_client_drop (bl->client);
6179 /* clean up 'normal' clients */
6182 while ((pos != NULL) && (pos->client != client))
6189 while (NULL != (mqe = pos->message_queue_head))
6191 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
6192 pos->message_queue_tail,
6194 pos->message_count--;
6198 clients = pos->next;
6200 prev->next = pos->next;
6201 if (GNUNET_YES == pos->tcs_pending)
6206 if (pos->th != NULL)
6208 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
6211 GNUNET_break (0 == pos->message_count);
6217 * Function called when the service shuts down. Unloads our plugins
6218 * and cancels pending validations.
6220 * @param cls closure, unused
6221 * @param tc task context (unused)
6224 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6226 struct TransportPlugin *plug;
6227 struct OwnAddressList *al;
6228 struct CheckHelloValidatedContext *chvc;
6230 shutdown_in_progress = GNUNET_YES;
6231 while (neighbours != NULL)
6234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6235 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
6238 disconnect_neighbour (neighbours, GNUNET_NO);
6241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6242 "Transport service is unloading plugins...\n");
6244 while (NULL != (plug = plugins))
6246 plugins = plug->next;
6247 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
6249 GNUNET_SCHEDULER_cancel (plug->address_update_task);
6250 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
6252 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
6253 GNUNET_free (plug->lib_name);
6254 GNUNET_free (plug->short_name);
6255 while (NULL != (al = plug->addresses))
6257 plug->addresses = al->next;
6262 if (my_private_key != NULL)
6263 GNUNET_CRYPTO_rsa_key_free (my_private_key);
6264 GNUNET_free_non_null (our_hello);
6266 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
6269 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6270 validation_map = NULL;
6274 /* free 'chvc' data structure */
6275 while (NULL != (chvc = chvc_head))
6277 chvc_head = chvc->next;
6278 if (chvc->piter != NULL)
6280 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
6281 GNUNET_STATISTICS_update (stats,
6282 gettext_noop ("# outstanding peerinfo iterate requests"),
6289 GNUNET_assert (chvc->ve_count == 0);
6296 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6299 if (peerinfo != NULL)
6301 GNUNET_PEERINFO_disconnect (peerinfo);
6304 /* Can we assume those are gone by now, or do we need to clean up
6306 GNUNET_break (bl_head == NULL);
6307 GNUNET_break (bc_head == NULL);
6311 static int ats_evaluate_results (int result, int solution, char * problem)
6313 int cont = GNUNET_NO;
6314 #if DEBUG_ATS || VERBOSE_ATS
6315 int error_kind = GNUNET_ERROR_TYPE_DEBUG;
6318 error_kind = GNUNET_ERROR_TYPE_ERROR;
6322 case GNUNET_SYSERR : /* GNUNET problem, not GLPK related */
6323 #if DEBUG_ATS || VERBOSE_ATS
6324 GNUNET_log (error_kind, "%s , GLPK solving not executed\n", problem);
6327 case GLP_ESTOP : /* search terminated by application */
6328 #if DEBUG_ATS || VERBOSE_ATS
6329 GNUNET_log (error_kind, "%s , Search terminated by application\n", problem);
6332 case GLP_EITLIM : /* iteration limit exceeded */
6333 #if DEBUG_ATS || VERBOSE_ATS
6334 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Iteration limit exceeded\n", problem);
6337 case GLP_ETMLIM : /* time limit exceeded */
6338 #if DEBUG_ATS || VERBOSE_ATS
6339 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Time limit exceeded\n", problem);
6342 case GLP_ENOPFS : /* no primal feasible solution */
6343 case GLP_ENODFS : /* no dual feasible solution */
6344 #if DEBUG_ATS || VERBOSE_ATS
6345 GNUNET_log (error_kind, "%s No feasible solution\n", problem);
6349 case GLP_EBADB : /* invalid basis */
6350 case GLP_ESING : /* singular matrix */
6351 case GLP_ECOND : /* ill-conditioned matrix */
6352 case GLP_EBOUND : /* invalid bounds */
6353 case GLP_EFAIL : /* solver failed */
6354 case GLP_EOBJLL : /* objective lower limit reached */
6355 case GLP_EOBJUL : /* objective upper limit reached */
6356 case GLP_EROOT : /* root LP optimum not provided */
6357 #if DEBUG_ATS || VERBOSE_ATS
6358 GNUNET_log (error_kind, "%s Invalid Input data: %i\n", problem, result);
6363 #if DEBUG_ATS || VERBOSE_ATS
6364 GNUNET_log (error_kind, "%s Problem has been solved\n", problem);
6371 #if DEBUG_ATS || VERBOSE_ATS
6372 GNUNET_log (error_kind, "%s solution is undefined\n", problem);
6376 #if DEBUG_ATS || VERBOSE_ATS
6377 GNUNET_log (error_kind, "%s solution is optimal\n", problem);
6382 #if DEBUG_ATS || VERBOSE_ATS
6383 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"));
6388 #if DEBUG_ATS || VERBOSE_ATS
6389 GNUNET_log (error_kind, "%s problem has no %sfeasible solution\n", problem, (0==strcmp(problem,"LP")?"":"integer "));
6393 #if DEBUG_ATS || VERBOSE_ATS
6394 GNUNET_log (error_kind, "%s problem is infeasible \n", problem);
6398 #if DEBUG_ATS || VERBOSE_ATS
6399 GNUNET_log (error_kind, "%s problem is unbounded \n", problem);
6407 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)
6409 int result = GNUNET_SYSERR;
6410 int lp_solution = GNUNET_SYSERR;
6411 int mlp_solution = GNUNET_SYSERR;
6415 glp_init_smcp(&opt_lp);
6417 opt_lp.msg_lev = GLP_MSG_ALL;
6419 opt_lp.msg_lev = GLP_MSG_OFF;
6422 // setting iteration limit
6423 opt_lp.it_lim = max_it;
6425 opt_lp.tm_lim = max_dur;
6427 if (ats->stat.recreate_problem == GNUNET_YES)
6428 opt_lp.presolve = GLP_ON;
6429 result = glp_simplex(ats->prob, &opt_lp);
6430 lp_solution = glp_get_status (ats->prob);
6432 if ((result == GLP_ETMLIM) || (result == GLP_EITLIM))
6434 ats->stat.valid = GNUNET_NO;
6435 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ATS exceeded time or iteration limit!\n");
6439 if (ats_evaluate_results(result, lp_solution, "LP") == GNUNET_YES)
6441 stat->valid = GNUNET_YES;
6445 ats->stat.simplex_rerun_required = GNUNET_YES;
6446 opt_lp.presolve = GLP_ON;
6447 result = glp_simplex(ats->prob, &opt_lp);
6448 lp_solution = glp_get_status (ats->prob);
6450 // TODO: Remove if this does not appear until release
6451 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "EXECUTED SIMPLEX WITH PRESOLVER! %i \n", lp_solution);
6453 if (ats_evaluate_results(result, lp_solution, "LP") != GNUNET_YES)
6455 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "After execution simplex with presolver: STILL INVALID!\n");
6457 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);
6458 glp_write_lp (ats->prob, NULL, filename);
6459 GNUNET_free (filename);
6460 stat->valid = GNUNET_NO;
6461 ats->stat.recreate_problem = GNUNET_YES;
6464 stat->valid = GNUNET_YES;
6469 glp_init_iocp(&opt_mlp);
6471 opt_mlp.tm_lim = max_dur;
6474 opt_mlp.msg_lev = GLP_MSG_ALL;
6476 opt_mlp.msg_lev = GLP_MSG_OFF;
6479 result = glp_intopt (ats->prob, &opt_mlp);
6480 mlp_solution = glp_mip_status (ats->prob);
6481 stat->solution = mlp_solution;
6483 if (ats_evaluate_results(result, mlp_solution, "MLP") == GNUNET_YES)
6485 stat->valid = GNUNET_YES;
6489 // TODO: Remove if this does not appear until release
6490 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);
6491 stat->valid = GNUNET_NO;
6496 int error = GNUNET_NO;
6498 struct ATS_mechanism *t = NULL;
6499 for (c=1; c<= (c_peers); c++ )
6502 t = peers[c].m_head;
6505 bw = glp_get_col_prim(prob, t->col_index);
6509 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);
6511 if (check ==GNUNET_YES)
6513 glp_write_sol(prob, "invalid_solution.mlp");
6514 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid solution, check invalid_solution.mlp");
6515 GNUNET_STATISTICS_update (stats, "ATS invalid solutions", 1, GNUNET_NO);
6518 if (check ==GNUNET_NO)
6526 if (glp_get_col_prim(ats->prob,2*c_mechs+1) != 1)
6529 for (c=1; c<= available_quality_metrics; c++ )
6531 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));
6533 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));
6534 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));
6535 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));
6536 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "objective value: %f\n", glp_mip_obj_val(ats->prob));
6541 static void ats_delete_problem ()
6544 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Deleting problem\n");
6548 for (c=0; c< (ats->stat).c_mechs; c++)
6549 GNUNET_free_non_null (ats->mechanisms[c].rc);
6552 if (ats->mechanisms!=NULL)
6554 GNUNET_free(ats->mechanisms);
6555 ats->mechanisms = NULL;
6558 if (ats->peers!=NULL)
6560 GNUNET_free(ats->peers);
6564 if (ats->prob != NULL)
6566 glp_delete_prob(ats->prob);
6570 ats->stat.begin_cr = GNUNET_SYSERR;
6571 ats->stat.begin_qm = GNUNET_SYSERR;
6572 ats->stat.c_mechs = 0;
6573 ats->stat.c_peers = 0;
6574 ats->stat.end_cr = GNUNET_SYSERR;
6575 ats->stat.end_qm = GNUNET_SYSERR;
6576 ats->stat.solution = GNUNET_SYSERR;
6577 ats->stat.valid = GNUNET_SYSERR;
6581 static void ats_update_problem_qm ()
6586 int c_q_metrics = available_quality_metrics;
6588 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6589 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6591 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6593 row_index = ats->stat.begin_qm;
6595 for (c=1; c <= c_q_metrics; c++)
6600 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6603 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6604 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6606 ja[array_index] = c2;
6608 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6609 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6611 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
6613 double v0 = 0, v1 = 0, v2 = 0;
6615 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6616 if (v1 < 1) v0 = 0.1;
6617 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6618 if (v1 < 1) v0 = 0.1;
6619 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6620 if (v1 < 1) v0 = 0.1;
6621 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
6624 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
6626 double v0 = 0, v1 = 0, v2 = 0;
6627 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6629 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6631 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6633 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
6635 value = (double) 10 / value;
6639 ar[array_index] = (ats->mechanisms[c2].peer->f) * value;
6641 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]);
6645 ja[array_index] = ats->stat.col_qm + c - 1;
6646 ar[array_index] = -1;
6649 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6651 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6657 GNUNET_free_non_null (ja);
6658 GNUNET_free_non_null (ar);
6662 static void ats_update_problem_cr ()
6668 double ct_max, ct_min;
6670 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6671 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6673 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6674 row_index = ats->stat.begin_cr;
6677 for (c=0; c<available_ressources; c++)
6679 ct_max = ressources[c].c_max;
6680 ct_min = ressources[c].c_min;
6682 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
6684 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
6686 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6690 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6691 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6693 ja[array_index] = c2;
6694 value = ats->mechanisms[c2].addr->ressources[c].c;
6695 ar[array_index] = value;
6697 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6701 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6707 GNUNET_free_non_null (ja);
6708 GNUNET_free_non_null (ar);
6713 static void ats_update_problem_qm_TEST ()
6718 int old_ja[ats->stat.c_mechs + 2];
6719 double old_ar[ats->stat.c_mechs + 2];
6723 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6724 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6726 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics TEST\n");
6728 if (ats->stat.begin_qm >0)
6729 row_index = ats->stat.begin_qm;
6734 for (c=0; c<available_quality_metrics; c++)
6737 c_old = glp_get_mat_row (ats->prob, row_index, old_ja, old_ar);
6739 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6741 for (c2=1; c2<=c_old; c2++)
6743 ja[c2] = old_ja[c2];
6744 if ((changed < 3) && (c2>2) && (old_ar[c2] != -1))
6746 ar[c2] = old_ar[c2] + 5 - changed;
6750 ar[c2] = old_ar[c2];
6752 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]);
6755 glp_set_mat_row (ats->prob, row_index, c_old, ja, ar);
6760 GNUNET_free_non_null (ja);
6761 GNUNET_free_non_null (ar);
6763 #endif //END: HAVE_LIBGLPK
6765 /** solve the bandwidth distribution problem
6766 * @param max_it maximum iterations
6767 * @param max_dur maximum duration in ms
6768 * @param D weight for diversity
6769 * @param U weight for utility
6770 * @param R weight for relativity
6771 * @param v_b_min minimal bandwidth per peer
6772 * @param v_n_min minimum number of connections
6773 * @param stat result struct
6774 * @return GNUNET_SYSERR if glpk is not available, number of mechanisms used
6776 static int ats_create_problem (double D, double U, double R, int v_b_min, int v_n_min, struct ATS_stat *stat)
6778 ats->prob = glp_create_prob();
6784 int c_c_ressources = available_ressources;
6785 int c_q_metrics = available_quality_metrics;
6787 double M = VERY_BIG_DOUBLE_VALUE;
6788 double Q[c_q_metrics+1];
6789 for (c=1; c<=c_q_metrics; c++)
6794 struct NeighbourList *next = neighbours;
6797 int found_addresses = GNUNET_NO;
6798 struct ReadyList *r_next = next->plugins;
6799 while (r_next != NULL)
6801 struct ForeignAddressList * a_next = r_next->addresses;
6802 while (a_next != NULL)
6805 found_addresses = GNUNET_YES;
6806 a_next = a_next->next;
6808 r_next = r_next->next;
6810 if (found_addresses) c_peers++;
6817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No addresses for bw distribution available\n", c_peers);
6819 stat->valid = GNUNET_NO;
6822 return GNUNET_SYSERR;
6825 GNUNET_assert (ats->mechanisms == NULL);
6826 ats->mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
6827 GNUNET_assert (ats->peers == NULL);
6828 ats->peers = GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
6830 struct ATS_mechanism * mechanisms = ats->mechanisms;
6831 struct ATS_peer * peers = ats->peers;
6839 int found_addresses = GNUNET_NO;
6840 struct ReadyList *r_next = next->plugins;
6841 while (r_next != NULL)
6843 struct ForeignAddressList * a_next = r_next->addresses;
6844 while (a_next != NULL)
6846 if (found_addresses == GNUNET_NO)
6848 peers[c_peers].peer = next->id;
6849 peers[c_peers].m_head = NULL;
6850 peers[c_peers].m_tail = NULL;
6851 peers[c_peers].f = 1.0 / c_mechs;
6854 mechanisms[c_mechs].addr = a_next;
6855 mechanisms[c_mechs].col_index = c_mechs;
6856 mechanisms[c_mechs].peer = &peers[c_peers];
6857 mechanisms[c_mechs].next = NULL;
6858 mechanisms[c_mechs].plugin = r_next->plugin;
6860 GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head, peers[c_peers].m_tail, &mechanisms[c_mechs]);
6861 found_addresses = GNUNET_YES;
6864 a_next = a_next->next;
6866 r_next = r_next->next;
6868 if (found_addresses == GNUNET_YES)
6875 if (v_n_min > c_peers)
6879 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);
6882 int size = 1 + 3 + 10 *c_mechs + c_peers + (c_q_metrics*c_mechs)+ c_q_metrics + c_c_ressources * c_mechs ;
6885 int * ia = GNUNET_malloc (size * sizeof (int));
6886 int * ja = GNUNET_malloc (size * sizeof (int));
6887 double * ar = GNUNET_malloc(size* sizeof (double));
6889 glp_set_prob_name(ats->prob, "gnunet ats bandwidth distribution");
6890 glp_set_obj_dir(ats->prob, GLP_MAX);
6892 /* adding columns */
6894 glp_add_cols(ats->prob, 2 * c_mechs);
6895 /* adding b_t cols */
6896 for (c=1; c <= c_mechs; c++)
6899 GNUNET_asprintf(&name, "p_%s_b%i",GNUNET_i2s(&(mechanisms[c].peer->peer)), c);
6900 glp_set_col_name(ats->prob, c, name);
6902 glp_set_col_bnds(ats->prob, c, GLP_LO, 0.0, 0.0);
6903 glp_set_col_kind(ats->prob, c, GLP_CV);
6904 glp_set_obj_coef(ats->prob, c, 0);
6907 /* adding n_t cols */
6908 for (c=c_mechs+1; c <= 2*c_mechs; c++)
6910 GNUNET_asprintf(&name, "p_%s_n%i",GNUNET_i2s(&(mechanisms[c-c_mechs].peer->peer)),(c-c_mechs));
6911 glp_set_col_name(ats->prob, c, name);
6913 glp_set_col_bnds(ats->prob, c, GLP_DB, 0.0, 1.0);
6914 glp_set_col_kind(ats->prob, c, GLP_IV);
6915 glp_set_obj_coef(ats->prob, c, 0);
6918 /* feasibility constraints */
6919 /* Constraint 1: one address per peer*/
6921 glp_add_rows(ats->prob, c_peers);
6922 for (c=1; c<=c_peers; c++)
6925 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6927 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 1.0, 1.0);
6929 struct ATS_mechanism *m = peers[c].m_head;
6932 ia[array_index] = row_index;
6933 ja[array_index] = (c_mechs + m->col_index);
6934 ar[array_index] = 1;
6936 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6944 /* Constraint 2: only active mechanism gets bandwidth assigned */
6945 glp_add_rows(ats->prob, c_mechs);
6946 for (c=1; c<=c_mechs; c++)
6948 /* b_t - n_t * M <= 0 */
6950 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6952 glp_set_row_bnds(ats->prob, row_index, GLP_UP, 0.0, 0.0);
6954 ia[array_index] = row_index;
6955 ja[array_index] = mechanisms[c].col_index;
6956 ar[array_index] = 1;
6958 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6961 ia[array_index] = row_index;
6962 ja[array_index] = c_mechs + mechanisms[c].col_index;
6963 ar[array_index] = -M;
6965 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6971 /* Constraint 3: minimum bandwidth*/
6972 glp_add_rows(ats->prob, c_mechs);
6973 for (c=1; c<=c_mechs; c++)
6975 /* b_t - n_t * b_min <= 0 */
6977 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6979 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
6981 ia[array_index] = row_index;
6982 ja[array_index] = mechanisms[c].col_index;
6983 ar[array_index] = 1;
6985 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6988 ia[array_index] = row_index;
6989 ja[array_index] = c_mechs + mechanisms[c].col_index;
6990 ar[array_index] = -v_b_min;
6992 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6998 /* Constraint 4: max ressource capacity */
6999 /* V cr: bt * ct_r <= cr_max
7001 glp_add_rows(ats->prob, available_ressources);
7002 double ct_max = VERY_BIG_DOUBLE_VALUE;
7003 double ct_min = 0.0;
7005 stat->begin_cr = array_index;
7007 for (c=0; c<available_ressources; c++)
7009 ct_max = ressources[c].c_max;
7010 ct_min = ressources[c].c_min;
7012 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
7014 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
7016 for (c2=1; c2<=c_mechs; c2++)
7019 ia[array_index] = row_index;
7020 ja[array_index] = c2;
7021 value = mechanisms[c2].addr->ressources[c].c;
7022 ar[array_index] = value;
7024 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7030 stat->end_cr = array_index--;
7032 /* Constraint 5: min number of connections*/
7033 glp_add_rows(ats->prob, 1);
7034 for (c=1; c<=c_mechs; c++)
7036 // b_t - n_t * b_min >= 0
7038 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7040 glp_set_row_bnds(ats->prob, row_index, GLP_LO, v_n_min, 0.0);
7042 ia[array_index] = row_index;
7043 ja[array_index] = c_mechs + mechanisms[c].col_index;
7044 ar[array_index] = 1;
7046 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7052 // optimisation constraints
7056 // Constraint 6: optimize for diversity
7058 col_d = glp_add_cols(ats->prob, 1);
7059 stat->col_d = col_d;
7060 //GNUNET_assert (col_d == (2*c_mechs) + 1);
7061 glp_set_col_name(ats->prob, col_d, "d");
7062 glp_set_obj_coef(ats->prob, col_d, D);
7063 glp_set_col_bnds(ats->prob, col_d, GLP_LO, 0.0, 0.0);
7064 glp_add_rows(ats->prob, 1);
7066 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7068 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7069 for (c=1; c<=c_mechs; c++)
7071 ia[array_index] = row_index;
7072 ja[array_index] = c_mechs + mechanisms[c].col_index;
7073 ar[array_index] = 1;
7075 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7079 ia[array_index] = row_index;
7080 ja[array_index] = col_d;
7081 ar[array_index] = -1;
7083 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7089 // Constraint 7: optimize for quality
7091 col_qm = glp_add_cols(ats->prob, c_q_metrics);
7092 stat->col_qm = col_qm;
7093 //GNUNET_assert (col_qm == (2*c_mechs) + 3 + 1);
7094 for (c=0; c< c_q_metrics; c++)
7096 GNUNET_asprintf(&name, "Q_%s",qm[c].name);
7097 glp_set_col_name(ats->prob, col_qm + c, name);
7098 glp_set_col_bnds(ats->prob, col_qm + c, GLP_LO, 0.0, 0.0);
7100 glp_set_obj_coef(ats->prob, col_qm + c, Q[c]);
7102 glp_add_rows(ats->prob, available_quality_metrics);
7103 stat->begin_qm = row_index;
7104 for (c=1; c <= c_q_metrics; c++)
7107 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7110 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7111 for (c2=1; c2<=c_mechs; c2++)
7114 ia[array_index] = row_index;
7115 ja[array_index] = c2;
7116 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
7118 double v0 = 0, v1 = 0, v2 = 0;
7119 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7120 if (v1 < 1) v0 = 0.1;
7121 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7122 if (v1 < 1) v0 = 0.1;
7123 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7124 if (v1 < 1) v0 = 0.1;
7125 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
7128 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
7130 double v0 = 0, v1 = 0, v2 = 0;
7131 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7133 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7135 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7137 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
7139 value = (double) 10 / value;
7143 ar[array_index] = (mechanisms[c2].peer->f) * value ;
7145 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]);
7150 ia[array_index] = row_index;
7151 ja[array_index] = col_qm + c - 1;
7152 ar[array_index] = -1;
7154 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7159 stat->end_qm = row_index-1;
7161 // Constraint 8: optimize bandwidth utility
7163 col_u = glp_add_cols(ats->prob, 1);
7164 stat->col_u = col_u;
7165 //GNUNET_assert (col_u == (2*c_mechs) + 2);
7166 glp_set_col_name(ats->prob, col_u, "u");
7167 glp_set_obj_coef(ats->prob, col_u, U);
7168 glp_set_col_bnds(ats->prob, col_u, GLP_LO, 0.0, 0.0);
7169 glp_add_rows(ats->prob, 1);
7171 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7173 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7174 for (c=1; c<=c_mechs; c++)
7176 ia[array_index] = row_index;
7177 ja[array_index] = c;
7178 ar[array_index] = mechanisms[c].peer->f;
7180 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7184 ia[array_index] = row_index;
7185 ja[array_index] = col_u;
7186 ar[array_index] = -1;
7188 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7194 // Constraint 9: optimize relativity
7196 col_r = glp_add_cols(ats->prob, 1);
7197 stat->col_r = col_r;
7198 //GNUNET_assert (col_r == (2*c_mechs) + 3);
7199 glp_set_col_name(ats->prob, col_r, "r");
7200 glp_set_obj_coef(ats->prob, col_r, R);
7201 glp_set_col_bnds(ats->prob, col_r, GLP_LO, 0.0, 0.0);
7202 glp_add_rows(ats->prob, c_peers);
7203 for (c=1; c<=c_peers; c++)
7205 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
7207 struct ATS_mechanism *m = peers[c].m_head;
7210 ia[array_index] = row_index;
7211 ja[array_index] = m->col_index;
7212 ar[array_index] = 1 / mechanisms[c].peer->f;
7214 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7219 ia[array_index] = row_index;
7220 ja[array_index] = col_r;
7221 ar[array_index] = -1;
7223 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7230 /* Loading the matrix */
7231 glp_load_matrix(ats->prob, array_index-1, ia, ja, ar);
7233 stat->c_mechs = c_mechs;
7234 stat->c_peers = c_peers;
7236 stat->valid = GNUNET_YES;
7248 void ats_notify_ats_data (
7249 const struct GNUNET_PeerIdentity *peer,
7250 const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
7253 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
7255 if (shutdown_in_progress == GNUNET_NO)
7256 ats_calculate_bandwidth_distribution();
7258 #endif //END: HAVE_LIBGLPK
7261 ats_calculate_bandwidth_distribution ()
7265 struct GNUNET_TIME_Absolute start;
7266 struct GNUNET_TIME_Relative creation;
7267 struct GNUNET_TIME_Relative solving;
7268 char *text = "unmodified";
7270 struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference (ats->last, GNUNET_TIME_absolute_get());
7271 if (delta.rel_value < ats->min_delta.rel_value)
7274 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
7279 if (shutdown_in_progress == GNUNET_YES)
7282 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Transport service is shutting down\n");
7289 if (INT_MAX < ats->max_exec_duration.rel_value)
7292 dur = (int) ats->max_exec_duration.rel_value;
7295 ats->stat.simplex_rerun_required = GNUNET_NO;
7296 start = GNUNET_TIME_absolute_get();
7297 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL) || (ats->stat.valid == GNUNET_NO))
7300 ats->stat.recreate_problem = GNUNET_YES;
7301 ats_delete_problem ();
7302 ats_create_problem (ats->D, ats->U, ats->R, ats->v_b_min, ats->v_n_min, &ats->stat);
7304 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);
7308 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_resources == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7310 text = "modified resources";
7311 ats_update_problem_cr();
7313 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_quality == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7315 text = "modified quality";
7316 ats_update_problem_qm();
7317 //ats_update_problem_qm_TEST ();
7321 else GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Problem is unmodified\n");
7324 creation = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7325 start = GNUNET_TIME_absolute_get();
7327 ats->stat.solution = GLP_UNDEF;
7328 if (ats->stat.valid == GNUNET_YES)
7330 ats_solve_problem(ats->max_iterations, ats->max_exec_duration.rel_value, ats->stat.c_peers, ats->stat.c_mechs, &ats->stat);
7332 solving = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7334 if (ats->stat.valid == GNUNET_YES)
7336 int msg_type = GNUNET_ERROR_TYPE_DEBUG;
7338 msg_type = GNUNET_ERROR_TYPE_ERROR;
7340 GNUNET_log (msg_type, "MLP %s: creation time: %llu, execution time: %llu, %i mechanisms, simplex rerun: %s, solution %s\n",
7341 text, creation.rel_value, solving.rel_value,
7343 (ats->stat.simplex_rerun_required == GNUNET_NO) ? "NO" : "YES", (ats->stat.solution == 5) ? "OPTIMAL" : "INVALID");
7344 ats->successful_executions ++;
7345 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7347 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL))
7348 GNUNET_STATISTICS_set (stats, "ATS state",ATS_NEW, GNUNET_NO);
7349 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7350 (ats->stat.modified_quality == GNUNET_NO))
7351 GNUNET_STATISTICS_set (stats, "ATS state", ATS_C_UPDATED, GNUNET_NO);
7352 else if ((ats->stat.modified_resources == GNUNET_NO) &&
7353 (ats->stat.modified_quality == GNUNET_YES) &&
7354 (ats->stat.simplex_rerun_required == GNUNET_NO))
7355 GNUNET_STATISTICS_set (stats, "ATS state", ATS_Q_UPDATED, GNUNET_NO);
7356 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7357 (ats->stat.modified_quality == GNUNET_YES) &&
7358 (ats->stat.simplex_rerun_required == GNUNET_NO))
7359 GNUNET_STATISTICS_set (stats, "ATS state", ATS_QC_UPDATED, GNUNET_NO);
7360 else if (ats->stat.simplex_rerun_required == GNUNET_NO)
7361 GNUNET_STATISTICS_set (stats, "ATS state", ATS_UNMODIFIED, GNUNET_NO);
7365 if (ats->stat.c_peers != 0)
7367 ats->invalid_executions ++;
7368 GNUNET_STATISTICS_set (stats, "# ATS invalid executions", ats->invalid_executions, GNUNET_NO);
7372 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7376 GNUNET_STATISTICS_set (stats, "ATS duration", solving.rel_value + creation.rel_value, GNUNET_NO);
7377 GNUNET_STATISTICS_set (stats, "ATS mechanisms", ats->stat.c_mechs, GNUNET_NO);
7378 GNUNET_STATISTICS_set (stats, "ATS peers", ats->stat.c_peers, GNUNET_NO);
7379 GNUNET_STATISTICS_set (stats, "ATS solution", ats->stat.solution, GNUNET_NO);
7380 GNUNET_STATISTICS_set (stats, "ATS timestamp", start.abs_value, GNUNET_NO);
7382 if ((ats->save_mlp == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7385 if (ats->dump_overwrite == GNUNET_NO)
7387 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.mlp",
7388 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7389 glp_write_lp (ats->prob, NULL, filename);
7393 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.mlp",
7394 ats->stat.c_peers, ats->stat.c_mechs );
7395 glp_write_lp (ats->prob, NULL, filename);
7397 GNUNET_free (filename);
7399 if ((ats->save_solution == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7402 if (ats->dump_overwrite == GNUNET_NO)
7404 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.sol",
7405 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7406 glp_print_sol (ats->prob, filename);
7410 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.sol",
7411 ats->stat.c_peers, ats->stat.c_mechs);
7412 glp_print_sol (ats->prob, filename);
7414 GNUNET_free (filename);
7417 ats->last = GNUNET_TIME_absolute_get();
7418 ats->stat.recreate_problem = GNUNET_NO;
7419 ats->stat.modified_resources = GNUNET_NO;
7420 ats->stat.modified_quality = GNUNET_NO;
7425 ats_schedule_calculation (void *cls,
7426 const struct GNUNET_SCHEDULER_TaskContext *tc)
7428 struct ATS_info *ats = (struct ATS_info *) cls;
7429 if (ats==NULL) return;
7431 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7432 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
7435 if (shutdown_in_progress == GNUNET_YES)
7439 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
7442 ats_calculate_bandwidth_distribution (ats);
7444 ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_interval,
7445 &ats_schedule_calculation, ats);
7451 unsigned long long value;
7454 ats = GNUNET_malloc(sizeof (struct ATS_info));
7456 ats->min_delta = ATS_MIN_INTERVAL;
7457 ats->exec_interval = ATS_EXEC_INTERVAL;
7458 ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
7459 ats->max_iterations = ATS_MAX_ITERATIONS;
7460 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS not active\n");
7470 ats->v_b_min = 64000;
7472 ats->dump_min_peers = 1;
7473 ats->dump_min_addr = 1;
7474 ats->dump_overwrite = GNUNET_NO;
7475 ats->mechanisms = NULL;
7477 ats->successful_executions = 0;
7478 ats->invalid_executions = 0;
7484 /* loading cost ressources */
7485 for (c=0; c<available_ressources; c++)
7487 GNUNET_asprintf(§ion,"%s_UP",ressources[c].cfg_param);
7488 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7490 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7493 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7495 ressources[c].c_max = value;
7498 GNUNET_free (section);
7499 GNUNET_asprintf(§ion,"%s_DOWN",ressources[c].cfg_param);
7500 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7502 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7505 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7507 ressources[c].c_min = value;
7510 GNUNET_free (section);
7513 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MLP"))
7514 ats->save_mlp = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_MLP");
7516 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_SOLUTION"))
7517 ats->save_solution = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_SOLUTION");
7518 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7519 ats->dump_overwrite = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_OVERWRITE");
7520 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_PEERS"))
7522 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_PEERS", &value);
7523 ats->dump_min_peers= value;
7525 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_ADDRS"))
7527 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_ADDRS", &value);
7528 ats->dump_min_addr= value;
7530 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7532 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_OVERWRITE", &value);
7533 ats->min_delta.rel_value = value;
7536 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7538 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7539 ats->min_delta.rel_value = value;
7542 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_EXEC_INTERVAL"))
7544 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_EXEC_INTERVAL", &value);
7545 ats->exec_interval.rel_value = value;
7547 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7549 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7550 ats->min_delta.rel_value = value;
7553 ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
7557 static void ats_shutdown ()
7560 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_destroy\n");
7562 if (ats->ats_task != GNUNET_SCHEDULER_NO_TASK)
7563 GNUNET_SCHEDULER_cancel(ats->ats_task);
7564 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7567 ats_delete_problem ();
7574 void ats_notify_peer_connect (
7575 const struct GNUNET_PeerIdentity *peer,
7576 const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count)
7579 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_connect: %s\n",GNUNET_i2s(peer));
7581 //update_addr_ats();
7582 ats->stat.recreate_problem = GNUNET_YES;
7583 ats_calculate_bandwidth_distribution(ats);
7586 void ats_notify_peer_disconnect (
7587 const struct GNUNET_PeerIdentity *peer)
7590 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_disconnect: %s\n",GNUNET_i2s(peer));
7592 ats->stat.recreate_problem = GNUNET_YES;
7593 ats_calculate_bandwidth_distribution (ats);
7596 struct ForeignAddressList * ats_get_preferred_address (
7597 struct NeighbourList *n)
7600 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ats_get_prefered_transport for peer: %s\n",GNUNET_i2s(&n->id));
7602 struct ReadyList *next = n->plugins;
7603 while (next != NULL)
7606 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "plugin: %s %i\n",next->plugin->short_name,strcmp(next->plugin->short_name,"unix"));
7610 return find_ready_address(n);
7614 * Initiate transport service.
7616 * @param cls closure
7617 * @param server the initialized server
7618 * @param c configuration to use
7622 struct GNUNET_SERVER_Handle *server,
7623 const struct GNUNET_CONFIGURATION_Handle *c)
7625 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
7626 {&handle_start, NULL,
7627 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
7628 {&handle_hello, NULL,
7629 GNUNET_MESSAGE_TYPE_HELLO, 0},
7630 {&handle_send, NULL,
7631 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
7632 {&handle_request_connect, NULL,
7633 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
7634 {&handle_set_quota, NULL,
7635 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
7636 {&handle_address_lookup, NULL,
7637 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
7639 {&handle_blacklist_init, NULL,
7640 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
7641 {&handle_blacklist_reply, NULL,
7642 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
7648 unsigned long long tneigh;
7651 shutdown_in_progress = GNUNET_NO;
7653 stats = GNUNET_STATISTICS_create ("transport", cfg);
7654 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
7655 /* parse configuration */
7657 GNUNET_CONFIGURATION_get_value_number (c,
7662 GNUNET_CONFIGURATION_get_value_filename (c,
7664 "HOSTKEY", &keyfile)))
7666 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7668 ("Transport service is lacking key configuration settings. Exiting.\n"));
7669 GNUNET_SCHEDULER_shutdown ();
7672 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7675 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7676 validation_map = NULL;
7680 max_connect_per_transport = (uint32_t) tneigh;
7681 peerinfo = GNUNET_PEERINFO_connect (cfg);
7682 if (peerinfo == NULL)
7684 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7685 _("Could not access PEERINFO service. Exiting.\n"));
7686 GNUNET_SCHEDULER_shutdown ();
7689 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7692 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7693 validation_map = NULL;
7694 GNUNET_free (keyfile);
7697 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7698 GNUNET_free (keyfile);
7699 if (my_private_key == NULL)
7701 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7703 ("Transport service could not access hostkey. Exiting.\n"));
7704 GNUNET_SCHEDULER_shutdown ();
7707 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7710 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7711 validation_map = NULL;
7714 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7715 GNUNET_CRYPTO_hash (&my_public_key,
7716 sizeof (my_public_key), &my_identity.hashPubKey);
7717 /* setup notification */
7718 GNUNET_SERVER_disconnect_notify (server,
7719 &client_disconnect_notification, NULL);
7720 /* load plugins... */
7723 GNUNET_CONFIGURATION_get_value_string (c,
7724 "TRANSPORT", "PLUGINS", &plugs))
7726 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7727 _("Starting transport plugins `%s'\n"), plugs);
7728 pos = strtok (plugs, " ");
7731 start_transport (server, pos);
7733 pos = strtok (NULL, " ");
7735 GNUNET_free (plugs);
7737 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
7738 &shutdown_task, NULL);
7745 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
7747 /* If we have a blacklist file, read from it */
7748 read_blacklist_file(cfg);
7749 /* process client requests */
7750 GNUNET_SERVER_add_handlers (server, handlers);
7755 * The main function for the transport service.
7757 * @param argc number of arguments from the command line
7758 * @param argv command line arguments
7759 * @return 0 ok, 1 on error
7762 main (int argc, char *const *argv)
7764 a2s (NULL, NULL, 0); /* make compiler happy */
7765 return (GNUNET_OK ==
7766 GNUNET_SERVICE_run (argc,
7769 GNUNET_SERVICE_OPTION_NONE,
7770 &run, NULL)) ? 0 : 1;
7773 /* end of gnunet-service-transport.c */