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);
2796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797 (add_remove == GNUNET_YES)
2798 ? "Adding `%s':%s to the set of our addresses\n"
2799 : "Removing `%s':%s from the set of our addresses\n",
2804 GNUNET_assert (addr != NULL);
2805 if (GNUNET_NO == add_remove)
2811 if ( (addrlen == al->addrlen) &&
2812 (0 == memcmp (addr, &al[1], addrlen)) )
2815 p->addresses = al->next;
2817 prev->next = al->next;
2828 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2829 al->next = p->addresses;
2831 al->addrlen = addrlen;
2832 memcpy (&al[1], addr, addrlen);
2838 * Notify all of our clients about a peer connecting.
2841 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2842 struct GNUNET_TIME_Relative latency,
2845 struct ConnectInfoMessage * cim;
2846 struct TransportClient *cpos;
2850 if (0 == memcmp (peer,
2852 sizeof (struct GNUNET_PeerIdentity)))
2858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859 "Notifying clients about connection with `%s'\n",
2862 GNUNET_STATISTICS_update (stats,
2863 gettext_noop ("# peers connected"),
2868 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2869 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2873 cim = GNUNET_malloc (size);
2874 cim->header.size = htons (size);
2875 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2876 cim->ats_count = htonl(2);
2877 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2878 (&(cim->ats))[0].value = htonl (distance);
2879 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2880 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2881 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2882 (&(cim->ats))[2].value = htonl (0);
2883 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2885 /* notify ats about connecting peer */
2886 if (shutdown_in_progress == GNUNET_NO)
2887 ats_notify_peer_connect (peer, &(cim->ats), 2);
2890 while (cpos != NULL)
2892 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2901 * Notify all of our clients about a peer disconnecting.
2904 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2906 struct DisconnectInfoMessage dim;
2907 struct TransportClient *cpos;
2909 if (0 == memcmp (peer,
2911 sizeof (struct GNUNET_PeerIdentity)))
2917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2918 "Notifying clients about lost connection to `%s'\n",
2921 GNUNET_STATISTICS_update (stats,
2922 gettext_noop ("# peers connected"),
2925 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2926 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2927 dim.reserved = htonl (0);
2928 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2930 /* notify ats about connecting peer */
2931 if (shutdown_in_progress == GNUNET_NO)
2932 ats_notify_peer_disconnect (peer);
2935 while (cpos != NULL)
2937 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2944 * Find a ForeignAddressList entry for the given neighbour
2945 * that matches the given address and transport.
2947 * @param neighbour which peer we care about
2948 * @param tname name of the transport plugin
2949 * @param session session to look for, NULL for 'any'; otherwise
2950 * can be used for the service to "learn" this session ID
2952 * @param addr binary address
2953 * @param addrlen length of addr
2954 * @return NULL if no such entry exists
2956 static struct ForeignAddressList *
2957 find_peer_address(struct NeighbourList *neighbour,
2959 struct Session *session,
2963 struct ReadyList *head;
2964 struct ForeignAddressList *pos;
2966 head = neighbour->plugins;
2967 while (head != NULL)
2969 if (0 == strcmp (tname, head->plugin->short_name))
2975 pos = head->addresses;
2976 while ( (pos != NULL) &&
2977 ( (pos->addrlen != addrlen) ||
2978 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2980 if ( (session != NULL) &&
2981 (pos->session == session) )
2985 if ( (session != NULL) && (pos != NULL) )
2986 pos->session = session; /* learn it! */
2992 * Get the peer address struct for the given neighbour and
2993 * address. If it doesn't yet exist, create it.
2995 * @param neighbour which peer we care about
2996 * @param tname name of the transport plugin
2997 * @param session session of the plugin, or NULL for none
2998 * @param addr binary address
2999 * @param addrlen length of addr
3000 * @return NULL if we do not have a transport plugin for 'tname'
3002 static struct ForeignAddressList *
3003 add_peer_address (struct NeighbourList *neighbour,
3005 struct Session *session,
3009 struct ReadyList *head;
3010 struct ForeignAddressList *ret;
3013 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
3016 head = neighbour->plugins;
3018 while (head != NULL)
3020 if (0 == strcmp (tname, head->plugin->short_name))
3026 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
3027 ret->session = session;
3028 if ((addrlen > 0) && (addr != NULL))
3030 ret->addr = (const char*) &ret[1];
3031 memcpy (&ret[1], addr, addrlen);
3038 ret->ressources = GNUNET_malloc(available_ressources * sizeof (struct ATS_ressource_entry));
3039 for (c=0; c<available_ressources; c++)
3041 struct ATS_ressource_entry *r = ret->ressources;
3043 r[c].atis_index = ressources[c].atis_index;
3044 if (0 == strcmp(neighbour->plugins->plugin->short_name,"unix"))
3046 r[c].c = ressources[c].c_unix;
3048 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"udp"))
3050 r[c].c = ressources[c].c_udp;
3052 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"tcp"))
3054 r[c].c = ressources[c].c_tcp;
3056 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"http"))
3058 r[c].c = ressources[c].c_http;
3060 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"https"))
3062 r[c].c = ressources[c].c_https;
3064 else if (0 == strcmp(neighbour->plugins->plugin->short_name,"wlan"))
3066 r[c].c = ressources[c].c_wlan;
3070 r[c].c = ressources[c].c_default;
3071 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3072 "Assigning default cost to peer `%s' addr plugin `%s'! This should not happen!\n",
3073 GNUNET_i2s(&neighbour->peer),
3074 neighbour->plugins->plugin->short_name);
3078 ret->quality = GNUNET_malloc (available_quality_metrics * sizeof (struct ATS_quality_entry));
3079 ret->addrlen = addrlen;
3080 ret->expires = GNUNET_TIME_relative_to_absolute
3081 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3082 ret->latency = GNUNET_TIME_relative_get_forever();
3084 ret->timeout = GNUNET_TIME_relative_to_absolute
3085 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3086 ret->ready_list = head;
3087 ret->next = head->addresses;
3088 head->addresses = ret;
3094 * Closure for 'add_validated_address'.
3096 struct AddValidatedAddressContext
3099 * Entry that has been validated.
3101 const struct ValidationEntry *ve;
3104 * Flag set after we have added the address so
3105 * that we terminate the iteration next time.
3112 * Callback function used to fill a buffer of max bytes with a list of
3113 * addresses in the format used by HELLOs. Should use
3114 * "GNUNET_HELLO_add_address" as a helper function.
3116 * @param cls the 'struct AddValidatedAddressContext' with the validated address
3117 * @param max maximum number of bytes that can be written to buf
3118 * @param buf where to write the address information
3119 * @return number of bytes written, 0 to signal the
3120 * end of the iteration.
3123 add_validated_address (void *cls,
3124 size_t max, void *buf)
3126 struct AddValidatedAddressContext *avac = cls;
3127 const struct ValidationEntry *ve = avac->ve;
3129 if (GNUNET_YES == avac->done)
3131 avac->done = GNUNET_YES;
3132 return GNUNET_HELLO_add_address (ve->transport_name,
3133 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
3143 * Closure for 'check_address_exists'.
3145 struct CheckAddressExistsClosure
3148 * Address to check for.
3153 * Name of the transport.
3160 struct Session *session;
3163 * Set to GNUNET_YES if the address exists.
3176 * Iterator over hash map entries. Checks if the given
3177 * validation entry is for the same address as what is given
3180 * @param cls the 'struct CheckAddressExistsClosure*'
3181 * @param key current key code (ignored)
3182 * @param value value in the hash map ('struct ValidationEntry')
3183 * @return GNUNET_YES if we should continue to
3184 * iterate (mismatch), GNUNET_NO if not (entry matched)
3187 check_address_exists (void *cls,
3188 const GNUNET_HashCode * key,
3191 struct CheckAddressExistsClosure *caec = cls;
3192 struct ValidationEntry *ve = value;
3194 if ( (0 == strcmp (caec->tname,
3195 ve->transport_name)) &&
3196 (caec->addrlen == ve->addrlen) &&
3197 (0 == memcmp (caec->addr,
3201 caec->exists = GNUNET_YES;
3204 if ( (ve->session != NULL) &&
3205 (caec->session == ve->session) )
3207 caec->exists = GNUNET_YES;
3215 neighbour_timeout_task (void *cls,
3216 const struct GNUNET_SCHEDULER_TaskContext *tc)
3218 struct NeighbourList *n = cls;
3221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3222 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
3224 GNUNET_STATISTICS_update (stats,
3225 gettext_noop ("# disconnects due to timeout"),
3228 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3229 disconnect_neighbour (n, GNUNET_NO);
3234 * Schedule the job that will cause us to send a PING to the
3235 * foreign address to evaluate its validity and latency.
3237 * @param fal address to PING
3240 schedule_next_ping (struct ForeignAddressList *fal);
3244 * Add the given address to the list of foreign addresses
3245 * available for the given peer (check for duplicates).
3247 * @param cls the respective 'struct NeighbourList' to update
3248 * @param tname name of the transport
3249 * @param expiration expiration time
3250 * @param addr the address
3251 * @param addrlen length of the address
3252 * @return GNUNET_OK (always)
3255 add_to_foreign_address_list (void *cls,
3257 struct GNUNET_TIME_Absolute expiration,
3261 struct NeighbourList *n = cls;
3262 struct ForeignAddressList *fal;
3265 GNUNET_STATISTICS_update (stats,
3266 gettext_noop ("# valid peer addresses returned by PEERINFO"),
3270 fal = find_peer_address (n, tname, NULL, addr, addrlen);
3273 #if DEBUG_TRANSPORT_HELLO
3274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3275 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
3276 a2s (tname, addr, addrlen),
3278 GNUNET_i2s (&n->id),
3279 expiration.abs_value);
3281 fal = add_peer_address (n, tname, NULL, addr, addrlen);
3284 GNUNET_STATISTICS_update (stats,
3285 gettext_noop ("# previously validated addresses lacking transport"),
3291 fal->expires = GNUNET_TIME_absolute_max (expiration,
3293 schedule_next_ping (fal);
3299 fal->expires = GNUNET_TIME_absolute_max (expiration,
3305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3306 "Failed to add new address for `%4s'\n",
3307 GNUNET_i2s (&n->id));
3311 if (fal->validated == GNUNET_NO)
3313 fal->validated = GNUNET_YES;
3314 GNUNET_STATISTICS_update (stats,
3315 gettext_noop ("# peer addresses considered valid"),
3319 if (try == GNUNET_YES)
3322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3323 "Have new addresses, will try to trigger transmissions.\n");
3325 try_transmission_to_peer (n);
3332 * Add addresses in validated HELLO "h" to the set of addresses
3333 * we have for this peer.
3335 * @param cls closure ('struct NeighbourList*')
3336 * @param peer id of the peer, NULL for last call
3337 * @param h hello message for the peer (can be NULL)
3338 * @param err_msg NULL if successful, otherwise contains error message
3341 add_hello_for_peer (void *cls,
3342 const struct GNUNET_PeerIdentity *peer,
3343 const struct GNUNET_HELLO_Message *h,
3344 const char *err_msg)
3346 struct NeighbourList *n = cls;
3348 if (err_msg != NULL)
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 _("Error in communication with PEERINFO service: %s\n"),
3359 GNUNET_STATISTICS_update (stats,
3360 gettext_noop ("# outstanding peerinfo iterate requests"),
3367 return; /* no HELLO available */
3369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3370 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
3374 if (GNUNET_YES != n->public_key_valid)
3376 GNUNET_HELLO_get_key (h, &n->publicKey);
3377 n->public_key_valid = GNUNET_YES;
3379 GNUNET_HELLO_iterate_addresses (h,
3381 &add_to_foreign_address_list,
3387 * Create a fresh entry in our neighbour list for the given peer.
3388 * Will try to transmit our current HELLO to the new neighbour.
3389 * Do not call this function directly, use 'setup_peer_check_blacklist.
3391 * @param peer the peer for which we create the entry
3392 * @param do_hello should we schedule transmitting a HELLO
3393 * @return the new neighbour list entry
3395 static struct NeighbourList *
3396 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
3399 struct NeighbourList *n;
3400 struct TransportPlugin *tp;
3401 struct ReadyList *rl;
3403 GNUNET_assert (0 != memcmp (peer,
3405 sizeof (struct GNUNET_PeerIdentity)));
3407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3408 "Setting up state for neighbour `%4s'\n",
3411 GNUNET_STATISTICS_update (stats,
3412 gettext_noop ("# active neighbours"),
3415 n = GNUNET_malloc (sizeof (struct NeighbourList));
3416 n->next = neighbours;
3420 GNUNET_TIME_relative_to_absolute
3421 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3422 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
3423 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
3424 MAX_BANDWIDTH_CARRY_S);
3428 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
3430 rl = GNUNET_malloc (sizeof (struct ReadyList));
3432 rl->next = n->plugins;
3435 rl->addresses = NULL;
3439 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
3441 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3442 &neighbour_timeout_task, n);
3445 GNUNET_STATISTICS_update (stats,
3446 gettext_noop ("# peerinfo new neighbor iterate requests"),
3449 GNUNET_STATISTICS_update (stats,
3450 gettext_noop ("# outstanding peerinfo iterate requests"),
3453 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
3454 GNUNET_TIME_UNIT_FOREVER_REL,
3455 &add_hello_for_peer, n);
3457 GNUNET_STATISTICS_update (stats,
3458 gettext_noop ("# HELLO's sent to new neighbors"),
3461 if (NULL != our_hello)
3462 transmit_to_peer (NULL, NULL, 0,
3463 HELLO_ADDRESS_EXPIRATION,
3464 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
3472 * Function called after we have checked if communicating
3473 * with a given peer is acceptable.
3475 * @param cls closure
3476 * @param n NULL if communication is not acceptable
3478 typedef void (*SetupContinuation)(void *cls,
3479 struct NeighbourList *n);
3483 * Information kept for each client registered to perform
3489 * This is a linked list.
3491 struct Blacklisters *next;
3494 * This is a linked list.
3496 struct Blacklisters *prev;
3499 * Client responsible for this entry.
3501 struct GNUNET_SERVER_Client *client;
3504 * Blacklist check that we're currently performing.
3506 struct BlacklistCheck *bc;
3512 * Head of DLL of blacklisting clients.
3514 static struct Blacklisters *bl_head;
3517 * Tail of DLL of blacklisting clients.
3519 static struct Blacklisters *bl_tail;
3523 * Context we use when performing a blacklist check.
3525 struct BlacklistCheck
3529 * This is a linked list.
3531 struct BlacklistCheck *next;
3534 * This is a linked list.
3536 struct BlacklistCheck *prev;
3539 * Peer being checked.
3541 struct GNUNET_PeerIdentity peer;
3544 * Option for setup neighbour afterwards.
3549 * Continuation to call with the result.
3551 SetupContinuation cont;
3559 * Current transmission request handle for this client, or NULL if no
3560 * request is pending.
3562 struct GNUNET_CONNECTION_TransmitHandle *th;
3565 * Our current position in the blacklisters list.
3567 struct Blacklisters *bl_pos;
3570 * Current task performing the check.
3572 GNUNET_SCHEDULER_TaskIdentifier task;
3577 * Head of DLL of active blacklisting queries.
3579 static struct BlacklistCheck *bc_head;
3582 * Tail of DLL of active blacklisting queries.
3584 static struct BlacklistCheck *bc_tail;
3588 * Perform next action in the blacklist check.
3590 * @param cls the 'struct BlacklistCheck*'
3594 do_blacklist_check (void *cls,
3595 const struct GNUNET_SCHEDULER_TaskContext *tc);
3598 * Transmit blacklist query to the client.
3600 * @param cls the 'struct BlacklistCheck'
3601 * @param size number of bytes allowed
3602 * @param buf where to copy the message
3603 * @return number of bytes copied to buf
3606 transmit_blacklist_message (void *cls,
3610 struct BlacklistCheck *bc = cls;
3611 struct Blacklisters *bl;
3612 struct BlacklistMessage bm;
3617 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
3618 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3620 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3621 "Failed to send blacklist test for peer `%s' to client\n",
3622 GNUNET_i2s (&bc->peer));
3626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3627 "Sending blacklist test for peer `%s' to client\n",
3628 GNUNET_i2s (&bc->peer));
3631 bm.header.size = htons (sizeof (struct BlacklistMessage));
3632 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3633 bm.is_allowed = htonl (0);
3635 memcpy (buf, &bm, sizeof (bm));
3636 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3642 * Perform next action in the blacklist check.
3644 * @param cls the 'struct BlacklistCheck*'
3648 do_blacklist_check (void *cls,
3649 const struct GNUNET_SCHEDULER_TaskContext *tc)
3651 struct BlacklistCheck *bc = cls;
3652 struct Blacklisters *bl;
3654 bc->task = GNUNET_SCHEDULER_NO_TASK;
3659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3660 "No blacklist clients active, will now setup neighbour record for peer `%s'\n",
3661 GNUNET_i2s (&bc->peer));
3663 bc->cont (bc->cont_cls,
3664 setup_new_neighbour (&bc->peer, bc->do_hello));
3671 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3672 sizeof (struct BlacklistMessage),
3673 GNUNET_TIME_UNIT_FOREVER_REL,
3674 &transmit_blacklist_message,
3681 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3682 * does not yet exist, check the blacklist. If the blacklist says creating
3683 * one is acceptable, create one and call the continuation; otherwise
3684 * call the continuation with NULL.
3686 * @param peer peer to setup or look up a struct NeighbourList for
3687 * @param do_hello should we also schedule sending our HELLO to the peer
3688 * if this is a new record
3689 * @param cont function to call with the 'struct NeigbhbourList*'
3690 * @param cont_cls closure for cont
3693 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3695 SetupContinuation cont,
3698 struct NeighbourList *n;
3699 struct BlacklistCheck *bc;
3701 n = find_neighbour(peer);
3705 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3706 "Neighbour record exists for peer `%s'\n",
3713 if (bl_head == NULL)
3716 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3718 setup_new_neighbour(peer, do_hello);
3721 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3722 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3724 bc->do_hello = do_hello;
3726 bc->cont_cls = cont_cls;
3727 bc->bl_pos = bl_head;
3728 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3734 * Function called with the result of querying a new blacklister about
3735 * it being allowed (or not) to continue to talk to an existing neighbour.
3737 * @param cls the original 'struct NeighbourList'
3738 * @param n NULL if we need to disconnect
3741 confirm_or_drop_neighbour (void *cls,
3742 struct NeighbourList *n)
3744 struct NeighbourList * orig = cls;
3749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3750 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3751 "confirm_or_drop_neighboUr");
3753 GNUNET_STATISTICS_update (stats,
3754 gettext_noop ("# disconnects due to blacklist"),
3757 disconnect_neighbour (orig, GNUNET_NO);
3763 * Handle a request to start a blacklist.
3765 * @param cls closure (always NULL)
3766 * @param client identification of the client
3767 * @param message the actual message
3770 handle_blacklist_init (void *cls,
3771 struct GNUNET_SERVER_Client *client,
3772 const struct GNUNET_MessageHeader *message)
3774 struct Blacklisters *bl;
3775 struct BlacklistCheck *bc;
3776 struct NeighbourList *n;
3781 if (bl->client == client)
3784 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3789 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3790 bl->client = client;
3791 GNUNET_SERVER_client_keep (client);
3792 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3793 /* confirm that all existing connections are OK! */
3797 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3798 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3800 bc->do_hello = GNUNET_NO;
3801 bc->cont = &confirm_or_drop_neighbour;
3804 if (n == neighbours) /* all would wait for the same client, no need to
3805 create more than just the first task right now */
3806 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3814 * Handle a request to blacklist a peer.
3816 * @param cls closure (always NULL)
3817 * @param client identification of the client
3818 * @param message the actual message
3821 handle_blacklist_reply (void *cls,
3822 struct GNUNET_SERVER_Client *client,
3823 const struct GNUNET_MessageHeader *message)
3825 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3826 struct Blacklisters *bl;
3827 struct BlacklistCheck *bc;
3830 while ( (bl != NULL) &&
3831 (bl->client != client) )
3836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3837 "Blacklist client disconnected\n");
3839 /* FIXME: other error handling here!? */
3840 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3845 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3849 "Blacklist check failed, peer not allowed\n");
3851 bc->cont (bc->cont_cls, NULL);
3852 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3859 "Blacklist check succeeded, continuing with checks\n");
3861 bc->bl_pos = bc->bl_pos->next;
3862 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3865 /* check if any other bc's are waiting for this blacklister */
3869 if ( (bc->bl_pos == bl) &&
3870 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3871 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3879 * Send periodic PING messages to a given foreign address.
3881 * @param cls our 'struct PeriodicValidationContext*'
3882 * @param tc task context
3885 send_periodic_ping (void *cls,
3886 const struct GNUNET_SCHEDULER_TaskContext *tc)
3888 struct ForeignAddressList *peer_address = cls;
3889 struct TransportPlugin *tp;
3890 struct ValidationEntry *va;
3891 struct NeighbourList *neighbour;
3892 struct TransportPingMessage ping;
3893 struct CheckAddressExistsClosure caec;
3895 uint16_t hello_size;
3899 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3900 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3902 tp = peer_address->ready_list->plugin;
3903 neighbour = peer_address->ready_list->neighbour;
3904 if (GNUNET_YES != neighbour->public_key_valid)
3906 /* no public key yet, try again later */
3907 schedule_next_ping (peer_address);
3910 caec.addr = peer_address->addr;
3911 caec.addrlen = peer_address->addrlen;
3912 caec.tname = tp->short_name;
3913 caec.session = peer_address->session;
3914 caec.exists = GNUNET_NO;
3915 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3916 &check_address_exists,
3918 if (caec.exists == GNUNET_YES)
3920 /* During validation attempts we will likely trigger the other
3921 peer trying to validate our address which in turn will cause
3922 it to send us its HELLO, so we expect to hit this case rather
3923 frequently. Only print something if we are very verbose. */
3924 #if DEBUG_TRANSPORT > 1
3925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3927 (peer_address->addr != NULL)
3928 ? a2s (tp->short_name,
3930 peer_address->addrlen)
3933 GNUNET_i2s (&neighbour->id));
3935 schedule_next_ping (peer_address);
3938 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3939 va->transport_name = GNUNET_strdup (tp->short_name);
3940 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3942 va->send_time = GNUNET_TIME_absolute_get();
3943 va->session = peer_address->session;
3944 if (peer_address->addr != NULL)
3946 va->addr = (const void*) &va[1];
3947 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3948 va->addrlen = peer_address->addrlen;
3950 memcpy(&va->publicKey,
3951 &neighbour->publicKey,
3952 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3954 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3955 &timeout_hello_validation,
3957 GNUNET_CONTAINER_multihashmap_put (validation_map,
3958 &neighbour->id.hashPubKey,
3960 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3962 if (peer_address->validated != GNUNET_YES)
3963 hello_size = GNUNET_HELLO_size(our_hello);
3967 tsize = sizeof(struct TransportPingMessage) + hello_size;
3969 if (peer_address->addr != NULL)
3971 slen = strlen (tp->short_name) + 1;
3972 tsize += slen + peer_address->addrlen;
3976 slen = 0; /* make gcc happy */
3978 message_buf = GNUNET_malloc(tsize);
3979 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3980 ping.challenge = htonl(va->challenge);
3981 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3982 if (peer_address->validated != GNUNET_YES)
3984 memcpy(message_buf, our_hello, hello_size);
3987 if (peer_address->addr != NULL)
3989 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3990 peer_address->addrlen +
3992 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3995 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3997 peer_address->addrlen);
4001 ping.header.size = htons(sizeof(struct TransportPingMessage));
4004 memcpy(&message_buf[hello_size],
4006 sizeof(struct TransportPingMessage));
4008 #if DEBUG_TRANSPORT_REVALIDATION
4009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
4011 (peer_address->addr != NULL)
4012 ? a2s (peer_address->plugin->short_name,
4014 peer_address->addrlen)
4017 GNUNET_i2s (&neighbour->id),
4018 "HELLO", hello_size,
4021 if (peer_address->validated != GNUNET_YES)
4022 GNUNET_STATISTICS_update (stats,
4023 gettext_noop ("# PING with HELLO messages sent"),
4027 GNUNET_STATISTICS_update (stats,
4028 gettext_noop ("# PING without HELLO messages sent"),
4031 GNUNET_STATISTICS_update (stats,
4032 gettext_noop ("# PING messages sent for re-validation"),
4035 transmit_to_peer (NULL, peer_address,
4036 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4037 HELLO_VERIFICATION_TIMEOUT,
4039 GNUNET_YES, neighbour);
4040 GNUNET_free(message_buf);
4041 schedule_next_ping (peer_address);
4046 * Schedule the job that will cause us to send a PING to the
4047 * foreign address to evaluate its validity and latency.
4049 * @param fal address to PING
4052 schedule_next_ping (struct ForeignAddressList *fal)
4054 struct GNUNET_TIME_Relative delay;
4056 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
4058 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
4059 delay.rel_value /= 2; /* do before expiration */
4060 delay = GNUNET_TIME_relative_min (delay,
4061 LATENCY_EVALUATION_MAX_DELAY);
4062 if (GNUNET_YES != fal->estimated)
4064 delay = GNUNET_TIME_UNIT_ZERO;
4065 fal->estimated = GNUNET_YES;
4067 if (GNUNET_YES == fal->connected)
4069 delay = GNUNET_TIME_relative_min (delay,
4070 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
4072 /* FIXME: also adjust delay based on how close the last
4073 observed latency is to the latency of the best alternative */
4074 /* bound how fast we can go */
4075 delay = GNUNET_TIME_relative_max (delay,
4076 GNUNET_TIME_UNIT_SECONDS);
4077 /* randomize a bit (to avoid doing all at the same time) */
4078 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
4079 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
4080 &send_periodic_ping,
4088 * Function that will be called if we receive some payload
4089 * from another peer.
4091 * @param message the payload
4092 * @param n peer who claimed to be the sender
4095 handle_payload_message (const struct GNUNET_MessageHeader *message,
4096 struct NeighbourList *n)
4098 struct InboundMessage *im;
4099 struct TransportClient *cpos;
4102 msize = ntohs (message->size);
4103 if (n->received_pong == GNUNET_NO)
4106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4107 "Received message of type %u and size %u from `%4s', but no pong yet!\n",
4108 ntohs (message->type),
4109 ntohs (message->size),
4110 GNUNET_i2s (&n->id));
4112 GNUNET_free_non_null (n->pre_connect_message_buffer);
4113 n->pre_connect_message_buffer = GNUNET_malloc (msize);
4114 memcpy (n->pre_connect_message_buffer, message, msize);
4119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4120 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4121 ntohs (message->type),
4122 ntohs (message->size),
4123 GNUNET_i2s (&n->id));
4125 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4128 n->quota_violation_count++;
4130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4131 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
4132 n->in_tracker.available_bytes_per_s__,
4133 n->quota_violation_count);
4135 /* Discount 32k per violation */
4136 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4141 if (n->quota_violation_count > 0)
4143 /* try to add 32k back */
4144 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
4146 n->quota_violation_count--;
4149 GNUNET_STATISTICS_update (stats,
4150 gettext_noop ("# payload received from other peers"),
4153 /* transmit message to all clients */
4154 uint32_t ats_count = 2;
4155 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
4156 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4159 im = GNUNET_malloc (size);
4160 im->header.size = htons (size);
4161 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
4163 im->ats_count = htonl(ats_count);
4164 /* Setting ATS data */
4165 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4166 (&(im->ats))[0].value = htonl (n->distance);
4167 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4168 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
4169 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4170 (&(im->ats))[ats_count].value = htonl (0);
4172 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
4174 while (cpos != NULL)
4176 transmit_to_client (cpos, &im->header, GNUNET_YES);
4184 * Iterator over hash map entries. Checks if the given validation
4185 * entry is for the same challenge as what is given in the PONG.
4187 * @param cls the 'struct TransportPongMessage*'
4188 * @param key peer identity
4189 * @param value value in the hash map ('struct ValidationEntry')
4190 * @return GNUNET_YES if we should continue to
4191 * iterate (mismatch), GNUNET_NO if not (entry matched)
4194 check_pending_validation (void *cls,
4195 const GNUNET_HashCode * key,
4198 const struct TransportPongMessage *pong = cls;
4199 struct ValidationEntry *ve = value;
4200 struct AddValidatedAddressContext avac;
4201 unsigned int challenge = ntohl(pong->challenge);
4202 struct GNUNET_HELLO_Message *hello;
4203 struct GNUNET_PeerIdentity target;
4204 struct NeighbourList *n;
4205 struct ForeignAddressList *fal;
4206 struct OwnAddressList *oal;
4207 struct TransportPlugin *tp;
4208 struct GNUNET_MessageHeader *prem;
4214 ps = ntohs (pong->header.size);
4215 if (ps < sizeof (struct TransportPongMessage))
4217 GNUNET_break_op (0);
4220 addr = (const char*) &pong[1];
4221 slen = strlen (ve->transport_name) + 1;
4222 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
4223 (ve->challenge != challenge) ||
4224 (addr[slen-1] != '\0') ||
4225 (0 != strcmp (addr, ve->transport_name)) ||
4226 (ntohl (pong->purpose.size)
4227 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4229 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4230 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
4235 alen = ps - sizeof (struct TransportPongMessage) - slen;
4236 switch (ntohl (pong->purpose.purpose))
4238 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
4239 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
4240 (0 != memcmp (&addr[slen],
4244 return GNUNET_YES; /* different entry, keep trying! */
4246 if (0 != memcmp (&pong->pid,
4248 sizeof (struct GNUNET_PeerIdentity)))
4250 GNUNET_break_op (0);
4254 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
4259 GNUNET_break_op (0);
4264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4265 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
4267 a2s (ve->transport_name,
4268 (const struct sockaddr *) ve->addr,
4270 ve->transport_name);
4273 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
4274 if (0 != memcmp (&pong->pid,
4276 sizeof (struct GNUNET_PeerIdentity)))
4280 GNUNET_asprintf(&peer, "%s",GNUNET_i2s (&pong->pid));
4282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4283 "Received PONG for different identity: I am `%s', PONG identity: `%s'\n",
4284 GNUNET_i2s (&my_identity),
4290 if (ve->addrlen != 0)
4292 /* must have been for a different validation entry */
4295 tp = find_transport (ve->transport_name);
4301 oal = tp->addresses;
4304 if ( (oal->addrlen == alen) &&
4305 (0 == memcmp (&oal[1],
4313 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4314 _("Not accepting PONG from `%s' with address `%s' since I cannot confirm using this address.\n"),
4315 GNUNET_i2s (&pong->pid),
4316 a2s (ve->transport_name,
4319 /* FIXME: since the sender of the PONG currently uses the
4320 wrong address (see FIMXE there!), we cannot run a
4321 proper check here... */
4327 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
4332 GNUNET_break_op (0);
4337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4338 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
4340 a2s (ve->transport_name,
4343 ve->transport_name);
4347 GNUNET_break_op (0);
4350 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
4352 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4353 _("Received expired signature. Check system time.\n"));
4356 GNUNET_STATISTICS_update (stats,
4357 gettext_noop ("# address validation successes"),
4360 /* create the updated HELLO */
4361 GNUNET_CRYPTO_hash (&ve->publicKey,
4362 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4363 &target.hashPubKey);
4364 if (ve->addr != NULL)
4366 avac.done = GNUNET_NO;
4368 hello = GNUNET_HELLO_create (&ve->publicKey,
4369 &add_validated_address,
4371 GNUNET_PEERINFO_add_peer (peerinfo,
4373 GNUNET_free (hello);
4375 n = find_neighbour (&target);
4378 n->publicKey = ve->publicKey;
4379 n->public_key_valid = GNUNET_YES;
4380 fal = add_peer_address (n,
4385 GNUNET_assert (fal != NULL);
4386 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
4387 fal->validated = GNUNET_YES;
4388 mark_address_connected (fal);
4389 GNUNET_STATISTICS_update (stats,
4390 gettext_noop ("# peer addresses considered valid"),
4393 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
4394 update_addr_value (fal, GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value, GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4396 schedule_next_ping (fal);
4397 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
4398 n->latency = fal->latency;
4400 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
4402 n->distance = fal->distance;
4403 if (GNUNET_NO == n->received_pong)
4405 n->received_pong = GNUNET_YES;
4406 notify_clients_connect (&target, n->latency, n->distance);
4407 if (NULL != (prem = n->pre_connect_message_buffer))
4409 n->pre_connect_message_buffer = NULL;
4410 handle_payload_message (prem, n);
4414 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4416 GNUNET_SCHEDULER_cancel (n->retry_task);
4417 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4418 try_transmission_to_peer (n);
4422 /* clean up validation entry */
4423 GNUNET_assert (GNUNET_YES ==
4424 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4427 abort_validation (NULL, NULL, ve);
4433 * Function that will be called if we receive a validation
4434 * of an address challenge that we transmitted to another
4435 * peer. Note that the validation should only be considered
4436 * acceptable if the challenge matches AND if the sender
4437 * address is at least a plausible address for this peer
4438 * (otherwise we may be seeing a MiM attack).
4440 * @param cls closure
4441 * @param message the pong message
4442 * @param peer who responded to our challenge
4443 * @param sender_address string describing our sender address (as observed
4444 * by the other peer in binary format)
4445 * @param sender_address_len number of bytes in 'sender_address'
4448 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
4449 const struct GNUNET_PeerIdentity *peer,
4450 const char *sender_address,
4451 size_t sender_address_len)
4453 if (0 == memcmp (peer,
4455 sizeof (struct GNUNET_PeerIdentity)))
4457 /* PONG send to self, ignore */
4458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4459 "Receiving `%s' message from myself\n",
4463 #if DEBUG_TRANSPORT > 1
4464 /* we get tons of these that just get discarded, only log
4465 if we are quite verbose */
4466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4467 "Receiving `%s' message from `%4s'.\n", "PONG",
4470 GNUNET_STATISTICS_update (stats,
4471 gettext_noop ("# PONG messages received"),
4474 if (GNUNET_SYSERR !=
4475 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
4477 &check_pending_validation,
4480 /* This is *expected* to happen a lot since we send
4481 PONGs to *all* known addresses of the sender of
4482 the PING, so most likely we get multiple PONGs
4483 per PING, and all but the first PONG will end up
4484 here. So really we should not print anything here
4485 unless we want to be very, very verbose... */
4486 #if DEBUG_TRANSPORT > 2
4487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4488 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
4500 * Try to validate a neighbour's address by sending him our HELLO and a PING.
4502 * @param cls the 'struct ValidationEntry*'
4503 * @param neighbour neighbour to validate, NULL if validation failed
4506 transmit_hello_and_ping (void *cls,
4507 struct NeighbourList *neighbour)
4509 struct ValidationEntry *va = cls;
4510 struct ForeignAddressList *peer_address;
4511 struct TransportPingMessage ping;
4512 uint16_t hello_size;
4515 struct GNUNET_PeerIdentity id;
4518 GNUNET_CRYPTO_hash (&va->publicKey,
4519 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4521 if (neighbour == NULL)
4523 /* FIXME: stats... */
4524 GNUNET_break (GNUNET_OK ==
4525 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4528 abort_validation (NULL, NULL, va);
4531 neighbour->publicKey = va->publicKey;
4532 neighbour->public_key_valid = GNUNET_YES;
4533 peer_address = add_peer_address (neighbour,
4534 va->transport_name, NULL,
4535 (const void*) &va[1],
4537 if (peer_address == NULL)
4539 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4540 "Failed to add peer `%4s' for plugin `%s'\n",
4541 GNUNET_i2s (&neighbour->id),
4542 va->transport_name);
4543 GNUNET_break (GNUNET_OK ==
4544 GNUNET_CONTAINER_multihashmap_remove (validation_map,
4547 abort_validation (NULL, NULL, va);
4550 if (NULL == our_hello)
4552 hello_size = GNUNET_HELLO_size(our_hello);
4553 slen = strlen(va->transport_name) + 1;
4554 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
4555 message_buf = GNUNET_malloc(tsize);
4556 ping.challenge = htonl(va->challenge);
4557 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
4558 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
4559 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
4560 memcpy(message_buf, our_hello, hello_size);
4561 memcpy(&message_buf[hello_size],
4563 sizeof(struct TransportPingMessage));
4564 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
4567 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
4571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4572 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
4575 : a2s (va->transport_name,
4576 (const void*) &va[1], va->addrlen),
4578 GNUNET_i2s (&neighbour->id),
4579 "HELLO", hello_size,
4580 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
4583 GNUNET_STATISTICS_update (stats,
4584 gettext_noop ("# PING messages sent for initial validation"),
4587 transmit_to_peer (NULL, peer_address,
4588 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
4589 HELLO_VERIFICATION_TIMEOUT,
4591 GNUNET_YES, neighbour);
4592 GNUNET_free(message_buf);
4597 * Check if the given address is already being validated; if not,
4598 * append the given address to the list of entries that are being be
4599 * validated and initiate validation.
4601 * @param cls closure ('struct CheckHelloValidatedContext *')
4602 * @param tname name of the transport
4603 * @param expiration expiration time
4604 * @param addr the address
4605 * @param addrlen length of the address
4606 * @return GNUNET_OK (always)
4609 run_validation (void *cls,
4611 struct GNUNET_TIME_Absolute expiration,
4615 struct CheckHelloValidatedContext *chvc = cls;
4616 struct GNUNET_PeerIdentity id;
4617 struct TransportPlugin *tp;
4618 struct ValidationEntry *va;
4619 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4620 struct CheckAddressExistsClosure caec;
4621 struct OwnAddressList *oal;
4623 GNUNET_assert (addr != NULL);
4625 GNUNET_STATISTICS_update (stats,
4626 gettext_noop ("# peer addresses scheduled for validation"),
4629 tp = find_transport (tname);
4632 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
4633 GNUNET_ERROR_TYPE_BULK,
4635 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
4637 GNUNET_STATISTICS_update (stats,
4638 gettext_noop ("# peer addresses not validated (plugin not available)"),
4643 /* check if this is one of our own addresses */
4644 oal = tp->addresses;
4647 if ( (oal->addrlen == addrlen) &&
4648 (0 == memcmp (&oal[1],
4652 /* not plausible, this address is equivalent to our own address! */
4653 GNUNET_STATISTICS_update (stats,
4654 gettext_noop ("# peer addresses not validated (loopback)"),
4661 GNUNET_HELLO_get_key (chvc->hello, &pk);
4662 GNUNET_CRYPTO_hash (&pk,
4664 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4667 if (is_blacklisted(&id, tp))
4670 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4671 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
4679 caec.addrlen = addrlen;
4680 caec.session = NULL;
4682 caec.exists = GNUNET_NO;
4683 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4684 &check_address_exists,
4686 if (caec.exists == GNUNET_YES)
4688 /* During validation attempts we will likely trigger the other
4689 peer trying to validate our address which in turn will cause
4690 it to send us its HELLO, so we expect to hit this case rather
4691 frequently. Only print something if we are very verbose. */
4692 #if DEBUG_TRANSPORT > 1
4693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4694 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4695 a2s (tname, addr, addrlen),
4699 GNUNET_STATISTICS_update (stats,
4700 gettext_noop ("# peer addresses not validated (in progress)"),
4705 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4708 va->transport_name = GNUNET_strdup (tname);
4709 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4711 va->send_time = GNUNET_TIME_absolute_get();
4712 va->addr = (const void*) &va[1];
4713 memcpy (&va[1], addr, addrlen);
4714 va->addrlen = addrlen;
4715 GNUNET_HELLO_get_key (chvc->hello,
4717 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4718 &timeout_hello_validation,
4720 GNUNET_CONTAINER_multihashmap_put (validation_map,
4723 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4724 setup_peer_check_blacklist (&id, GNUNET_NO,
4725 &transmit_hello_and_ping,
4732 * Check if addresses in validated hello "h" overlap with
4733 * those in "chvc->hello" and validate the rest.
4735 * @param cls closure
4736 * @param peer id of the peer, NULL for last call
4737 * @param h hello message for the peer (can be NULL)
4738 * @param err_msg NULL if successful, otherwise contains error message
4741 check_hello_validated (void *cls,
4742 const struct GNUNET_PeerIdentity *peer,
4743 const struct GNUNET_HELLO_Message *h,
4744 const char *err_msg)
4746 struct CheckHelloValidatedContext *chvc = cls;
4747 struct GNUNET_HELLO_Message *plain_hello;
4748 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4749 struct GNUNET_PeerIdentity target;
4750 struct NeighbourList *n;
4752 if (err_msg != NULL)
4755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4756 _("Error in communication with PEERINFO service: %s\n"),
4764 GNUNET_STATISTICS_update (stats,
4765 gettext_noop ("# outstanding peerinfo iterate requests"),
4769 if (GNUNET_NO == chvc->hello_known)
4771 /* notify PEERINFO about the peer now, so that we at least
4772 have the public key if some other component needs it */
4773 GNUNET_HELLO_get_key (chvc->hello, &pk);
4774 GNUNET_CRYPTO_hash (&pk,
4775 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4776 &target.hashPubKey);
4777 plain_hello = GNUNET_HELLO_create (&pk,
4780 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4781 GNUNET_free (plain_hello);
4782 #if DEBUG_TRANSPORT_HELLO
4783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4784 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4786 GNUNET_i2s (&target));
4788 GNUNET_STATISTICS_update (stats,
4789 gettext_noop ("# new HELLOs requiring full validation"),
4792 GNUNET_HELLO_iterate_addresses (chvc->hello,
4799 GNUNET_STATISTICS_update (stats,
4800 gettext_noop ("# duplicate HELLO (peer known)"),
4805 if (chvc->ve_count == 0)
4807 GNUNET_CONTAINER_DLL_remove (chvc_head,
4816 #if DEBUG_TRANSPORT_HELLO
4817 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4818 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4822 chvc->hello_known = GNUNET_YES;
4823 n = find_neighbour (peer);
4826 #if DEBUG_TRANSPORT_HELLO
4827 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4828 "Calling hello_iterate_addresses for %s!\n",
4831 GNUNET_HELLO_iterate_addresses (h,
4833 &add_to_foreign_address_list,
4835 try_transmission_to_peer (n);
4839 #if DEBUG_TRANSPORT_HELLO
4840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4841 "No existing neighbor record for %s!\n",
4844 GNUNET_STATISTICS_update (stats,
4845 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4849 GNUNET_STATISTICS_update (stats,
4850 gettext_noop ("# HELLO validations (update case)"),
4853 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4855 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4862 * Process HELLO-message.
4864 * @param plugin transport involved, may be NULL
4865 * @param message the actual message
4866 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4869 process_hello (struct TransportPlugin *plugin,
4870 const struct GNUNET_MessageHeader *message)
4873 struct GNUNET_PeerIdentity target;
4874 const struct GNUNET_HELLO_Message *hello;
4875 struct CheckHelloValidatedContext *chvc;
4876 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4877 struct NeighbourList *n;
4878 #if DEBUG_TRANSPORT_HELLO > 2
4882 hsize = ntohs (message->size);
4883 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4884 (hsize < sizeof (struct GNUNET_MessageHeader)))
4887 return GNUNET_SYSERR;
4889 GNUNET_STATISTICS_update (stats,
4890 gettext_noop ("# HELLOs received for validation"),
4894 hello = (const struct GNUNET_HELLO_Message *) message;
4895 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4897 #if DEBUG_TRANSPORT_HELLO
4898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4899 "Unable to get public key from `%s' for `%4s'!\n",
4901 GNUNET_i2s (&target));
4903 GNUNET_break_op (0);
4904 return GNUNET_SYSERR;
4906 GNUNET_CRYPTO_hash (&publicKey,
4907 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4908 &target.hashPubKey);
4910 #if DEBUG_TRANSPORT_HELLO
4911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4912 "Received `%s' message for `%4s'\n",
4914 GNUNET_i2s (&target));
4916 if (0 == memcmp (&my_identity,
4918 sizeof (struct GNUNET_PeerIdentity)))
4920 GNUNET_STATISTICS_update (stats,
4921 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4926 n = find_neighbour (&target);
4928 (! n->public_key_valid) )
4930 GNUNET_HELLO_get_key (hello, &n->publicKey);
4931 n->public_key_valid = GNUNET_YES;
4934 /* check if load is too high before doing expensive stuff */
4935 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4937 GNUNET_STATISTICS_update (stats,
4938 gettext_noop ("# HELLOs ignored due to high load"),
4941 #if DEBUG_TRANSPORT_HELLO
4942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4943 "Ignoring `%s' for `%4s', load too high.\n",
4945 GNUNET_i2s (&target));
4952 while (NULL != chvc)
4954 if (GNUNET_HELLO_equals (hello,
4956 GNUNET_TIME_absolute_get ()).abs_value > 0)
4958 #if DEBUG_TRANSPORT_HELLO > 2
4959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4960 "Received duplicate `%s' message for `%4s'; ignored\n",
4962 GNUNET_i2s (&target));
4964 return GNUNET_OK; /* validation already pending */
4966 if (GNUNET_HELLO_size (hello) == GNUNET_HELLO_size (chvc->hello))
4967 GNUNET_break (0 != memcmp (hello, chvc->hello,
4968 GNUNET_HELLO_size(hello)));
4973 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4974 if ((NULL != temp_neighbor))
4976 fprintf(stderr, "Already know peer, ignoring hello\n");
4981 #if DEBUG_TRANSPORT_HELLO > 2
4984 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4987 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4990 GNUNET_i2s (&target),
4992 GNUNET_HELLO_size(hello));
4997 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4999 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
5000 memcpy (&chvc[1], hello, hsize);
5001 GNUNET_CONTAINER_DLL_insert (chvc_head,
5004 /* finally, check if HELLO was previously validated
5005 (continuation will then schedule actual validation) */
5006 GNUNET_STATISTICS_update (stats,
5007 gettext_noop ("# peerinfo process hello iterate requests"),
5010 GNUNET_STATISTICS_update (stats,
5011 gettext_noop ("# outstanding peerinfo iterate requests"),
5014 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
5016 HELLO_VERIFICATION_TIMEOUT,
5017 &check_hello_validated, chvc);
5023 * The peer specified by the given neighbour has timed-out or a plugin
5024 * has disconnected. We may either need to do nothing (other plugins
5025 * still up), or trigger a full disconnect and clean up. This
5026 * function updates our state and does the necessary notifications.
5027 * Also notifies our clients that the neighbour is now officially
5030 * @param n the neighbour list entry for the peer
5031 * @param check GNUNET_YES to check if ALL addresses for this peer
5032 * are gone, GNUNET_NO to force a disconnect of the peer
5033 * regardless of whether other addresses exist.
5036 disconnect_neighbour (struct NeighbourList *n, int check)
5038 struct ReadyList *rpos;
5039 struct NeighbourList *npos;
5040 struct NeighbourList *nprev;
5041 struct MessageQueue *mq;
5042 struct ForeignAddressList *peer_addresses;
5043 struct ForeignAddressList *peer_pos;
5045 if (GNUNET_YES == check)
5048 while (NULL != rpos)
5050 peer_addresses = rpos->addresses;
5051 while (peer_addresses != NULL)
5053 // Do not disconnect if: an address is connected or an inbound address exists
5054 if ((GNUNET_YES == peer_addresses->connected) || (peer_addresses->addrlen == 0))
5057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5058 "NOT Disconnecting from `%4s', still have live address `%s'!\n",
5059 GNUNET_i2s (&n->id),
5060 a2s (peer_addresses->ready_list->plugin->short_name,
5061 peer_addresses->addr,
5062 peer_addresses->addrlen));
5064 return; /* still connected */
5066 peer_addresses = peer_addresses->next;
5072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5073 "Disconnecting from `%4s'\n",
5074 GNUNET_i2s (&n->id));
5076 /* remove n from neighbours list */
5079 while ((npos != NULL) && (npos != n))
5084 GNUNET_assert (npos != NULL);
5086 neighbours = n->next;
5088 nprev->next = n->next;
5090 /* notify all clients about disconnect */
5091 if (GNUNET_YES == n->received_pong)
5092 notify_clients_disconnect (&n->id);
5094 /* clean up all plugins, cancel connections and pending transmissions */
5095 while (NULL != (rpos = n->plugins))
5097 n->plugins = rpos->next;
5098 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
5099 while (rpos->addresses != NULL)
5101 peer_pos = rpos->addresses;
5102 rpos->addresses = peer_pos->next;
5103 if (peer_pos->connected == GNUNET_YES)
5104 GNUNET_STATISTICS_update (stats,
5105 gettext_noop ("# connected addresses"),
5108 if (GNUNET_YES == peer_pos->validated)
5109 GNUNET_STATISTICS_update (stats,
5110 gettext_noop ("# peer addresses considered valid"),
5113 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
5115 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
5116 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
5118 GNUNET_free(peer_pos->ressources);
5119 peer_pos->ressources = NULL;
5120 GNUNET_free(peer_pos->quality);
5121 peer_pos->ressources = NULL;
5122 GNUNET_free(peer_pos);
5123 ats->stat.recreate_problem = GNUNET_YES;
5128 /* free all messages on the queue */
5129 while (NULL != (mq = n->messages_head))
5131 GNUNET_STATISTICS_update (stats,
5132 gettext_noop ("# bytes in message queue for other peers"),
5133 - (int64_t) mq->message_buf_size,
5135 GNUNET_STATISTICS_update (stats,
5136 gettext_noop ("# bytes discarded due to disconnect"),
5137 mq->message_buf_size,
5139 GNUNET_CONTAINER_DLL_remove (n->messages_head,
5142 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5144 sizeof(struct GNUNET_PeerIdentity)));
5148 while (NULL != (mq = n->cont_head))
5151 GNUNET_CONTAINER_DLL_remove (n->cont_head,
5154 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
5156 sizeof(struct GNUNET_PeerIdentity)));
5160 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
5162 GNUNET_SCHEDULER_cancel (n->timeout_task);
5163 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
5165 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
5167 GNUNET_SCHEDULER_cancel (n->retry_task);
5168 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
5170 if (n->piter != NULL)
5172 GNUNET_PEERINFO_iterate_cancel (n->piter);
5173 GNUNET_STATISTICS_update (stats,
5174 gettext_noop ("# outstanding peerinfo iterate requests"),
5179 /* finally, free n itself */
5180 GNUNET_STATISTICS_update (stats,
5181 gettext_noop ("# active neighbours"),
5184 GNUNET_free_non_null (n->pre_connect_message_buffer);
5190 * We have received a PING message from someone. Need to send a PONG message
5191 * in response to the peer by any means necessary.
5194 handle_ping (void *cls, const struct GNUNET_MessageHeader *message,
5195 const struct GNUNET_PeerIdentity *peer,
5196 struct Session *session,
5197 const char *sender_address,
5198 uint16_t sender_address_len)
5200 struct TransportPlugin *plugin = cls;
5201 struct SessionHeader *session_header = (struct SessionHeader*) session;
5202 struct TransportPingMessage *ping;
5203 struct TransportPongMessage *pong;
5204 struct NeighbourList *n;
5205 struct ReadyList *rl;
5206 struct ForeignAddressList *fal;
5207 struct OwnAddressList *oal;
5213 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
5215 GNUNET_break_op (0);
5216 return GNUNET_SYSERR;
5219 ping = (struct TransportPingMessage *) message;
5220 if (0 != memcmp (&ping->target,
5221 plugin->env.my_identity,
5222 sizeof (struct GNUNET_PeerIdentity)))
5225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5226 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
5228 (sender_address != NULL)
5229 ? a2s (plugin->short_name,
5230 (const struct sockaddr *)sender_address,
5233 GNUNET_i2s (&ping->target));
5235 return GNUNET_SYSERR;
5238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5239 "Processing `%s' from `%s'\n",
5241 (sender_address != NULL)
5242 ? a2s (plugin->short_name,
5243 (const struct sockaddr *)sender_address,
5247 GNUNET_STATISTICS_update (stats,
5248 gettext_noop ("# PING messages received"),
5251 addr = (const char*) &ping[1];
5252 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
5253 slen = strlen (plugin->short_name) + 1;
5256 /* peer wants to confirm that we have an outbound connection to him */
5257 if (session == NULL)
5259 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5260 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
5262 return GNUNET_SYSERR;
5264 /* FIXME-urg: the use of 'sender_address' in the code below is doubly-wrong:
5265 1) it is NULL when we need to have a real value
5266 2) it is documented to be the address of the sender (source-IP), where
5267 what we actually want is our LISTEN IP (what we 'bound' to); which we don't even
5270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5271 "Creating PONG indicating that we received a connection at our address `%s' from `%s'.\n",
5272 a2s (plugin->short_name,
5274 sender_address_len),
5277 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5278 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
5279 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5280 pong->purpose.size =
5281 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5283 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5284 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
5285 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
5286 pong->challenge = ping->challenge;
5287 pong->addrlen = htonl(sender_address_len + slen);
5290 sizeof(struct GNUNET_PeerIdentity));
5294 if ((sender_address!=NULL) && (sender_address_len > 0))
5295 memcpy (&((char*)&pong[1])[slen],
5297 sender_address_len);
5298 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
5300 /* create / update cached sig */
5302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5303 "Creating PONG signature to indicate active connection.\n");
5305 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5306 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5307 GNUNET_assert (GNUNET_OK ==
5308 GNUNET_CRYPTO_rsa_sign (my_private_key,
5310 &session_header->pong_signature));
5314 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
5316 memcpy (&pong->signature,
5317 &session_header->pong_signature,
5318 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5324 /* peer wants to confirm that this is one of our addresses */
5328 plugin->api->check_address (plugin->api->cls,
5332 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5333 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
5334 a2s (plugin->short_name,
5339 oal = plugin->addresses;
5342 if ( (oal->addrlen == alen) &&
5349 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
5350 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
5351 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
5352 pong->purpose.size =
5353 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
5355 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
5356 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
5357 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
5358 pong->challenge = ping->challenge;
5359 pong->addrlen = htonl(alen + slen);
5362 sizeof(struct GNUNET_PeerIdentity));
5363 memcpy (&pong[1], plugin->short_name, slen);
5364 memcpy (&((char*)&pong[1])[slen], addr, alen);
5365 if ( (oal != NULL) &&
5366 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
5368 /* create / update cached sig */
5370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5371 "Creating PONG signature to indicate ownership.\n");
5373 oal->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
5374 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5375 GNUNET_assert (GNUNET_OK ==
5376 GNUNET_CRYPTO_rsa_sign (my_private_key,
5378 &oal->pong_signature));
5379 memcpy (&pong->signature,
5380 &oal->pong_signature,
5381 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5383 else if (oal == NULL)
5385 /* not using cache (typically DV-only) */
5386 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
5387 GNUNET_assert (GNUNET_OK ==
5388 GNUNET_CRYPTO_rsa_sign (my_private_key,
5394 /* can used cached version */
5395 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
5396 memcpy (&pong->signature,
5397 &oal->pong_signature,
5398 sizeof (struct GNUNET_CRYPTO_RsaSignature));
5401 n = find_neighbour(peer);
5402 GNUNET_assert (n != NULL);
5403 did_pong = GNUNET_NO;
5404 /* first try reliable response transmission */
5408 fal = rl->addresses;
5411 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
5414 ntohs (pong->header.size),
5415 TRANSPORT_PONG_PRIORITY,
5416 HELLO_VERIFICATION_TIMEOUT,
5423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5424 "Transmitted PONG to `%s' via reliable mechanism\n",
5427 GNUNET_STATISTICS_update (stats,
5428 gettext_noop ("# PONGs unicast via reliable transport"),
5434 did_pong = GNUNET_YES;
5439 /* no reliable method found, do multicast */
5440 GNUNET_STATISTICS_update (stats,
5441 gettext_noop ("# PONGs multicast to all available addresses"),
5447 fal = rl->addresses;
5450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5451 "Transmitting PONG to `%s' via unreliable mechanism `%s':%s\n",
5453 a2s (rl->plugin->short_name,
5456 rl->plugin->short_name);
5457 transmit_to_peer(NULL, fal,
5458 TRANSPORT_PONG_PRIORITY,
5459 HELLO_VERIFICATION_TIMEOUT,
5461 ntohs(pong->header.size),
5464 did_pong = GNUNET_YES;
5470 if (GNUNET_YES != did_pong)
5471 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5472 _("Could not send PONG to `%s': no address available\n"),
5479 * Function called by the plugin for each received message. Update
5480 * data volumes, possibly notify plugins about reducing the rate at
5481 * which they read from the socket and generally forward to our
5484 * @param cls the "struct TransportPlugin *" we gave to the plugin
5485 * @param peer (claimed) identity of the other peer
5486 * @param message the message, NULL if we only care about
5487 * learning about the delay until we should receive again
5488 * @param ats_data information for automatic transport selection
5489 * @param ats_count number of elements in ats not including 0-terminator
5490 * @param session identifier used for this session (can be NULL)
5491 * @param sender_address binary address of the sender (if observed)
5492 * @param sender_address_len number of bytes in sender_address
5493 * @return how long in ms the plugin should wait until receiving more data
5494 * (plugins that do not support this, can ignore the return value)
5496 static struct GNUNET_TIME_Relative
5497 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
5498 const struct GNUNET_MessageHeader *message,
5499 const struct GNUNET_TRANSPORT_ATS_Information *ats_data,
5501 struct Session *session,
5502 const char *sender_address,
5503 uint16_t sender_address_len)
5505 struct TransportPlugin *plugin = cls;
5506 struct ReadyList *service_context;
5507 struct ForeignAddressList *peer_address;
5509 struct NeighbourList *n;
5510 struct GNUNET_TIME_Relative ret;
5514 if (0 == memcmp (peer,
5516 sizeof (struct GNUNET_PeerIdentity)))
5518 /* refuse to receive from myself */
5520 return GNUNET_TIME_UNIT_FOREVER_REL;
5522 if (is_blacklisted (peer, plugin))
5523 return GNUNET_TIME_UNIT_FOREVER_REL;
5524 n = find_neighbour (peer);
5526 n = setup_new_neighbour (peer, GNUNET_YES);
5527 service_context = n->plugins;
5528 while ((service_context != NULL) && (plugin != service_context->plugin))
5529 service_context = service_context->next;
5530 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
5531 peer_address = NULL;
5534 for (c=0; c<ats_count; c++)
5535 if (ntohl(ats_data[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
5536 distance = ntohl(ats_data[c].value);
5538 /* notify ATS about incoming data */
5539 //ats_notify_ats_data(peer, ats_data);
5541 if (message != NULL)
5543 if ( (session != NULL) ||
5544 (sender_address != NULL) )
5545 peer_address = add_peer_address (n,
5549 sender_address_len);
5550 if (peer_address != NULL)
5552 update_addr_ats(peer_address, ats_data, ats_count);
5553 update_addr_value(peer_address, distance, GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5555 peer_address->distance = distance;
5556 if (GNUNET_YES == peer_address->validated)
5557 mark_address_connected (peer_address);
5558 peer_address->timeout
5559 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5560 schedule_next_ping (peer_address);
5562 /* update traffic received amount ... */
5563 msize = ntohs (message->size);
5565 GNUNET_STATISTICS_update (stats,
5566 gettext_noop ("# bytes received from other peers"),
5569 n->distance = distance;
5571 GNUNET_TIME_relative_to_absolute
5572 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
5573 GNUNET_SCHEDULER_cancel (n->timeout_task);
5575 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
5576 &neighbour_timeout_task, n);
5577 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
5579 /* dropping message due to frequent inbound volume violations! */
5580 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
5581 GNUNET_ERROR_TYPE_BULK,
5583 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
5584 n->in_tracker.available_bytes_per_s__,
5585 n->quota_violation_count);
5586 GNUNET_STATISTICS_update (stats,
5587 gettext_noop ("# bandwidth quota violations by other peers"),
5590 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
5592 if ((ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_ATS) &&
5593 (ntohs(message->size) == (sizeof (struct GNUNET_MessageHeader) + sizeof (uint32_t))))
5595 uint32_t value = ntohl(*((uint32_t *) &message[1]));
5596 //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "GNUNET_MESSAGE_TYPE_TRANSPORT_ATS: %i \n", value);
5597 /* Force ressource and quality update */
5600 ats->stat.modified_resources = GNUNET_YES;
5601 ats->stat.modified_quality = GNUNET_YES;
5603 /* Force cost update */
5605 ats->stat.modified_resources = GNUNET_YES;
5606 /* Force quality update */
5608 ats->stat.modified_quality = GNUNET_YES;
5609 /* Force full rebuild */
5611 ats->stat.recreate_problem = GNUNET_YES;
5615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5616 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
5617 ntohs (message->type),
5618 ntohs (message->size),
5621 switch (ntohs (message->type))
5623 case GNUNET_MESSAGE_TYPE_HELLO:
5624 GNUNET_STATISTICS_update (stats,
5625 gettext_noop ("# HELLO messages received from other peers"),
5628 process_hello (plugin, message);
5630 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
5631 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
5632 if (! n->received_pong)
5633 transmit_plain_ping (n);
5635 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
5636 handle_pong (plugin, message, peer, sender_address, sender_address_len);
5638 case GNUNET_MESSAGE_TYPE_TRANSPORT_ATS:
5641 handle_payload_message (message, n);
5645 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
5646 if (ret.rel_value > 0)
5649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5650 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
5651 (unsigned long long) n->in_tracker.consumption_since_last_update__,
5652 (unsigned int) n->in_tracker.available_bytes_per_s__,
5653 (unsigned long long) ret.rel_value);
5655 GNUNET_STATISTICS_update (stats,
5656 gettext_noop ("# ms throttling suggested"),
5657 (int64_t) ret.rel_value,
5664 * Handle START-message. This is the first message sent to us
5665 * by any client which causes us to add it to our list.
5667 * @param cls closure (always NULL)
5668 * @param client identification of the client
5669 * @param message the actual message
5672 handle_start (void *cls,
5673 struct GNUNET_SERVER_Client *client,
5674 const struct GNUNET_MessageHeader *message)
5676 const struct StartMessage *start;
5677 struct TransportClient *c;
5678 struct ConnectInfoMessage * cim;
5679 struct NeighbourList *n;
5683 start = (const struct StartMessage*) message;
5685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5686 "Received `%s' request from client\n", "START");
5691 if (c->client == client)
5693 /* client already on our list! */
5695 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5700 if ( (GNUNET_NO != ntohl (start->do_check)) &&
5701 (0 != memcmp (&start->self,
5703 sizeof (struct GNUNET_PeerIdentity))) )
5705 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5706 _("Rejecting control connection from peer `%s', which is not me!\n"),
5707 GNUNET_i2s (&start->self));
5708 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5711 c = GNUNET_malloc (sizeof (struct TransportClient));
5715 if (our_hello != NULL)
5718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5719 "Sending our own `%s' to new client\n", "HELLO");
5721 transmit_to_client (c,
5722 (const struct GNUNET_MessageHeader *) our_hello,
5724 /* tell new client about all existing connections */
5726 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
5727 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
5731 cim = GNUNET_malloc (size);
5732 cim->header.size = htons (size);
5733 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
5734 cim->ats_count = htonl(ats_count);
5735 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
5736 (&(cim->ats))[2].value = htonl (0);
5740 if (GNUNET_YES == n->received_pong)
5742 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
5743 (&(cim->ats))[0].value = htonl (n->distance);
5744 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
5745 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
5747 transmit_to_client (c, &cim->header, GNUNET_NO);
5753 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5758 * Handle HELLO-message.
5760 * @param cls closure (always NULL)
5761 * @param client identification of the client
5762 * @param message the actual message
5765 handle_hello (void *cls,
5766 struct GNUNET_SERVER_Client *client,
5767 const struct GNUNET_MessageHeader *message)
5771 GNUNET_STATISTICS_update (stats,
5772 gettext_noop ("# HELLOs received from clients"),
5775 ret = process_hello (NULL, message);
5776 GNUNET_SERVER_receive_done (client, ret);
5781 * Closure for 'transmit_client_message'; followed by
5782 * 'msize' bytes of the actual message.
5784 struct TransmitClientMessageContext
5787 * Client on whom's behalf we are sending.
5789 struct GNUNET_SERVER_Client *client;
5792 * Timeout for the transmission.
5794 struct GNUNET_TIME_Absolute timeout;
5802 * Size of the message in bytes.
5809 * Schedule transmission of a message we got from a client to a peer.
5811 * @param cls the 'struct TransmitClientMessageContext*'
5812 * @param n destination, or NULL on error (in that case, drop the message)
5815 transmit_client_message (void *cls,
5816 struct NeighbourList *n)
5818 struct TransmitClientMessageContext *tcmc = cls;
5819 struct TransportClient *tc;
5822 while ((tc != NULL) && (tc->client != tcmc->client))
5827 transmit_to_peer (tc, NULL, tcmc->priority,
5828 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5830 tcmc->msize, GNUNET_NO, n);
5832 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5833 GNUNET_SERVER_client_drop (tcmc->client);
5839 * Handle SEND-message.
5841 * @param cls closure (always NULL)
5842 * @param client identification of the client
5843 * @param message the actual message
5846 handle_send (void *cls,
5847 struct GNUNET_SERVER_Client *client,
5848 const struct GNUNET_MessageHeader *message)
5850 const struct OutboundMessage *obm;
5851 const struct GNUNET_MessageHeader *obmm;
5852 struct TransmitClientMessageContext *tcmc;
5856 size = ntohs (message->size);
5858 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5861 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5864 GNUNET_STATISTICS_update (stats,
5865 gettext_noop ("# payload received for other peers"),
5868 obm = (const struct OutboundMessage *) message;
5869 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5870 msize = size - sizeof (struct OutboundMessage);
5872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5873 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5874 "SEND", GNUNET_i2s (&obm->peer),
5878 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5879 tcmc->client = client;
5880 tcmc->priority = ntohl (obm->priority);
5881 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5882 tcmc->msize = msize;
5883 /* FIXME: this memcpy can be up to 7% of our total runtime */
5884 memcpy (&tcmc[1], obmm, msize);
5885 GNUNET_SERVER_client_keep (client);
5886 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5887 &transmit_client_message,
5893 * Handle request connect message
5895 * @param cls closure (always NULL)
5896 * @param client identification of the client
5897 * @param message the actual message
5900 handle_request_connect (void *cls,
5901 struct GNUNET_SERVER_Client *client,
5902 const struct GNUNET_MessageHeader *message)
5904 const struct TransportRequestConnectMessage *trcm =
5905 (const struct TransportRequestConnectMessage *) message;
5907 GNUNET_STATISTICS_update (stats,
5908 gettext_noop ("# REQUEST CONNECT messages received"),
5912 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
5913 "Received a request connect message for peer `%s'\n",
5914 GNUNET_i2s(&trcm->peer));
5916 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5918 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5923 * Handle SET_QUOTA-message.
5925 * @param cls closure (always NULL)
5926 * @param client identification of the client
5927 * @param message the actual message
5930 handle_set_quota (void *cls,
5931 struct GNUNET_SERVER_Client *client,
5932 const struct GNUNET_MessageHeader *message)
5934 const struct QuotaSetMessage *qsm =
5935 (const struct QuotaSetMessage *) message;
5936 struct NeighbourList *n;
5938 GNUNET_STATISTICS_update (stats,
5939 gettext_noop ("# SET QUOTA messages received"),
5942 n = find_neighbour (&qsm->peer);
5945 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5946 GNUNET_STATISTICS_update (stats,
5947 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5954 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5956 (unsigned int) ntohl (qsm->quota.value__),
5957 (unsigned int) n->in_tracker.available_bytes_per_s__,
5958 GNUNET_i2s (&qsm->peer));
5960 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5962 if (0 == ntohl (qsm->quota.value__))
5965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5966 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5969 GNUNET_STATISTICS_update (stats,
5970 gettext_noop ("# disconnects due to quota of 0"),
5973 disconnect_neighbour (n, GNUNET_NO);
5975 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5980 * Take the given address and append it to the set of results sent back to
5983 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5984 * @param address the resolved name, NULL to indicate the last response
5987 transmit_address_to_client (void *cls, const char *address)
5989 struct GNUNET_SERVER_TransmitContext *tc = cls;
5992 if (NULL != address)
5994 slen = strlen (address) + 1;
5995 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5996 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6000 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
6006 * Handle AddressLookup-message.
6008 * @param cls closure (always NULL)
6009 * @param client identification of the client
6010 * @param message the actual message
6013 handle_address_lookup (void *cls,
6014 struct GNUNET_SERVER_Client *client,
6015 const struct GNUNET_MessageHeader *message)
6017 const struct AddressLookupMessage *alum;
6018 struct TransportPlugin *lsPlugin;
6019 const char *nameTransport;
6020 const char *address;
6022 struct GNUNET_SERVER_TransmitContext *tc;
6023 struct GNUNET_TIME_Absolute timeout;
6024 struct GNUNET_TIME_Relative rtimeout;
6027 size = ntohs (message->size);
6028 if (size < sizeof (struct AddressLookupMessage))
6030 GNUNET_break_op (0);
6031 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6034 alum = (const struct AddressLookupMessage *) message;
6035 uint32_t addressLen = ntohl (alum->addrlen);
6036 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
6038 GNUNET_break_op (0);
6039 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6042 address = (const char *) &alum[1];
6043 nameTransport = (const char *) &address[addressLen];
6045 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
6047 GNUNET_break_op (0);
6048 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6051 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
6052 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
6053 numeric = ntohl (alum->numeric_only);
6054 lsPlugin = find_transport (nameTransport);
6055 if (NULL == lsPlugin)
6057 tc = GNUNET_SERVER_transmit_context_create (client);
6058 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
6059 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
6060 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
6063 GNUNET_SERVER_disable_receive_done_warning (client);
6064 tc = GNUNET_SERVER_transmit_context_create (client);
6065 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
6067 address, addressLen,
6070 &transmit_address_to_client, tc);
6075 * Setup the environment for this plugin.
6078 create_environment (struct TransportPlugin *plug)
6080 plug->env.cfg = cfg;
6081 plug->env.my_identity = &my_identity;
6082 plug->env.our_hello = &our_hello;
6083 plug->env.cls = plug;
6084 plug->env.receive = &plugin_env_receive;
6085 plug->env.notify_address = &plugin_env_notify_address;
6086 plug->env.session_end = &plugin_env_session_end;
6087 plug->env.max_connections = max_connect_per_transport;
6088 plug->env.stats = stats;
6093 * Start the specified transport (load the plugin).
6096 start_transport (struct GNUNET_SERVER_Handle *server,
6099 struct TransportPlugin *plug;
6102 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6103 _("Loading `%s' transport plugin\n"), name);
6104 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
6105 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
6106 create_environment (plug);
6107 plug->short_name = GNUNET_strdup (name);
6108 plug->lib_name = libname;
6109 plug->next = plugins;
6111 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
6112 if (plug->api == NULL)
6114 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6115 _("Failed to load transport plugin for `%s'\n"), name);
6116 GNUNET_free (plug->short_name);
6117 plugins = plug->next;
6118 GNUNET_free (libname);
6125 * Called whenever a client is disconnected. Frees our
6126 * resources associated with that client.
6128 * @param cls closure
6129 * @param client identification of the client
6132 client_disconnect_notification (void *cls,
6133 struct GNUNET_SERVER_Client *client)
6135 struct TransportClient *pos;
6136 struct TransportClient *prev;
6137 struct ClientMessageQueueEntry *mqe;
6138 struct Blacklisters *bl;
6139 struct BlacklistCheck *bc;
6144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
6145 "Client disconnected, cleaning up.\n");
6147 /* clean up blacklister */
6151 if (bl->client == client)
6156 if (bc->bl_pos == bl)
6158 bc->bl_pos = bl->next;
6161 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
6164 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
6165 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
6171 GNUNET_CONTAINER_DLL_remove (bl_head,
6174 GNUNET_SERVER_client_drop (bl->client);
6180 /* clean up 'normal' clients */
6183 while ((pos != NULL) && (pos->client != client))
6190 while (NULL != (mqe = pos->message_queue_head))
6192 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
6193 pos->message_queue_tail,
6195 pos->message_count--;
6199 clients = pos->next;
6201 prev->next = pos->next;
6202 if (GNUNET_YES == pos->tcs_pending)
6207 if (pos->th != NULL)
6209 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
6212 GNUNET_break (0 == pos->message_count);
6218 * Function called when the service shuts down. Unloads our plugins
6219 * and cancels pending validations.
6221 * @param cls closure, unused
6222 * @param tc task context (unused)
6225 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6227 struct TransportPlugin *plug;
6228 struct OwnAddressList *al;
6229 struct CheckHelloValidatedContext *chvc;
6231 shutdown_in_progress = GNUNET_YES;
6232 while (neighbours != NULL)
6235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6236 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
6239 disconnect_neighbour (neighbours, GNUNET_NO);
6242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6243 "Transport service is unloading plugins...\n");
6245 while (NULL != (plug = plugins))
6247 plugins = plug->next;
6248 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
6250 GNUNET_SCHEDULER_cancel (plug->address_update_task);
6251 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
6253 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
6254 GNUNET_free (plug->lib_name);
6255 GNUNET_free (plug->short_name);
6256 while (NULL != (al = plug->addresses))
6258 plug->addresses = al->next;
6263 if (my_private_key != NULL)
6264 GNUNET_CRYPTO_rsa_key_free (my_private_key);
6265 GNUNET_free_non_null (our_hello);
6267 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
6270 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
6271 validation_map = NULL;
6275 /* free 'chvc' data structure */
6276 while (NULL != (chvc = chvc_head))
6278 chvc_head = chvc->next;
6279 if (chvc->piter != NULL)
6281 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
6282 GNUNET_STATISTICS_update (stats,
6283 gettext_noop ("# outstanding peerinfo iterate requests"),
6290 GNUNET_assert (chvc->ve_count == 0);
6297 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
6300 if (peerinfo != NULL)
6302 GNUNET_PEERINFO_disconnect (peerinfo);
6305 /* Can we assume those are gone by now, or do we need to clean up
6307 GNUNET_break (bl_head == NULL);
6308 GNUNET_break (bc_head == NULL);
6312 static int ats_evaluate_results (int result, int solution, char * problem)
6314 int cont = GNUNET_NO;
6315 #if DEBUG_ATS || VERBOSE_ATS
6316 int error_kind = GNUNET_ERROR_TYPE_DEBUG;
6319 error_kind = GNUNET_ERROR_TYPE_ERROR;
6323 case GNUNET_SYSERR : /* GNUNET problem, not GLPK related */
6324 #if DEBUG_ATS || VERBOSE_ATS
6325 GNUNET_log (error_kind, "%s , GLPK solving not executed\n", problem);
6328 case GLP_ESTOP : /* search terminated by application */
6329 #if DEBUG_ATS || VERBOSE_ATS
6330 GNUNET_log (error_kind, "%s , Search terminated by application\n", problem);
6333 case GLP_EITLIM : /* iteration limit exceeded */
6334 #if DEBUG_ATS || VERBOSE_ATS
6335 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Iteration limit exceeded\n", problem);
6338 case GLP_ETMLIM : /* time limit exceeded */
6339 #if DEBUG_ATS || VERBOSE_ATS
6340 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s Time limit exceeded\n", problem);
6343 case GLP_ENOPFS : /* no primal feasible solution */
6344 case GLP_ENODFS : /* no dual feasible solution */
6345 #if DEBUG_ATS || VERBOSE_ATS
6346 GNUNET_log (error_kind, "%s No feasible solution\n", problem);
6350 case GLP_EBADB : /* invalid basis */
6351 case GLP_ESING : /* singular matrix */
6352 case GLP_ECOND : /* ill-conditioned matrix */
6353 case GLP_EBOUND : /* invalid bounds */
6354 case GLP_EFAIL : /* solver failed */
6355 case GLP_EOBJLL : /* objective lower limit reached */
6356 case GLP_EOBJUL : /* objective upper limit reached */
6357 case GLP_EROOT : /* root LP optimum not provided */
6358 #if DEBUG_ATS || VERBOSE_ATS
6359 GNUNET_log (error_kind, "%s Invalid Input data: %i\n", problem, result);
6364 #if DEBUG_ATS || VERBOSE_ATS
6365 GNUNET_log (error_kind, "%s Problem has been solved\n", problem);
6372 #if DEBUG_ATS || VERBOSE_ATS
6373 GNUNET_log (error_kind, "%s solution is undefined\n", problem);
6377 #if DEBUG_ATS || VERBOSE_ATS
6378 GNUNET_log (error_kind, "%s solution is optimal\n", problem);
6383 #if DEBUG_ATS || VERBOSE_ATS
6384 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"));
6389 #if DEBUG_ATS || VERBOSE_ATS
6390 GNUNET_log (error_kind, "%s problem has no %sfeasible solution\n", problem, (0==strcmp(problem,"LP")?"":"integer "));
6394 #if DEBUG_ATS || VERBOSE_ATS
6395 GNUNET_log (error_kind, "%s problem is infeasible \n", problem);
6399 #if DEBUG_ATS || VERBOSE_ATS
6400 GNUNET_log (error_kind, "%s problem is unbounded \n", problem);
6408 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)
6410 int result = GNUNET_SYSERR;
6411 int lp_solution = GNUNET_SYSERR;
6412 int mlp_solution = GNUNET_SYSERR;
6416 glp_init_smcp(&opt_lp);
6418 opt_lp.msg_lev = GLP_MSG_ALL;
6420 opt_lp.msg_lev = GLP_MSG_OFF;
6423 // setting iteration limit
6424 opt_lp.it_lim = max_it;
6426 opt_lp.tm_lim = max_dur;
6428 if (ats->stat.recreate_problem == GNUNET_YES)
6429 opt_lp.presolve = GLP_ON;
6430 result = glp_simplex(ats->prob, &opt_lp);
6431 lp_solution = glp_get_status (ats->prob);
6433 if ((result == GLP_ETMLIM) || (result == GLP_EITLIM))
6435 ats->stat.valid = GNUNET_NO;
6436 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ATS exceeded time or iteration limit!\n");
6440 if (ats_evaluate_results(result, lp_solution, "LP") == GNUNET_YES)
6442 stat->valid = GNUNET_YES;
6446 ats->stat.simplex_rerun_required = GNUNET_YES;
6447 opt_lp.presolve = GLP_ON;
6448 result = glp_simplex(ats->prob, &opt_lp);
6449 lp_solution = glp_get_status (ats->prob);
6451 // TODO: Remove if this does not appear until release
6452 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "EXECUTED SIMPLEX WITH PRESOLVER! %i \n", lp_solution);
6454 if (ats_evaluate_results(result, lp_solution, "LP") != GNUNET_YES)
6456 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "After execution simplex with presolver: STILL INVALID!\n");
6458 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);
6459 glp_write_lp (ats->prob, NULL, filename);
6460 GNUNET_free (filename);
6461 stat->valid = GNUNET_NO;
6462 ats->stat.recreate_problem = GNUNET_YES;
6465 stat->valid = GNUNET_YES;
6470 glp_init_iocp(&opt_mlp);
6472 opt_mlp.tm_lim = max_dur;
6475 opt_mlp.msg_lev = GLP_MSG_ALL;
6477 opt_mlp.msg_lev = GLP_MSG_OFF;
6480 result = glp_intopt (ats->prob, &opt_mlp);
6481 mlp_solution = glp_mip_status (ats->prob);
6482 stat->solution = mlp_solution;
6484 if (ats_evaluate_results(result, mlp_solution, "MLP") == GNUNET_YES)
6486 stat->valid = GNUNET_YES;
6490 // TODO: Remove if this does not appear until release
6491 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);
6492 stat->valid = GNUNET_NO;
6497 int error = GNUNET_NO;
6499 struct ATS_mechanism *t = NULL;
6500 for (c=1; c<= (c_peers); c++ )
6503 t = peers[c].m_head;
6506 bw = glp_get_col_prim(prob, t->col_index);
6510 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);
6512 if (check ==GNUNET_YES)
6514 glp_write_sol(prob, "invalid_solution.mlp");
6515 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid solution, check invalid_solution.mlp");
6516 GNUNET_STATISTICS_update (stats, "ATS invalid solutions", 1, GNUNET_NO);
6519 if (check ==GNUNET_NO)
6527 if (glp_get_col_prim(ats->prob,2*c_mechs+1) != 1)
6530 for (c=1; c<= available_quality_metrics; c++ )
6532 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));
6534 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));
6535 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));
6536 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));
6537 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "objective value: %f\n", glp_mip_obj_val(ats->prob));
6542 static void ats_delete_problem ()
6545 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Deleting problem\n");
6549 for (c=0; c< (ats->stat).c_mechs; c++)
6550 GNUNET_free_non_null (ats->mechanisms[c].rc);
6553 if (ats->mechanisms!=NULL)
6555 GNUNET_free(ats->mechanisms);
6556 ats->mechanisms = NULL;
6559 if (ats->peers!=NULL)
6561 GNUNET_free(ats->peers);
6565 if (ats->prob != NULL)
6567 glp_delete_prob(ats->prob);
6571 ats->stat.begin_cr = GNUNET_SYSERR;
6572 ats->stat.begin_qm = GNUNET_SYSERR;
6573 ats->stat.c_mechs = 0;
6574 ats->stat.c_peers = 0;
6575 ats->stat.end_cr = GNUNET_SYSERR;
6576 ats->stat.end_qm = GNUNET_SYSERR;
6577 ats->stat.solution = GNUNET_SYSERR;
6578 ats->stat.valid = GNUNET_SYSERR;
6582 static void ats_update_problem_qm ()
6587 int c_q_metrics = available_quality_metrics;
6589 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6590 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6592 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6594 row_index = ats->stat.begin_qm;
6596 for (c=1; c <= c_q_metrics; c++)
6601 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6604 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6605 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6607 ja[array_index] = c2;
6609 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6610 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6612 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
6614 double v0 = 0, v1 = 0, v2 = 0;
6616 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6617 if (v1 < 1) v0 = 0.1;
6618 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6619 if (v1 < 1) v0 = 0.1;
6620 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6621 if (v1 < 1) v0 = 0.1;
6622 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
6625 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
6627 double v0 = 0, v1 = 0, v2 = 0;
6628 v0 = ats->mechanisms[c2].addr->quality[c-1].values[0];
6630 v1 = ats->mechanisms[c2].addr->quality[c-1].values[1];
6632 v2 = ats->mechanisms[c2].addr->quality[c-1].values[2];
6634 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
6636 value = (double) 10 / value;
6640 ar[array_index] = (ats->mechanisms[c2].peer->f) * value;
6642 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]);
6646 ja[array_index] = ats->stat.col_qm + c - 1;
6647 ar[array_index] = -1;
6650 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6652 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6658 GNUNET_free_non_null (ja);
6659 GNUNET_free_non_null (ar);
6663 static void ats_update_problem_cr ()
6669 double ct_max, ct_min;
6671 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6672 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6674 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics\n");
6675 row_index = ats->stat.begin_cr;
6678 for (c=0; c<available_ressources; c++)
6680 ct_max = ressources[c].c_max;
6681 ct_min = ressources[c].c_min;
6683 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
6685 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
6687 for (c2=1; c2<=ats->stat.c_mechs; c2++)
6691 GNUNET_assert (ats->mechanisms[c2].addr != NULL);
6692 GNUNET_assert (ats->mechanisms[c2].peer != NULL);
6694 ja[array_index] = c2;
6695 value = ats->mechanisms[c2].addr->ressources[c].c;
6696 ar[array_index] = value;
6698 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, row_index, ja[array_index], ar[array_index]);
6702 glp_set_mat_row (ats->prob, row_index, array_index, ja, ar);
6708 GNUNET_free_non_null (ja);
6709 GNUNET_free_non_null (ar);
6714 static void ats_update_problem_qm_TEST ()
6719 int old_ja[ats->stat.c_mechs + 2];
6720 double old_ar[ats->stat.c_mechs + 2];
6724 int *ja = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (int));
6725 double *ar = GNUNET_malloc ((1 + ats->stat.c_mechs*2 + 3 + available_quality_metrics) * sizeof (double));
6727 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Updating problem quality metrics TEST\n");
6729 if (ats->stat.begin_qm >0)
6730 row_index = ats->stat.begin_qm;
6735 for (c=0; c<available_quality_metrics; c++)
6738 c_old = glp_get_mat_row (ats->prob, row_index, old_ja, old_ar);
6740 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
6742 for (c2=1; c2<=c_old; c2++)
6744 ja[c2] = old_ja[c2];
6745 if ((changed < 3) && (c2>2) && (old_ar[c2] != -1))
6747 ar[c2] = old_ar[c2] + 5 - changed;
6751 ar[c2] = old_ar[c2];
6753 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]);
6756 glp_set_mat_row (ats->prob, row_index, c_old, ja, ar);
6761 GNUNET_free_non_null (ja);
6762 GNUNET_free_non_null (ar);
6764 #endif //END: HAVE_LIBGLPK
6766 /** solve the bandwidth distribution problem
6767 * @param max_it maximum iterations
6768 * @param max_dur maximum duration in ms
6769 * @param D weight for diversity
6770 * @param U weight for utility
6771 * @param R weight for relativity
6772 * @param v_b_min minimal bandwidth per peer
6773 * @param v_n_min minimum number of connections
6774 * @param stat result struct
6775 * @return GNUNET_SYSERR if glpk is not available, number of mechanisms used
6777 static int ats_create_problem (double D, double U, double R, int v_b_min, int v_n_min, struct ATS_stat *stat)
6779 ats->prob = glp_create_prob();
6785 int c_c_ressources = available_ressources;
6786 int c_q_metrics = available_quality_metrics;
6788 double M = VERY_BIG_DOUBLE_VALUE;
6789 double Q[c_q_metrics+1];
6790 for (c=1; c<=c_q_metrics; c++)
6795 struct NeighbourList *next = neighbours;
6798 int found_addresses = GNUNET_NO;
6799 struct ReadyList *r_next = next->plugins;
6800 while (r_next != NULL)
6802 struct ForeignAddressList * a_next = r_next->addresses;
6803 while (a_next != NULL)
6806 found_addresses = GNUNET_YES;
6807 a_next = a_next->next;
6809 r_next = r_next->next;
6811 if (found_addresses) c_peers++;
6818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No addresses for bw distribution available\n", c_peers);
6820 stat->valid = GNUNET_NO;
6823 return GNUNET_SYSERR;
6826 GNUNET_assert (ats->mechanisms == NULL);
6827 ats->mechanisms = GNUNET_malloc((1+c_mechs) * sizeof (struct ATS_mechanism));
6828 GNUNET_assert (ats->peers == NULL);
6829 ats->peers = GNUNET_malloc((1+c_peers) * sizeof (struct ATS_peer));
6831 struct ATS_mechanism * mechanisms = ats->mechanisms;
6832 struct ATS_peer * peers = ats->peers;
6840 int found_addresses = GNUNET_NO;
6841 struct ReadyList *r_next = next->plugins;
6842 while (r_next != NULL)
6844 struct ForeignAddressList * a_next = r_next->addresses;
6845 while (a_next != NULL)
6847 if (found_addresses == GNUNET_NO)
6849 peers[c_peers].peer = next->id;
6850 peers[c_peers].m_head = NULL;
6851 peers[c_peers].m_tail = NULL;
6852 peers[c_peers].f = 1.0 / c_mechs;
6855 mechanisms[c_mechs].addr = a_next;
6856 mechanisms[c_mechs].col_index = c_mechs;
6857 mechanisms[c_mechs].peer = &peers[c_peers];
6858 mechanisms[c_mechs].next = NULL;
6859 mechanisms[c_mechs].plugin = r_next->plugin;
6861 GNUNET_CONTAINER_DLL_insert_tail(peers[c_peers].m_head, peers[c_peers].m_tail, &mechanisms[c_mechs]);
6862 found_addresses = GNUNET_YES;
6865 a_next = a_next->next;
6867 r_next = r_next->next;
6869 if (found_addresses == GNUNET_YES)
6876 if (v_n_min > c_peers)
6880 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);
6883 int size = 1 + 3 + 10 *c_mechs + c_peers + (c_q_metrics*c_mechs)+ c_q_metrics + c_c_ressources * c_mechs ;
6886 int * ia = GNUNET_malloc (size * sizeof (int));
6887 int * ja = GNUNET_malloc (size * sizeof (int));
6888 double * ar = GNUNET_malloc(size* sizeof (double));
6890 glp_set_prob_name(ats->prob, "gnunet ats bandwidth distribution");
6891 glp_set_obj_dir(ats->prob, GLP_MAX);
6893 /* adding columns */
6895 glp_add_cols(ats->prob, 2 * c_mechs);
6896 /* adding b_t cols */
6897 for (c=1; c <= c_mechs; c++)
6900 GNUNET_asprintf(&name, "p_%s_b%i",GNUNET_i2s(&(mechanisms[c].peer->peer)), c);
6901 glp_set_col_name(ats->prob, c, name);
6903 glp_set_col_bnds(ats->prob, c, GLP_LO, 0.0, 0.0);
6904 glp_set_col_kind(ats->prob, c, GLP_CV);
6905 glp_set_obj_coef(ats->prob, c, 0);
6908 /* adding n_t cols */
6909 for (c=c_mechs+1; c <= 2*c_mechs; c++)
6911 GNUNET_asprintf(&name, "p_%s_n%i",GNUNET_i2s(&(mechanisms[c-c_mechs].peer->peer)),(c-c_mechs));
6912 glp_set_col_name(ats->prob, c, name);
6914 glp_set_col_bnds(ats->prob, c, GLP_DB, 0.0, 1.0);
6915 glp_set_col_kind(ats->prob, c, GLP_IV);
6916 glp_set_obj_coef(ats->prob, c, 0);
6919 /* feasibility constraints */
6920 /* Constraint 1: one address per peer*/
6922 glp_add_rows(ats->prob, c_peers);
6923 for (c=1; c<=c_peers; c++)
6926 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6928 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 1.0, 1.0);
6930 struct ATS_mechanism *m = peers[c].m_head;
6933 ia[array_index] = row_index;
6934 ja[array_index] = (c_mechs + m->col_index);
6935 ar[array_index] = 1;
6937 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6945 /* Constraint 2: only active mechanism gets bandwidth assigned */
6946 glp_add_rows(ats->prob, c_mechs);
6947 for (c=1; c<=c_mechs; c++)
6949 /* b_t - n_t * M <= 0 */
6951 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6953 glp_set_row_bnds(ats->prob, row_index, GLP_UP, 0.0, 0.0);
6955 ia[array_index] = row_index;
6956 ja[array_index] = mechanisms[c].col_index;
6957 ar[array_index] = 1;
6959 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6962 ia[array_index] = row_index;
6963 ja[array_index] = c_mechs + mechanisms[c].col_index;
6964 ar[array_index] = -M;
6966 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6972 /* Constraint 3: minimum bandwidth*/
6973 glp_add_rows(ats->prob, c_mechs);
6974 for (c=1; c<=c_mechs; c++)
6976 /* b_t - n_t * b_min <= 0 */
6978 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
6980 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
6982 ia[array_index] = row_index;
6983 ja[array_index] = mechanisms[c].col_index;
6984 ar[array_index] = 1;
6986 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6989 ia[array_index] = row_index;
6990 ja[array_index] = c_mechs + mechanisms[c].col_index;
6991 ar[array_index] = -v_b_min;
6993 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
6999 /* Constraint 4: max ressource capacity */
7000 /* V cr: bt * ct_r <= cr_max
7002 glp_add_rows(ats->prob, available_ressources);
7003 double ct_max = VERY_BIG_DOUBLE_VALUE;
7004 double ct_min = 0.0;
7006 stat->begin_cr = array_index;
7008 for (c=0; c<available_ressources; c++)
7010 ct_max = ressources[c].c_max;
7011 ct_min = ressources[c].c_min;
7013 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] %f..%f\n",row_index, ct_min, ct_max);
7015 glp_set_row_bnds(ats->prob, row_index, GLP_DB, ct_min, ct_max);
7017 for (c2=1; c2<=c_mechs; c2++)
7020 ia[array_index] = row_index;
7021 ja[array_index] = c2;
7022 value = mechanisms[c2].addr->ressources[c].c;
7023 ar[array_index] = value;
7025 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7031 stat->end_cr = array_index--;
7033 /* Constraint 5: min number of connections*/
7034 glp_add_rows(ats->prob, 1);
7035 for (c=1; c<=c_mechs; c++)
7037 // b_t - n_t * b_min >= 0
7039 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7041 glp_set_row_bnds(ats->prob, row_index, GLP_LO, v_n_min, 0.0);
7043 ia[array_index] = row_index;
7044 ja[array_index] = c_mechs + mechanisms[c].col_index;
7045 ar[array_index] = 1;
7047 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7053 // optimisation constraints
7057 // Constraint 6: optimize for diversity
7059 col_d = glp_add_cols(ats->prob, 1);
7060 stat->col_d = col_d;
7061 //GNUNET_assert (col_d == (2*c_mechs) + 1);
7062 glp_set_col_name(ats->prob, col_d, "d");
7063 glp_set_obj_coef(ats->prob, col_d, D);
7064 glp_set_col_bnds(ats->prob, col_d, GLP_LO, 0.0, 0.0);
7065 glp_add_rows(ats->prob, 1);
7067 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7069 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7070 for (c=1; c<=c_mechs; c++)
7072 ia[array_index] = row_index;
7073 ja[array_index] = c_mechs + mechanisms[c].col_index;
7074 ar[array_index] = 1;
7076 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7080 ia[array_index] = row_index;
7081 ja[array_index] = col_d;
7082 ar[array_index] = -1;
7084 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7090 // Constraint 7: optimize for quality
7092 col_qm = glp_add_cols(ats->prob, c_q_metrics);
7093 stat->col_qm = col_qm;
7094 //GNUNET_assert (col_qm == (2*c_mechs) + 3 + 1);
7095 for (c=0; c< c_q_metrics; c++)
7097 GNUNET_asprintf(&name, "Q_%s",qm[c].name);
7098 glp_set_col_name(ats->prob, col_qm + c, name);
7099 glp_set_col_bnds(ats->prob, col_qm + c, GLP_LO, 0.0, 0.0);
7101 glp_set_obj_coef(ats->prob, col_qm + c, Q[c]);
7103 glp_add_rows(ats->prob, available_quality_metrics);
7104 stat->begin_qm = row_index;
7105 for (c=1; c <= c_q_metrics; c++)
7108 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7111 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7112 for (c2=1; c2<=c_mechs; c2++)
7115 ia[array_index] = row_index;
7116 ja[array_index] = c2;
7117 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY)
7119 double v0 = 0, v1 = 0, v2 = 0;
7120 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7121 if (v1 < 1) v0 = 0.1;
7122 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7123 if (v1 < 1) v0 = 0.1;
7124 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7125 if (v1 < 1) v0 = 0.1;
7126 value = 100.0 / ((v0 + 2 * v1 + 3 * v2) / 6.0);
7129 if (qm[c-1].atis_index == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
7131 double v0 = 0, v1 = 0, v2 = 0;
7132 v0 = mechanisms[c2].addr->quality[c-1].values[0];
7134 v1 = mechanisms[c2].addr->quality[c-1].values[1];
7136 v2 = mechanisms[c2].addr->quality[c-1].values[2];
7138 value = (v0 + 2 * v1 + 3 * v2) / 6.0;
7140 value = (double) 10 / value;
7144 ar[array_index] = (mechanisms[c2].peer->f) * value ;
7146 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]);
7151 ia[array_index] = row_index;
7152 ja[array_index] = col_qm + c - 1;
7153 ar[array_index] = -1;
7155 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7160 stat->end_qm = row_index-1;
7162 // Constraint 8: optimize bandwidth utility
7164 col_u = glp_add_cols(ats->prob, 1);
7165 stat->col_u = col_u;
7166 //GNUNET_assert (col_u == (2*c_mechs) + 2);
7167 glp_set_col_name(ats->prob, col_u, "u");
7168 glp_set_obj_coef(ats->prob, col_u, U);
7169 glp_set_col_bnds(ats->prob, col_u, GLP_LO, 0.0, 0.0);
7170 glp_add_rows(ats->prob, 1);
7172 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "bounds [row]=[%i] \n",row_index);
7174 glp_set_row_bnds(ats->prob, row_index, GLP_FX, 0.0, 0.0);
7175 for (c=1; c<=c_mechs; c++)
7177 ia[array_index] = row_index;
7178 ja[array_index] = c;
7179 ar[array_index] = mechanisms[c].peer->f;
7181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7185 ia[array_index] = row_index;
7186 ja[array_index] = col_u;
7187 ar[array_index] = -1;
7189 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7195 // Constraint 9: optimize relativity
7197 col_r = glp_add_cols(ats->prob, 1);
7198 stat->col_r = col_r;
7199 //GNUNET_assert (col_r == (2*c_mechs) + 3);
7200 glp_set_col_name(ats->prob, col_r, "r");
7201 glp_set_obj_coef(ats->prob, col_r, R);
7202 glp_set_col_bnds(ats->prob, col_r, GLP_LO, 0.0, 0.0);
7203 glp_add_rows(ats->prob, c_peers);
7204 for (c=1; c<=c_peers; c++)
7206 glp_set_row_bnds(ats->prob, row_index, GLP_LO, 0.0, 0.0);
7208 struct ATS_mechanism *m = peers[c].m_head;
7211 ia[array_index] = row_index;
7212 ja[array_index] = m->col_index;
7213 ar[array_index] = 1 / mechanisms[c].peer->f;
7215 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7220 ia[array_index] = row_index;
7221 ja[array_index] = col_r;
7222 ar[array_index] = -1;
7224 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "[index]=[%i]: [%i,%i]=%f \n",array_index, ia[array_index], ja[array_index], ar[array_index]);
7231 /* Loading the matrix */
7232 glp_load_matrix(ats->prob, array_index-1, ia, ja, ar);
7234 stat->c_mechs = c_mechs;
7235 stat->c_peers = c_peers;
7237 stat->valid = GNUNET_YES;
7249 void ats_notify_ats_data (
7250 const struct GNUNET_PeerIdentity *peer,
7251 const struct GNUNET_TRANSPORT_ATS_Information *ats_data)
7254 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ATS_notify_ats_data: %s\n",GNUNET_i2s(peer));
7256 if (shutdown_in_progress == GNUNET_NO)
7257 ats_calculate_bandwidth_distribution();
7259 #endif //END: HAVE_LIBGLPK
7262 ats_calculate_bandwidth_distribution ()
7266 struct GNUNET_TIME_Absolute start;
7267 struct GNUNET_TIME_Relative creation;
7268 struct GNUNET_TIME_Relative solving;
7269 char *text = "unmodified";
7271 struct GNUNET_TIME_Relative delta = GNUNET_TIME_absolute_get_difference (ats->last, GNUNET_TIME_absolute_get());
7272 if (delta.rel_value < ats->min_delta.rel_value)
7275 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Minimum time between cycles not reached\n");
7280 if (shutdown_in_progress == GNUNET_YES)
7283 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Transport service is shutting down\n");
7290 if (INT_MAX < ats->max_exec_duration.rel_value)
7293 dur = (int) ats->max_exec_duration.rel_value;
7296 ats->stat.simplex_rerun_required = GNUNET_NO;
7297 start = GNUNET_TIME_absolute_get();
7298 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL) || (ats->stat.valid == GNUNET_NO))
7301 ats->stat.recreate_problem = GNUNET_YES;
7302 ats_delete_problem ();
7303 ats_create_problem (ats->D, ats->U, ats->R, ats->v_b_min, ats->v_n_min, &ats->stat);
7305 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);
7309 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_resources == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7311 text = "modified resources";
7312 ats_update_problem_cr();
7314 else if ((ats->stat.recreate_problem == GNUNET_NO) && (ats->stat.modified_quality == GNUNET_YES) && (ats->stat.valid == GNUNET_YES))
7316 text = "modified quality";
7317 ats_update_problem_qm();
7318 //ats_update_problem_qm_TEST ();
7322 else GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Problem is unmodified\n");
7325 creation = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7326 start = GNUNET_TIME_absolute_get();
7328 ats->stat.solution = GLP_UNDEF;
7329 if (ats->stat.valid == GNUNET_YES)
7331 ats_solve_problem(ats->max_iterations, ats->max_exec_duration.rel_value, ats->stat.c_peers, ats->stat.c_mechs, &ats->stat);
7333 solving = GNUNET_TIME_absolute_get_difference(start,GNUNET_TIME_absolute_get());
7335 if (ats->stat.valid == GNUNET_YES)
7337 int msg_type = GNUNET_ERROR_TYPE_DEBUG;
7339 msg_type = GNUNET_ERROR_TYPE_ERROR;
7341 GNUNET_log (msg_type, "MLP %s: creation time: %llu, execution time: %llu, %i mechanisms, simplex rerun: %s, solution %s\n",
7342 text, creation.rel_value, solving.rel_value,
7344 (ats->stat.simplex_rerun_required == GNUNET_NO) ? "NO" : "YES", (ats->stat.solution == 5) ? "OPTIMAL" : "INVALID");
7345 ats->successful_executions ++;
7346 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7348 if ((ats->stat.recreate_problem == GNUNET_YES) || (ats->prob==NULL))
7349 GNUNET_STATISTICS_set (stats, "ATS state",ATS_NEW, GNUNET_NO);
7350 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7351 (ats->stat.modified_quality == GNUNET_NO))
7352 GNUNET_STATISTICS_set (stats, "ATS state", ATS_C_UPDATED, GNUNET_NO);
7353 else if ((ats->stat.modified_resources == GNUNET_NO) &&
7354 (ats->stat.modified_quality == GNUNET_YES) &&
7355 (ats->stat.simplex_rerun_required == GNUNET_NO))
7356 GNUNET_STATISTICS_set (stats, "ATS state", ATS_Q_UPDATED, GNUNET_NO);
7357 else if ((ats->stat.modified_resources == GNUNET_YES) &&
7358 (ats->stat.modified_quality == GNUNET_YES) &&
7359 (ats->stat.simplex_rerun_required == GNUNET_NO))
7360 GNUNET_STATISTICS_set (stats, "ATS state", ATS_QC_UPDATED, GNUNET_NO);
7361 else if (ats->stat.simplex_rerun_required == GNUNET_NO)
7362 GNUNET_STATISTICS_set (stats, "ATS state", ATS_UNMODIFIED, GNUNET_NO);
7366 if (ats->stat.c_peers != 0)
7368 ats->invalid_executions ++;
7369 GNUNET_STATISTICS_set (stats, "# ATS invalid executions", ats->invalid_executions, GNUNET_NO);
7373 GNUNET_STATISTICS_set (stats, "# ATS successful executions", ats->successful_executions, GNUNET_NO);
7377 GNUNET_STATISTICS_set (stats, "ATS duration", solving.rel_value + creation.rel_value, GNUNET_NO);
7378 GNUNET_STATISTICS_set (stats, "ATS mechanisms", ats->stat.c_mechs, GNUNET_NO);
7379 GNUNET_STATISTICS_set (stats, "ATS peers", ats->stat.c_peers, GNUNET_NO);
7380 GNUNET_STATISTICS_set (stats, "ATS solution", ats->stat.solution, GNUNET_NO);
7381 GNUNET_STATISTICS_set (stats, "ATS timestamp", start.abs_value, GNUNET_NO);
7383 if ((ats->save_mlp == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7386 if (ats->dump_overwrite == GNUNET_NO)
7388 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.mlp",
7389 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7390 glp_write_lp (ats->prob, NULL, filename);
7394 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.mlp",
7395 ats->stat.c_peers, ats->stat.c_mechs );
7396 glp_write_lp (ats->prob, NULL, filename);
7398 GNUNET_free (filename);
7400 if ((ats->save_solution == GNUNET_YES) && (ats->stat.c_mechs >= ats->dump_min_peers) && (ats->stat.c_mechs >= ats->dump_min_addr))
7403 if (ats->dump_overwrite == GNUNET_NO)
7405 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i_%s_%llu.sol",
7406 ats->stat.c_peers, ats->stat.c_mechs, text, GNUNET_TIME_absolute_get().abs_value);
7407 glp_print_sol (ats->prob, filename);
7411 GNUNET_asprintf (&filename, "ats_mlp_p%i_m%i.sol",
7412 ats->stat.c_peers, ats->stat.c_mechs);
7413 glp_print_sol (ats->prob, filename);
7415 GNUNET_free (filename);
7418 ats->last = GNUNET_TIME_absolute_get();
7419 ats->stat.recreate_problem = GNUNET_NO;
7420 ats->stat.modified_resources = GNUNET_NO;
7421 ats->stat.modified_quality = GNUNET_NO;
7426 ats_schedule_calculation (void *cls,
7427 const struct GNUNET_SCHEDULER_TaskContext *tc)
7429 struct ATS_info *ats = (struct ATS_info *) cls;
7430 if (ats==NULL) return;
7432 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7433 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
7436 if (shutdown_in_progress == GNUNET_YES)
7440 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Running scheduled calculation\n");
7443 ats_calculate_bandwidth_distribution (ats);
7445 ats->ats_task = GNUNET_SCHEDULER_add_delayed (ats->exec_interval,
7446 &ats_schedule_calculation, ats);
7452 unsigned long long value;
7455 ats = GNUNET_malloc(sizeof (struct ATS_info));
7457 ats->min_delta = ATS_MIN_INTERVAL;
7458 ats->exec_interval = ATS_EXEC_INTERVAL;
7459 ats->max_exec_duration = ATS_MAX_EXEC_DURATION;
7460 ats->max_iterations = ATS_MAX_ITERATIONS;
7461 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7464 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS not active\n");
7471 ats->v_b_min = 64000;
7473 ats->dump_min_peers = 1;
7474 ats->dump_min_addr = 1;
7475 ats->dump_overwrite = GNUNET_NO;
7476 ats->mechanisms = NULL;
7478 ats->successful_executions = 0;
7479 ats->invalid_executions = 0;
7485 /* loading cost ressources */
7486 for (c=0; c<available_ressources; c++)
7488 GNUNET_asprintf(§ion,"%s_UP",ressources[c].cfg_param);
7489 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7491 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7494 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7496 ressources[c].c_max = value;
7499 GNUNET_free (section);
7500 GNUNET_asprintf(§ion,"%s_DOWN",ressources[c].cfg_param);
7501 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", section))
7503 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "transport",section, &value))
7506 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Found ressource cost: [%s] = %llu\n", section, value);
7508 ressources[c].c_min = value;
7511 GNUNET_free (section);
7514 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MLP"))
7515 ats->save_mlp = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_MLP");
7517 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_SOLUTION"))
7518 ats->save_solution = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_SOLUTION");
7519 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7520 ats->dump_overwrite = GNUNET_CONFIGURATION_get_value_yesno (cfg, "transport","DUMP_OVERWRITE");
7521 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_PEERS"))
7523 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_PEERS", &value);
7524 ats->dump_min_peers= value;
7526 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_MIN_ADDRS"))
7528 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_MIN_ADDRS", &value);
7529 ats->dump_min_addr= value;
7531 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "DUMP_OVERWRITE"))
7533 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","DUMP_OVERWRITE", &value);
7534 ats->min_delta.rel_value = value;
7537 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7539 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7540 ats->min_delta.rel_value = value;
7543 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_EXEC_INTERVAL"))
7545 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_EXEC_INTERVAL", &value);
7546 ats->exec_interval.rel_value = value;
7548 if (GNUNET_CONFIGURATION_have_value(cfg, "transport", "ATS_MIN_INTERVAL"))
7550 GNUNET_CONFIGURATION_get_value_number(cfg, "transport","ATS_MIN_INTERVAL", &value);
7551 ats->min_delta.rel_value = value;
7554 ats->ats_task = GNUNET_SCHEDULER_add_now(&ats_schedule_calculation, ats);
7558 static void ats_shutdown ()
7561 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_destroy\n");
7563 if (ats->ats_task != GNUNET_SCHEDULER_NO_TASK)
7564 GNUNET_SCHEDULER_cancel(ats->ats_task);
7565 ats->ats_task = GNUNET_SCHEDULER_NO_TASK;
7568 ats_delete_problem ();
7575 void ats_notify_peer_connect (
7576 const struct GNUNET_PeerIdentity *peer,
7577 const struct GNUNET_TRANSPORT_ATS_Information *ats_data, int ats_count)
7580 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_connect: %s\n",GNUNET_i2s(peer));
7582 //update_addr_ats();
7583 ats->stat.recreate_problem = GNUNET_YES;
7584 ats_calculate_bandwidth_distribution(ats);
7587 void ats_notify_peer_disconnect (
7588 const struct GNUNET_PeerIdentity *peer)
7591 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ats_notify_peer_disconnect: %s\n",GNUNET_i2s(peer));
7593 ats->stat.recreate_problem = GNUNET_YES;
7594 ats_calculate_bandwidth_distribution (ats);
7597 struct ForeignAddressList * ats_get_preferred_address (
7598 struct NeighbourList *n)
7601 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "ats_get_prefered_transport for peer: %s\n",GNUNET_i2s(&n->id));
7603 struct ReadyList *next = n->plugins;
7604 while (next != NULL)
7607 //GNUNET_log (GNUNET_ERROR_TYPE_BULK, "plugin: %s %i\n",next->plugin->short_name,strcmp(next->plugin->short_name,"unix"));
7611 return find_ready_address(n);
7615 * Initiate transport service.
7617 * @param cls closure
7618 * @param server the initialized server
7619 * @param c configuration to use
7623 struct GNUNET_SERVER_Handle *server,
7624 const struct GNUNET_CONFIGURATION_Handle *c)
7626 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
7627 {&handle_start, NULL,
7628 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
7629 {&handle_hello, NULL,
7630 GNUNET_MESSAGE_TYPE_HELLO, 0},
7631 {&handle_send, NULL,
7632 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
7633 {&handle_request_connect, NULL,
7634 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
7635 {&handle_set_quota, NULL,
7636 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
7637 {&handle_address_lookup, NULL,
7638 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
7640 {&handle_blacklist_init, NULL,
7641 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
7642 {&handle_blacklist_reply, NULL,
7643 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
7649 unsigned long long tneigh;
7652 shutdown_in_progress = GNUNET_NO;
7654 stats = GNUNET_STATISTICS_create ("transport", cfg);
7655 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
7656 /* parse configuration */
7658 GNUNET_CONFIGURATION_get_value_number (c,
7663 GNUNET_CONFIGURATION_get_value_filename (c,
7665 "HOSTKEY", &keyfile)))
7667 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7669 ("Transport service is lacking key configuration settings. Exiting.\n"));
7670 GNUNET_SCHEDULER_shutdown ();
7673 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7676 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7677 validation_map = NULL;
7681 max_connect_per_transport = (uint32_t) tneigh;
7682 peerinfo = GNUNET_PEERINFO_connect (cfg);
7683 if (peerinfo == NULL)
7685 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7686 _("Could not access PEERINFO service. Exiting.\n"));
7687 GNUNET_SCHEDULER_shutdown ();
7690 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7693 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7694 validation_map = NULL;
7695 GNUNET_free (keyfile);
7698 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7699 GNUNET_free (keyfile);
7700 if (my_private_key == NULL)
7702 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7704 ("Transport service could not access hostkey. Exiting.\n"));
7705 GNUNET_SCHEDULER_shutdown ();
7708 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
7711 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
7712 validation_map = NULL;
7715 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7716 GNUNET_CRYPTO_hash (&my_public_key,
7717 sizeof (my_public_key), &my_identity.hashPubKey);
7718 /* setup notification */
7719 GNUNET_SERVER_disconnect_notify (server,
7720 &client_disconnect_notification, NULL);
7721 /* load plugins... */
7724 GNUNET_CONFIGURATION_get_value_string (c,
7725 "TRANSPORT", "PLUGINS", &plugs))
7727 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7728 _("Starting transport plugins `%s'\n"), plugs);
7729 pos = strtok (plugs, " ");
7732 start_transport (server, pos);
7734 pos = strtok (NULL, " ");
7736 GNUNET_free (plugs);
7738 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
7739 &shutdown_task, NULL);
7746 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
7748 /* If we have a blacklist file, read from it */
7749 read_blacklist_file(cfg);
7750 /* process client requests */
7751 GNUNET_SERVER_add_handlers (server, handlers);
7756 * The main function for the transport service.
7758 * @param argc number of arguments from the command line
7759 * @param argv command line arguments
7760 * @return 0 ok, 1 on error
7763 main (int argc, char *const *argv)
7765 a2s (NULL, NULL, 0); /* make compiler happy */
7766 return (GNUNET_OK ==
7767 GNUNET_SERVICE_run (argc,
7770 GNUNET_SERVICE_OPTION_NONE,
7771 &run, NULL)) ? 0 : 1;
7774 /* end of gnunet-service-transport.c */