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"
42 #define DEBUG_BLACKLIST GNUNET_YES
44 #define DEBUG_PING_PONG GNUNET_YES
46 #define DEBUG_TRANSPORT_HELLO GNUNET_YES
49 * Should we do some additional checks (to validate behavior
52 #define EXTRA_CHECKS GNUNET_YES
55 * How many messages can we have pending for a given client process
56 * before we start to drop incoming messages? We typically should
57 * have only one client and so this would be the primary buffer for
58 * messages, so the number should be chosen rather generously.
60 * The expectation here is that most of the time the queue is large
61 * enough so that a drop is virtually never required. Note that
62 * this value must be about as large as 'TOTAL_MSGS' in the
63 * 'test_transport_api_reliability.c', otherwise that testcase may
66 #define MAX_PENDING (128 * 1024)
69 * Size of the per-transport blacklist hash maps.
71 #define TRANSPORT_BLACKLIST_HT_SIZE 16
74 * How often should we try to reconnect to a peer using a particular
75 * transport plugin before giving up? Note that the plugin may be
76 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
78 #define MAX_CONNECT_RETRY 3
81 * Limit on the number of ready-to-run tasks when validating
82 * HELLOs. If more tasks are ready to run, we will drop
83 * HELLOs instead of validating them.
85 #define MAX_HELLO_LOAD 4
88 * How often must a peer violate bandwidth quotas before we start
89 * to simply drop its messages?
91 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
94 * How long until a HELLO verification attempt should time out?
95 * Must be rather small, otherwise a partially successful HELLO
96 * validation (some addresses working) might not be available
97 * before a client's request for a connection fails for good.
98 * Besides, if a single request to an address takes a long time,
99 * then the peer is unlikely worthwhile anyway.
101 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
104 * How long is a PONG signature valid? We'll recycle a signature until
105 * 1/4 of this time is remaining. PONGs should expire so that if our
106 * external addresses change an adversary cannot replay them indefinitely.
107 * OTOH, we don't want to spend too much time generating PONG signatures,
108 * so they must have some lifetime to reduce our CPU usage.
110 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
113 * Priority to use for PONG messages.
115 #define TRANSPORT_PONG_PRIORITY 4
118 * How often do we re-add (cheaper) plugins to our list of plugins
119 * to try for a given connected peer?
121 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
124 * After how long do we expire an address in a HELLO that we just
125 * validated? This value is also used for our own addresses when we
128 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
132 * How long before an existing address expires should we again try to
133 * validate it? Must be (significantly) smaller than
134 * HELLO_ADDRESS_EXPIRATION.
136 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
139 * Maximum frequency for re-evaluating latencies for all transport addresses.
141 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
144 * Maximum frequency for re-evaluating latencies for connected addresses.
146 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
150 * List of addresses of other peers
152 struct ForeignAddressList
155 * This is a linked list.
157 struct ForeignAddressList *next;
160 * Which ready list does this entry belong to.
162 struct ReadyList *ready_list;
165 * How long until we auto-expire this address (unless it is
166 * re-confirmed by the transport)?
168 struct GNUNET_TIME_Absolute expires;
171 * Task used to re-validate addresses, updates latencies and
174 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
182 * Session (or NULL if no valid session currently exists or if the
183 * plugin does not use sessions).
185 struct Session *session;
188 * What was the last latency observed for this address, plugin and peer?
190 struct GNUNET_TIME_Relative latency;
193 * If we did not successfully transmit a message to the given peer
194 * via this connection during the specified time, we should consider
195 * the connection to be dead. This is used in the case that a TCP
196 * transport simply stalls writing to the stream but does not
197 * formerly get a signal that the other peer died.
199 struct GNUNET_TIME_Absolute timeout;
202 * How often have we tried to connect using this plugin? Used to
203 * discriminate against addresses that do not work well.
204 * FIXME: not yet used, but should be!
206 unsigned int connect_attempts;
209 * DV distance to this peer (1 if no DV is used).
210 * FIXME: need to set this from transport plugins!
220 * Have we ever estimated the latency of this address? Used to
221 * ensure that the first time we add an address, we immediately
227 * Are we currently connected via this address? The first time we
228 * successfully transmit or receive data to a peer via a particular
229 * address, we set this to GNUNET_YES. If we later get an error
230 * (disconnect notification, transmission failure, timeout), we set
231 * it back to GNUNET_NO.
236 * Is this plugin currently busy transmitting to the specific target?
237 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
238 * messages do not count as 'in transmit'.
243 * Has this address been validated yet?
251 * Entry in linked list of network addresses for ourselves. Also
252 * includes a cached signature for 'struct TransportPongMessage's.
254 struct OwnAddressList
257 * This is a linked list.
259 struct OwnAddressList *next;
262 * How long until we actually auto-expire this address (unless it is
263 * re-confirmed by the transport)?
265 struct GNUNET_TIME_Absolute expires;
268 * How long until the current signature expires? (ZERO if the
269 * signature was never created).
271 struct GNUNET_TIME_Absolute pong_sig_expires;
274 * Signature for a 'struct TransportPongMessage' for this address.
276 struct GNUNET_CRYPTO_RsaSignature pong_signature;
287 * Entry in linked list of all of our plugins.
289 struct TransportPlugin
293 * This is a linked list.
295 struct TransportPlugin *next;
298 * API of the transport as returned by the plugin's
299 * initialization function.
301 struct GNUNET_TRANSPORT_PluginFunctions *api;
304 * Short name for the plugin (i.e. "tcp").
309 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
314 * List of our known addresses for this transport.
316 struct OwnAddressList *addresses;
319 * Environment this transport service is using
322 struct GNUNET_TRANSPORT_PluginEnvironment env;
325 * ID of task that is used to clean up expired addresses.
327 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
330 * Set to GNUNET_YES if we need to scrap the existing list of
331 * "addresses" and start fresh when we receive the next address
332 * update from a transport. Set to GNUNET_NO if we should just add
333 * the new address to the list and wait for the commit call.
338 * Hashmap of blacklisted peers for this particular transport.
340 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
343 struct NeighbourList;
346 * For each neighbour we keep a list of messages
347 * that we still want to transmit to the neighbour.
353 * This is a doubly linked list.
355 struct MessageQueue *next;
358 * This is a doubly linked list.
360 struct MessageQueue *prev;
363 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
364 * stuck together in memory. Allocated at the end of this struct.
366 const char *message_buf;
369 * Size of the message buf
371 size_t message_buf_size;
374 * Client responsible for queueing the message;
375 * used to check that a client has no two messages
376 * pending for the same target. Can be NULL.
378 struct TransportClient *client;
381 * Using which specific address should we send this message?
383 struct ForeignAddressList *specific_address;
386 * Peer ID of the Neighbour this entry belongs to.
388 struct GNUNET_PeerIdentity neighbour_id;
391 * Plugin that we used for the transmission.
392 * NULL until we scheduled a transmission.
394 struct TransportPlugin *plugin;
397 * At what time should we fail?
399 struct GNUNET_TIME_Absolute timeout;
402 * Internal message of the transport system that should not be
403 * included in the usual SEND-SEND_OK transmission confirmation
404 * traffic management scheme. Typically, "internal_msg" will
405 * be set whenever "client" is NULL (but it is not strictly
411 * How important is the message?
413 unsigned int priority;
419 * For a given Neighbour, which plugins are available
420 * to talk to this peer and what are their costs?
425 * This is a linked list.
427 struct ReadyList *next;
430 * Which of our transport plugins does this entry
433 struct TransportPlugin *plugin;
436 * Transport addresses, latency, and readiness for
437 * this particular plugin.
439 struct ForeignAddressList *addresses;
442 * To which neighbour does this ready list belong to?
444 struct NeighbourList *neighbour;
450 * Entry in linked list of all of our current neighbours.
456 * This is a linked list.
458 struct NeighbourList *next;
461 * Which of our transports is connected to this peer
462 * and what is their status?
464 struct ReadyList *plugins;
467 * Head of list of messages we would like to send to this peer;
468 * must contain at most one message per client.
470 struct MessageQueue *messages_head;
473 * Tail of list of messages we would like to send to this peer; must
474 * contain at most one message per client.
476 struct MessageQueue *messages_tail;
479 * Buffer for at most one payload message used when we receive
480 * payload data before our PING-PONG has succeeded. We then
481 * store such messages in this intermediary buffer until the
482 * connection is fully up.
484 struct GNUNET_MessageHeader *pre_connect_message_buffer;
487 * Context for peerinfo iteration.
488 * NULL after we are done processing peerinfo's information.
490 struct GNUNET_PEERINFO_IteratorContext *piter;
493 * Public key for this peer. Valid only if the respective flag is set below.
495 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
498 * Identity of this neighbour.
500 struct GNUNET_PeerIdentity id;
503 * ID of task scheduled to run when this peer is about to
504 * time out (will free resources associated with the peer).
506 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
509 * ID of task scheduled to run when we should retry transmitting
510 * the head of the message queue. Actually triggered when the
511 * transmission is timing out (we trigger instantly when we have
512 * a chance of success).
514 GNUNET_SCHEDULER_TaskIdentifier retry_task;
517 * How long until we should consider this peer dead
518 * (if we don't receive another message in the
521 struct GNUNET_TIME_Absolute peer_timeout;
524 * Tracker for inbound bandwidth.
526 struct GNUNET_BANDWIDTH_Tracker in_tracker;
529 * The latency we have seen for this particular address for
530 * this particular peer. This latency may have been calculated
531 * over multiple transports. This value reflects how long it took
532 * us to receive a response when SENDING via this particular
533 * transport/neighbour/address combination!
535 * FIXME: we need to periodically send PINGs to update this
536 * latency (at least more often than the current "huge" (11h?)
539 struct GNUNET_TIME_Relative latency;
542 * How often has the other peer (recently) violated the
543 * inbound traffic limit? Incremented by 10 per violation,
544 * decremented by 1 per non-violation (for each
547 unsigned int quota_violation_count;
550 * DV distance to this peer (1 if no DV is used).
555 * Have we seen an PONG from this neighbour in the past (and
556 * not had a disconnect since)?
561 * Do we have a valid public key for this neighbour?
563 int public_key_valid;
566 * Performance data for the peer.
568 struct GNUNET_TRANSPORT_ATS_Information *ats;
571 * Identity of the neighbour.
573 struct GNUNET_PeerIdentity peer;
578 * Message used to ask a peer to validate receipt (to check an address
579 * from a HELLO). Followed by the address we are trying to validate,
580 * or an empty address if we are just sending a PING to confirm that a
581 * connection which the receiver (of the PING) initiated is still valid.
583 struct TransportPingMessage
587 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
589 struct GNUNET_MessageHeader header;
592 * Challenge code (to ensure fresh reply).
594 uint32_t challenge GNUNET_PACKED;
597 * Who is the intended recipient?
599 struct GNUNET_PeerIdentity target;
605 * Message used to validate a HELLO. The challenge is included in the
606 * confirmation to make matching of replies to requests possible. The
607 * signature signs our public key, an expiration time and our address.<p>
609 * This message is followed by our transport address that the PING tried
610 * to confirm (if we liked it). The address can be empty (zero bytes)
611 * if the PING had not address either (and we received the request via
612 * a connection that we initiated).
614 struct TransportPongMessage
618 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
620 struct GNUNET_MessageHeader header;
623 * Challenge code from PING (showing freshness). Not part of what
624 * is signed so that we can re-use signatures.
626 uint32_t challenge GNUNET_PACKED;
631 struct GNUNET_CRYPTO_RsaSignature signature;
634 * What are we signing and why? Two possible reason codes can be here:
635 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
636 * plausible address for this peer (pid is set to identity of signer); or
637 * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
638 * an address we used to connect to the peer with the given pid.
640 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
643 * When does this signature expire?
645 struct GNUNET_TIME_AbsoluteNBO expiration;
648 * Either the identity of the peer Who signed this message, or the
649 * identity of the peer that we're connected to using the given
650 * address (depending on purpose.type).
652 struct GNUNET_PeerIdentity pid;
655 * Size of address appended to this message (part of what is
656 * being signed, hence not redundant).
664 * Linked list of messages to be transmitted to the client. Each
665 * entry is followed by the actual message.
667 struct ClientMessageQueueEntry
670 * This is a doubly-linked list.
672 struct ClientMessageQueueEntry *next;
675 * This is a doubly-linked list.
677 struct ClientMessageQueueEntry *prev;
682 * Client connected to the transport service.
684 struct TransportClient
688 * This is a linked list.
690 struct TransportClient *next;
693 * Handle to the client.
695 struct GNUNET_SERVER_Client *client;
698 * Linked list of messages yet to be transmitted to
701 struct ClientMessageQueueEntry *message_queue_head;
704 * Tail of linked list of messages yet to be transmitted to the
707 struct ClientMessageQueueEntry *message_queue_tail;
710 * Current transmit request handle.
712 struct GNUNET_CONNECTION_TransmitHandle *th;
715 * Is a call to "transmit_send_continuation" pending? If so, we
716 * must not free this struct (even if the corresponding client
717 * disconnects) and instead only remove it from the linked list and
718 * set the "client" field to NULL.
723 * Length of the list of messages pending for this client.
725 unsigned int message_count;
731 * Context of currently active requests to peerinfo
732 * for validation of HELLOs.
734 struct CheckHelloValidatedContext;
738 * Entry in map of all HELLOs awaiting validation.
740 struct ValidationEntry
744 * NULL if this entry is not part of a larger HELLO validation.
746 struct CheckHelloValidatedContext *chvc;
749 * The address, actually a pointer to the end
750 * of this struct. Do not free!
755 * Name of the transport.
757 char *transport_name;
760 * The public key of the peer.
762 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
765 * ID of task that will clean up this entry if we don't succeed
766 * with the validation first.
768 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
771 * At what time did we send this validation?
773 struct GNUNET_TIME_Absolute send_time;
776 * Session being validated (or NULL for none).
778 struct Session *session;
781 * Challenge number we used.
794 * Context of currently active requests to peerinfo
795 * for validation of HELLOs.
797 struct CheckHelloValidatedContext
801 * This is a doubly-linked list.
803 struct CheckHelloValidatedContext *next;
806 * This is a doubly-linked list.
808 struct CheckHelloValidatedContext *prev;
811 * Hello that we are validating.
813 const struct GNUNET_HELLO_Message *hello;
816 * Context for peerinfo iteration.
817 * NULL after we are done processing peerinfo's information.
819 struct GNUNET_PEERINFO_IteratorContext *piter;
822 * Was a HELLO known for this peer to peerinfo?
827 * Number of validation entries currently referring to this
830 unsigned int ve_count;
838 static struct GNUNET_HELLO_Message *our_hello;
843 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
848 static struct GNUNET_PeerIdentity my_identity;
853 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
858 const struct GNUNET_CONFIGURATION_Handle *cfg;
861 * Linked list of all clients to this service.
863 static struct TransportClient *clients;
866 * All loaded plugins.
868 static struct TransportPlugin *plugins;
871 * Handle to peerinfo service.
873 static struct GNUNET_PEERINFO_Handle *peerinfo;
876 * All known neighbours and their HELLOs.
878 static struct NeighbourList *neighbours;
881 * Number of neighbours we'd like to have.
883 static uint32_t max_connect_per_transport;
886 * Head of linked list.
888 static struct CheckHelloValidatedContext *chvc_head;
891 * Tail of linked list.
893 static struct CheckHelloValidatedContext *chvc_tail;
896 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
897 * of the given peer that we are currently validating).
899 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
902 * Handle for reporting statistics.
904 static struct GNUNET_STATISTICS_Handle *stats;
907 * The peer specified by the given neighbour has timed-out or a plugin
908 * has disconnected. We may either need to do nothing (other plugins
909 * still up), or trigger a full disconnect and clean up. This
910 * function updates our state and do the necessary notifications.
911 * Also notifies our clients that the neighbour is now officially
914 * @param n the neighbour list entry for the peer
915 * @param check should we just check if all plugins
916 * disconnected or must we ask all plugins to
919 static void disconnect_neighbour (struct NeighbourList *n, int check);
922 * Check the ready list for the given neighbour and if a plugin is
923 * ready for transmission (and if we have a message), do so!
925 * @param neighbour target peer for which to transmit
927 static void try_transmission_to_peer (struct NeighbourList *neighbour);
931 * Find an entry in the neighbour list for a particular peer.
933 * @return NULL if not found.
935 static struct NeighbourList *
936 find_neighbour (const struct GNUNET_PeerIdentity *key)
938 struct NeighbourList *head = neighbours;
940 while ((head != NULL) &&
941 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
948 * Find an entry in the transport list for a particular transport.
950 * @return NULL if not found.
952 static struct TransportPlugin *
953 find_transport (const char *short_name)
955 struct TransportPlugin *head = plugins;
956 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
962 * Is a particular peer blacklisted for a particular transport?
964 * @param peer the peer to check for
965 * @param plugin the plugin used to connect to the peer
967 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
970 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
973 if (plugin->blacklist != NULL)
975 if (GNUNET_CONTAINER_multihashmap_contains (plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979 "Peer `%s:%s' is blacklisted!\n",
980 plugin->short_name, GNUNET_i2s (peer));
983 GNUNET_STATISTICS_update (stats, "# blacklisted peers refused", 1, GNUNET_NO);
993 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
995 struct TransportPlugin *plugin;
997 plugin = find_transport(transport_name);
998 if (plugin == NULL) /* Nothing to do */
1000 if (plugin->blacklist == NULL)
1001 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
1002 GNUNET_assert(plugin->blacklist != NULL);
1003 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
1005 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1010 * Read the blacklist file, containing transport:peer entries.
1011 * Provided the transport is loaded, set up hashmap with these
1012 * entries to blacklist peers by transport.
1016 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1023 struct GNUNET_PeerIdentity pid;
1025 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1026 unsigned int entries_found;
1027 char *transport_name;
1030 GNUNET_CONFIGURATION_get_value_filename (cfg,
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037 "Option `%s' in section `%s' not specified!\n",
1043 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1044 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1045 | GNUNET_DISK_PERM_USER_WRITE);
1046 if (0 != STAT (fn, &frstat))
1048 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1049 _("Could not read blacklist file `%s'\n"), fn);
1053 if (frstat.st_size == 0)
1056 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057 _("Blacklist file `%s' is empty.\n"),
1063 /* FIXME: use mmap */
1064 data = GNUNET_malloc_large (frstat.st_size);
1065 GNUNET_assert(data != NULL);
1066 if (frstat.st_size !=
1067 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1069 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1070 _("Failed to read blacklist from `%s'\n"), fn);
1077 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1079 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1080 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1083 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1086 if (colon_pos >= frstat.st_size)
1088 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1089 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1090 (unsigned long long) colon_pos);
1096 if (isspace( (unsigned char) data[colon_pos]))
1098 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1100 (unsigned long long) colon_pos);
1102 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1106 tsize = colon_pos - pos;
1107 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1109 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1110 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1111 (unsigned long long) colon_pos);
1120 transport_name = GNUNET_malloc(tsize + 1);
1121 memcpy(transport_name, &data[pos], tsize);
1122 pos = colon_pos + 1;
1124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1125 "Read transport name %s in blacklist file.\n",
1128 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1129 if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1131 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1132 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1133 (unsigned long long) pos);
1135 while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1137 GNUNET_free_non_null(transport_name);
1140 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1141 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1143 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1144 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1145 (unsigned long long) pos,
1150 if (0 != memcmp (&pid,
1152 sizeof (struct GNUNET_PeerIdentity)))
1155 add_peer_to_blacklist (&pid,
1160 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1161 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1165 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1166 GNUNET_free_non_null(transport_name);
1167 while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1170 GNUNET_STATISTICS_update (stats, "# Transport entries blacklisted", entries_found, GNUNET_NO);
1177 * Function called to notify a client about the socket being ready to
1178 * queue more data. "buf" will be NULL and "size" zero if the socket
1179 * was closed for writing in the meantime.
1181 * @param cls closure
1182 * @param size number of bytes available in buf
1183 * @param buf where the callee should write the message
1184 * @return number of bytes written to buf
1187 transmit_to_client_callback (void *cls, size_t size, void *buf)
1189 struct TransportClient *client = cls;
1190 struct ClientMessageQueueEntry *q;
1193 const struct GNUNET_MessageHeader *msg;
1200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1201 "Transmission to client failed, closing connection.\n");
1203 /* fatal error with client, free message queue! */
1204 while (NULL != (q = client->message_queue_head))
1206 GNUNET_STATISTICS_update (stats,
1207 gettext_noop ("# bytes discarded (could not transmit to client)"),
1208 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1210 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1211 client->message_queue_tail,
1215 client->message_count = 0;
1220 while (NULL != (q = client->message_queue_head))
1222 msg = (const struct GNUNET_MessageHeader *) &q[1];
1223 msize = ntohs (msg->size);
1224 if (msize + tsize > size)
1227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1228 "Transmitting message of type %u to client.\n",
1231 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1232 client->message_queue_tail,
1234 memcpy (&cbuf[tsize], msg, msize);
1237 client->message_count--;
1241 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1242 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1244 GNUNET_TIME_UNIT_FOREVER_REL,
1245 &transmit_to_client_callback,
1247 GNUNET_assert (client->th != NULL);
1254 * Convert an address to a string.
1256 * @param plugin name of the plugin responsible for the address
1257 * @param addr binary address
1258 * @param addr_len number of bytes in addr
1259 * @return NULL on error, otherwise address string
1262 a2s (const char *plugin,
1266 struct TransportPlugin *p;
1270 p = find_transport (plugin);
1273 return p->api->address_to_string (p->api->cls,
1280 * Mark the given FAL entry as 'connected' (and hence preferred for
1281 * sending); also mark all others for the same peer as 'not connected'
1282 * (since only one can be preferred).
1284 * @param fal address to set to 'connected'
1287 mark_address_connected (struct ForeignAddressList *fal)
1289 struct ForeignAddressList *pos;
1292 GNUNET_assert (GNUNET_YES == fal->validated);
1293 if (fal->connected == GNUNET_YES)
1294 return; /* nothing to do */
1296 pos = fal->ready_list->addresses;
1299 if (GNUNET_YES == pos->connected)
1302 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1303 "Marking address `%s' as no longer connected (due to connect on other address)\n",
1304 a2s (pos->ready_list->plugin->short_name,
1308 GNUNET_break (cnt == GNUNET_YES);
1310 pos->connected = GNUNET_NO;
1311 GNUNET_STATISTICS_update (stats,
1312 gettext_noop ("# connected addresses"),
1318 fal->connected = GNUNET_YES;
1319 if (GNUNET_YES == cnt)
1321 GNUNET_STATISTICS_update (stats,
1322 gettext_noop ("# connected addresses"),
1330 * Send the specified message to the specified client. Since multiple
1331 * messages may be pending for the same client at a time, this code
1332 * makes sure that no message is lost.
1334 * @param client client to transmit the message to
1335 * @param msg the message to send
1336 * @param may_drop can this message be dropped if the
1337 * message queue for this client is getting far too large?
1340 transmit_to_client (struct TransportClient *client,
1341 const struct GNUNET_MessageHeader *msg, int may_drop)
1343 struct ClientMessageQueueEntry *q;
1346 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1348 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1350 ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1353 client->message_count,
1355 GNUNET_STATISTICS_update (stats,
1356 gettext_noop ("# messages dropped due to slow client"),
1361 msize = ntohs (msg->size);
1362 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1363 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1364 memcpy (&q[1], msg, msize);
1365 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1366 client->message_queue_tail,
1367 client->message_queue_tail,
1369 client->message_count++;
1370 if (client->th == NULL)
1372 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1374 GNUNET_TIME_UNIT_FOREVER_REL,
1375 &transmit_to_client_callback,
1377 GNUNET_assert (client->th != NULL);
1383 * Transmit a 'SEND_OK' notification to the given client for the
1386 * @param client who to notify
1387 * @param n neighbour to notify about, can be NULL (on failure)
1388 * @param target target of the transmission
1389 * @param result status code for the transmission request
1392 transmit_send_ok (struct TransportClient *client,
1393 struct NeighbourList *n,
1394 const struct GNUNET_PeerIdentity *target,
1397 struct SendOkMessage send_ok_msg;
1399 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1400 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1401 send_ok_msg.success = htonl (result);
1403 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1405 send_ok_msg.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
1406 send_ok_msg.peer = *target;
1407 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1412 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1413 * upon "completion" of a send request. This tells the API
1414 * that it is now legal to send another message to the given
1417 * @param cls closure, identifies the entry on the
1418 * message queue that was transmitted and the
1419 * client responsible for queuing the message
1420 * @param target the peer receiving the message
1421 * @param result GNUNET_OK on success, if the transmission
1422 * failed, we should not tell the client to transmit
1426 transmit_send_continuation (void *cls,
1427 const struct GNUNET_PeerIdentity *target,
1430 struct MessageQueue *mq = cls;
1431 struct NeighbourList *n;
1433 GNUNET_STATISTICS_update (stats,
1434 gettext_noop ("# bytes pending with plugins"),
1435 - (int64_t) mq->message_buf_size,
1437 if (result == GNUNET_OK)
1439 GNUNET_STATISTICS_update (stats,
1440 gettext_noop ("# bytes successfully transmitted by plugins"),
1441 mq->message_buf_size,
1446 GNUNET_STATISTICS_update (stats,
1447 gettext_noop ("# bytes with transmission failure by plugins"),
1448 mq->message_buf_size,
1451 if (mq->specific_address != NULL)
1453 if (result == GNUNET_OK)
1455 mq->specific_address->timeout =
1456 GNUNET_TIME_relative_to_absolute
1457 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1458 if (mq->specific_address->validated == GNUNET_YES)
1459 mark_address_connected (mq->specific_address);
1463 if (mq->specific_address->connected != GNUNET_NO)
1466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1467 "Marking address `%s' as no longer connected (due to transmission problem)\n",
1468 a2s (mq->specific_address->ready_list->plugin->short_name,
1469 mq->specific_address->addr,
1470 mq->specific_address->addrlen));
1472 GNUNET_STATISTICS_update (stats,
1473 gettext_noop ("# connected addresses"),
1476 mq->specific_address->connected = GNUNET_NO;
1479 if (! mq->internal_msg)
1480 mq->specific_address->in_transmit = GNUNET_NO;
1482 n = find_neighbour(&mq->neighbour_id);
1483 if (mq->client != NULL)
1484 transmit_send_ok (mq->client, n, target, result);
1487 try_transmission_to_peer (n);
1492 * Find an address in any of the available transports for
1493 * the given neighbour that would be good for message
1494 * transmission. This is essentially the transport selection
1497 * @param neighbour for whom to select an address
1498 * @return selected address, NULL if we have none
1500 struct ForeignAddressList *
1501 find_ready_address(struct NeighbourList *neighbour)
1503 struct ReadyList *head = neighbour->plugins;
1504 struct ForeignAddressList *addresses;
1505 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1506 struct ForeignAddressList *best_address;
1508 best_address = NULL;
1509 while (head != NULL)
1511 addresses = head->addresses;
1512 while (addresses != NULL)
1514 if ( (addresses->timeout.abs_value < now.abs_value) &&
1515 (addresses->connected == GNUNET_YES) )
1518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1519 "Marking long-time inactive connection to `%4s' as down.\n",
1520 GNUNET_i2s (&neighbour->id));
1522 GNUNET_STATISTICS_update (stats,
1523 gettext_noop ("# connected addresses"),
1526 addresses->connected = GNUNET_NO;
1528 addresses = addresses->next;
1531 addresses = head->addresses;
1532 while (addresses != NULL)
1534 #if DEBUG_TRANSPORT > 1
1535 if (addresses->addr != NULL)
1536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1537 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1538 a2s (head->plugin->short_name,
1540 addresses->addrlen),
1541 GNUNET_i2s (&neighbour->id),
1542 addresses->connected,
1543 addresses->in_transmit,
1544 addresses->validated,
1545 addresses->connect_attempts,
1546 (unsigned long long) addresses->timeout.abs_value,
1547 (unsigned int) addresses->distance);
1549 if ( ( (best_address == NULL) ||
1550 (addresses->connected == GNUNET_YES) ||
1551 (best_address->connected == GNUNET_NO) ) &&
1552 (addresses->in_transmit == GNUNET_NO) &&
1553 ( (best_address == NULL) ||
1554 (addresses->latency.rel_value < best_address->latency.rel_value)) )
1555 best_address = addresses;
1556 /* FIXME: also give lower-latency addresses that are not
1557 connected a chance some times... */
1558 addresses = addresses->next;
1562 if (best_address != NULL)
1565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1566 "Best address found (`%s') has latency of %llu ms.\n",
1567 (best_address->addrlen > 0)
1568 ? a2s (best_address->ready_list->plugin->short_name,
1570 best_address->addrlen)
1572 best_address->latency.rel_value);
1577 GNUNET_STATISTICS_update (stats,
1578 gettext_noop ("# transmission attempts failed (no address)"),
1582 return best_address;
1588 * We should re-try transmitting to the given peer,
1589 * hopefully we've learned something in the meantime.
1592 retry_transmission_task (void *cls,
1593 const struct GNUNET_SCHEDULER_TaskContext *tc)
1595 struct NeighbourList *n = cls;
1597 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1598 try_transmission_to_peer (n);
1603 * Check the ready list for the given neighbour and if a plugin is
1604 * ready for transmission (and if we have a message), do so!
1606 * @param neighbour target peer for which to transmit
1609 try_transmission_to_peer (struct NeighbourList *neighbour)
1611 struct ReadyList *rl;
1612 struct MessageQueue *mq;
1613 struct GNUNET_TIME_Relative timeout;
1617 if (neighbour->messages_head == NULL)
1620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1621 "Transmission queue for `%4s' is empty\n",
1622 GNUNET_i2s (&neighbour->id));
1624 return; /* nothing to do */
1627 mq = neighbour->messages_head;
1628 force_address = GNUNET_YES;
1629 if (mq->specific_address == NULL)
1631 mq->specific_address = find_ready_address(neighbour);
1632 GNUNET_STATISTICS_update (stats,
1633 gettext_noop ("# transport selected peer address freely"),
1636 force_address = GNUNET_NO;
1638 if (mq->specific_address == NULL)
1640 GNUNET_STATISTICS_update (stats,
1641 gettext_noop ("# transport failed to selected peer address"),
1644 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1645 if (timeout.rel_value == 0)
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649 "No destination address available to transmit message of size %u to peer `%4s'\n",
1650 mq->message_buf_size,
1651 GNUNET_i2s (&mq->neighbour_id));
1653 GNUNET_STATISTICS_update (stats,
1654 gettext_noop ("# bytes in message queue for other peers"),
1655 - (int64_t) mq->message_buf_size,
1657 GNUNET_STATISTICS_update (stats,
1658 gettext_noop ("# bytes discarded (no destination address available)"),
1659 mq->message_buf_size,
1661 if (mq->client != NULL)
1662 transmit_send_ok (mq->client, neighbour, &neighbour->id, GNUNET_NO);
1663 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1664 neighbour->messages_tail,
1667 return; /* nobody ready */
1669 GNUNET_STATISTICS_update (stats,
1670 gettext_noop ("# message delivery deferred (no address)"),
1673 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1674 GNUNET_SCHEDULER_cancel (neighbour->retry_task);
1675 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
1676 &retry_transmission_task,
1679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1681 mq->message_buf_size,
1682 GNUNET_i2s (&mq->neighbour_id),
1685 /* FIXME: might want to trigger peerinfo lookup here
1686 (unless that's already pending...) */
1689 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1690 neighbour->messages_tail,
1692 if (mq->specific_address->connected == GNUNET_NO)
1693 mq->specific_address->connect_attempts++;
1694 rl = mq->specific_address->ready_list;
1695 mq->plugin = rl->plugin;
1696 if (!mq->internal_msg)
1697 mq->specific_address->in_transmit = GNUNET_YES;
1699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1700 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1701 mq->message_buf_size,
1702 GNUNET_i2s (&neighbour->id),
1703 (mq->specific_address->addr != NULL)
1704 ? a2s (mq->plugin->short_name,
1705 mq->specific_address->addr,
1706 mq->specific_address->addrlen)
1708 rl->plugin->short_name);
1710 GNUNET_STATISTICS_update (stats,
1711 gettext_noop ("# bytes in message queue for other peers"),
1712 - (int64_t) mq->message_buf_size,
1714 GNUNET_STATISTICS_update (stats,
1715 gettext_noop ("# bytes pending with plugins"),
1716 mq->message_buf_size,
1718 ret = rl->plugin->api->send (rl->plugin->api->cls,
1721 mq->message_buf_size,
1723 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1724 mq->specific_address->session,
1725 mq->specific_address->addr,
1726 mq->specific_address->addrlen,
1728 &transmit_send_continuation, mq);
1731 /* failure, but 'send' would not call continuation in this case,
1732 so we need to do it here! */
1733 transmit_send_continuation (mq,
1741 * Send the specified message to the specified peer.
1743 * @param client source of the transmission request (can be NULL)
1744 * @param peer_address ForeignAddressList where we should send this message
1745 * @param priority how important is the message
1746 * @param timeout how long do we have to transmit?
1747 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1748 * @param message_buf_size total size of all messages in message_buf
1749 * @param is_internal is this an internal message; these are pre-pended and
1750 * also do not count for plugins being "ready" to transmit
1751 * @param neighbour handle to the neighbour for transmission
1754 transmit_to_peer (struct TransportClient *client,
1755 struct ForeignAddressList *peer_address,
1756 unsigned int priority,
1757 struct GNUNET_TIME_Relative timeout,
1758 const char *message_buf,
1759 size_t message_buf_size,
1760 int is_internal, struct NeighbourList *neighbour)
1762 struct MessageQueue *mq;
1767 /* check for duplicate submission */
1768 mq = neighbour->messages_head;
1771 if (mq->client == client)
1773 /* client transmitted to same peer twice
1774 before getting SEND_OK! */
1782 GNUNET_STATISTICS_update (stats,
1783 gettext_noop ("# bytes in message queue for other peers"),
1786 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1787 mq->specific_address = peer_address;
1788 mq->client = client;
1789 /* FIXME: this memcpy can be up to 7% of our total runtime! */
1790 memcpy (&mq[1], message_buf, message_buf_size);
1791 mq->message_buf = (const char*) &mq[1];
1792 mq->message_buf_size = message_buf_size;
1793 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1794 mq->internal_msg = is_internal;
1795 mq->priority = priority;
1796 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1798 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1799 neighbour->messages_tail,
1802 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1803 neighbour->messages_tail,
1804 neighbour->messages_tail,
1806 try_transmission_to_peer (neighbour);
1813 struct GeneratorContext
1815 struct TransportPlugin *plug_pos;
1816 struct OwnAddressList *addr_pos;
1817 struct GNUNET_TIME_Absolute expiration;
1825 address_generator (void *cls, size_t max, void *buf)
1827 struct GeneratorContext *gc = cls;
1830 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1832 gc->plug_pos = gc->plug_pos->next;
1833 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1835 if (NULL == gc->plug_pos)
1840 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1843 gc->addr_pos->addrlen, buf, max);
1844 gc->addr_pos = gc->addr_pos->next;
1850 * Construct our HELLO message from all of the addresses of
1851 * all of the transports.
1856 struct GNUNET_HELLO_Message *hello;
1857 struct TransportClient *cpos;
1858 struct NeighbourList *npos;
1859 struct GeneratorContext gc;
1861 gc.plug_pos = plugins;
1862 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1863 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1864 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1867 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1869 GNUNET_STATISTICS_update (stats,
1870 gettext_noop ("# refreshed my HELLO"),
1874 while (cpos != NULL)
1876 transmit_to_client (cpos,
1877 (const struct GNUNET_MessageHeader *) hello,
1882 GNUNET_free_non_null (our_hello);
1884 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1886 while (npos != NULL)
1889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1890 "Transmitting updated `%s' to neighbour `%4s'\n",
1891 "HELLO", GNUNET_i2s (&npos->id));
1893 GNUNET_STATISTICS_update (stats,
1894 gettext_noop ("# transmitted my HELLO to other peers"),
1897 transmit_to_peer (NULL, NULL, 0,
1898 HELLO_ADDRESS_EXPIRATION,
1899 (const char *) our_hello,
1900 GNUNET_HELLO_size(our_hello),
1908 * Task used to clean up expired addresses for a plugin.
1910 * @param cls closure
1914 expire_address_task (void *cls,
1915 const struct GNUNET_SCHEDULER_TaskContext *tc);
1919 * Update the list of addresses for this plugin,
1920 * expiring those that are past their expiration date.
1922 * @param plugin addresses of which plugin should be recomputed?
1923 * @param fresh set to GNUNET_YES if a new address was added
1924 * and we need to regenerate the HELLO even if nobody
1928 update_addresses (struct TransportPlugin *plugin,
1931 static struct GNUNET_TIME_Absolute last_update;
1932 struct GNUNET_TIME_Relative min_remaining;
1933 struct GNUNET_TIME_Relative remaining;
1934 struct GNUNET_TIME_Absolute now;
1935 struct OwnAddressList *pos;
1936 struct OwnAddressList *prev;
1937 struct OwnAddressList *next;
1940 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1941 GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1942 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1943 now = GNUNET_TIME_absolute_get ();
1944 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1945 expired = (GNUNET_TIME_absolute_get_duration (last_update).rel_value > (HELLO_ADDRESS_EXPIRATION.rel_value / 4));
1947 pos = plugin->addresses;
1951 if (pos->expires.abs_value < now.abs_value)
1953 expired = GNUNET_YES;
1955 plugin->addresses = pos->next;
1957 prev->next = pos->next;
1962 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1963 if (remaining.rel_value < min_remaining.rel_value)
1964 min_remaining = remaining;
1970 if (expired || fresh)
1975 min_remaining = GNUNET_TIME_relative_min (min_remaining,
1976 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1978 plugin->address_update_task
1979 = GNUNET_SCHEDULER_add_delayed (min_remaining,
1980 &expire_address_task, plugin);
1985 * Task used to clean up expired addresses for a plugin.
1987 * @param cls closure
1991 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1993 struct TransportPlugin *plugin = cls;
1995 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1996 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1997 update_addresses (plugin, GNUNET_NO);
2002 * Iterator over hash map entries that NULLs the session of validation
2003 * entries that match the given session.
2005 * @param cls closure (the 'struct Session*' to match against)
2006 * @param key current key code (peer ID, not used)
2007 * @param value value in the hash map ('struct ValidationEntry*')
2008 * @return GNUNET_YES (we should continue to iterate)
2011 remove_session_validations (void *cls,
2012 const GNUNET_HashCode * key,
2015 struct Session *session = cls;
2016 struct ValidationEntry *ve = value;
2018 if (session == ve->session)
2025 * We've been disconnected from the other peer (for some
2026 * connection-oriented transport). Either quickly
2027 * re-establish the connection or signal the disconnect
2030 * Only signal CORE level disconnect if ALL addresses
2031 * for the peer are exhausted.
2033 * @param p overall plugin context
2034 * @param nl neighbour that was disconnected
2037 try_fast_reconnect (struct TransportPlugin *p,
2038 struct NeighbourList *nl)
2040 /* FIXME-MW: fast reconnect / transport switching not implemented... */
2041 /* Note: the idea here is to hide problems with transports (or
2042 switching between plugins) from the core to eliminate the need to
2043 re-negotiate session keys and the like; OTOH, we should tell core
2044 quickly (much faster than timeout) `if a connection was lost and
2045 could not be re-established (i.e. other peer went down or is
2046 unable / refuses to communicate);
2048 So we should consider:
2049 1) ideally: our own willingness / need to connect
2050 2) prior failures to connect to this peer (by plugin)
2051 3) ideally: reasons why other peer terminated (as far as knowable)
2053 Most importantly, it must be POSSIBLE for another peer to terminate
2054 a connection for a while (without us instantly re-establishing it).
2055 Similarly, if another peer is gone we should quickly notify CORE.
2056 OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2057 on the other end), we should reconnect in such a way that BOTH CORE
2058 services never even notice.
2059 Furthermore, the same mechanism (or small variation) could be used
2060 to switch to a better-performing plugin (ATS).
2062 Finally, this needs to be tested throughly... */
2065 * GNUNET_NO in the call below makes transport disconnect the peer,
2066 * even if only a single address (out of say, six) went away. This
2067 * function must be careful to ONLY disconnect if the peer is gone,
2068 * not just a specifi address.
2070 * More specifically, half the places it was used had it WRONG.
2073 /* No reconnect, signal disconnect instead! */
2074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2075 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2076 "try_fast_reconnect");
2077 disconnect_neighbour (nl, GNUNET_YES);
2082 * Function that will be called whenever the plugin internally
2083 * cleans up a session pointer and hence the service needs to
2084 * discard all of those sessions as well. Plugins that do not
2085 * use sessions can simply omit calling this function and always
2086 * use NULL wherever a session pointer is needed.
2088 * @param cls closure
2089 * @param peer which peer was the session for
2090 * @param session which session is being destoyed
2093 plugin_env_session_end (void *cls,
2094 const struct GNUNET_PeerIdentity *peer,
2095 struct Session *session)
2097 struct TransportPlugin *p = cls;
2098 struct NeighbourList *nl;
2099 struct ReadyList *rl;
2100 struct ForeignAddressList *pos;
2101 struct ForeignAddressList *prev;
2103 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2104 &remove_session_validations,
2106 nl = find_neighbour (peer);
2108 return; /* was never marked as connected */
2112 if (rl->plugin == p)
2117 return; /* was never marked as connected */
2119 pos = rl->addresses;
2120 while ( (pos != NULL) &&
2121 (pos->session != session) )
2127 return; /* was never marked as connected */
2128 pos->session = NULL;
2129 if (pos->addrlen != 0)
2131 if (nl->received_pong != GNUNET_NO)
2132 try_fast_reconnect (p, nl);
2135 /* was inbound connection, free 'pos' */
2137 rl->addresses = pos->next;
2139 prev->next = pos->next;
2140 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2142 GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2143 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2146 if (nl->received_pong == GNUNET_NO)
2147 return; /* nothing to do, never connected... */
2148 /* check if we have any validated addresses left */
2149 pos = rl->addresses;
2154 try_fast_reconnect (p, nl);
2159 /* no valid addresses left, signal disconnect! */
2161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2163 "plugin_env_session_end");
2164 /* FIXME: This doesn't mean there are no addresses left for this PEER,
2165 * it means there aren't any left for this PLUGIN/PEER combination! So
2166 * calling disconnect_neighbor here with GNUNET_NO forces disconnect
2167 * when it isn't necessary. Using GNUNET_YES at least checks to see
2168 * if there are any addresses that work first, so as not to overdo it.
2171 disconnect_neighbour (nl, GNUNET_YES);
2176 * Function that must be called by each plugin to notify the
2177 * transport service about the addresses under which the transport
2178 * provided by the plugin can be reached.
2180 * @param cls closure
2181 * @param name name of the transport that generated the address
2182 * @param addr one of the addresses of the host, NULL for the last address
2183 * the specific address format depends on the transport
2184 * @param addrlen length of the address
2185 * @param expires when should this address automatically expire?
2188 plugin_env_notify_address (void *cls,
2192 struct GNUNET_TIME_Relative expires)
2194 struct TransportPlugin *p = cls;
2195 struct OwnAddressList *al;
2196 struct GNUNET_TIME_Absolute abex;
2198 GNUNET_assert (addr != NULL);
2199 abex = GNUNET_TIME_relative_to_absolute (expires);
2200 GNUNET_assert (p == find_transport (name));
2204 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2207 update_addresses (p, GNUNET_NO);
2213 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2214 al->next = p->addresses;
2217 al->addrlen = addrlen;
2218 memcpy (&al[1], addr, addrlen);
2219 update_addresses (p, GNUNET_YES);
2224 * Notify all of our clients about a peer connecting.
2227 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2228 struct GNUNET_TIME_Relative latency,
2231 struct ConnectInfoMessage * cim;
2232 struct TransportClient *cpos;
2237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2238 "Notifying clients about connection from `%s'\n",
2241 GNUNET_STATISTICS_update (stats,
2242 gettext_noop ("# peers connected"),
2247 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
2248 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2252 cim = GNUNET_malloc (size);
2254 cim->header.size = htons (size);
2255 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2256 cim->ats_count = htonl(2);
2257 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2258 (&(cim->ats))[0].value = htonl (distance);
2259 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
2260 (&(cim->ats))[1].value = htonl ((uint32_t) latency.rel_value);
2261 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2262 (&(cim->ats))[2].value = htonl (0);
2263 memcpy (&cim->id, peer, sizeof (struct GNUNET_PeerIdentity));
2265 while (cpos != NULL)
2267 transmit_to_client (cpos, &(cim->header), GNUNET_NO);
2275 * Notify all of our clients about a peer disconnecting.
2278 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2280 struct DisconnectInfoMessage dim;
2281 struct TransportClient *cpos;
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "Notifying clients about lost connection to `%s'\n",
2288 GNUNET_STATISTICS_update (stats,
2289 gettext_noop ("# peers connected"),
2292 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2293 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2294 dim.reserved = htonl (0);
2295 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2297 while (cpos != NULL)
2299 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2306 * Find a ForeignAddressList entry for the given neighbour
2307 * that matches the given address and transport.
2309 * @param neighbour which peer we care about
2310 * @param tname name of the transport plugin
2311 * @param session session to look for, NULL for 'any'; otherwise
2312 * can be used for the service to "learn" this session ID
2314 * @param addr binary address
2315 * @param addrlen length of addr
2316 * @return NULL if no such entry exists
2318 static struct ForeignAddressList *
2319 find_peer_address(struct NeighbourList *neighbour,
2321 struct Session *session,
2325 struct ReadyList *head;
2326 struct ForeignAddressList *pos;
2328 head = neighbour->plugins;
2329 while (head != NULL)
2331 if (0 == strcmp (tname, head->plugin->short_name))
2337 pos = head->addresses;
2338 while ( (pos != NULL) &&
2339 ( (pos->addrlen != addrlen) ||
2340 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2342 if ( (session != NULL) &&
2343 (pos->session == session) )
2347 if ( (session != NULL) && (pos != NULL) )
2348 pos->session = session; /* learn it! */
2354 * Get the peer address struct for the given neighbour and
2355 * address. If it doesn't yet exist, create it.
2357 * @param neighbour which peer we care about
2358 * @param tname name of the transport plugin
2359 * @param session session of the plugin, or NULL for none
2360 * @param addr binary address
2361 * @param addrlen length of addr
2362 * @return NULL if we do not have a transport plugin for 'tname'
2364 static struct ForeignAddressList *
2365 add_peer_address (struct NeighbourList *neighbour,
2367 struct Session *session,
2371 struct ReadyList *head;
2372 struct ForeignAddressList *ret;
2374 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2377 head = neighbour->plugins;
2379 while (head != NULL)
2381 if (0 == strcmp (tname, head->plugin->short_name))
2387 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2388 ret->session = session;
2391 ret->addr = (const char*) &ret[1];
2392 memcpy (&ret[1], addr, addrlen);
2398 ret->addrlen = addrlen;
2399 ret->expires = GNUNET_TIME_relative_to_absolute
2400 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2401 ret->latency = GNUNET_TIME_relative_get_forever();
2403 ret->timeout = GNUNET_TIME_relative_to_absolute
2404 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2405 ret->ready_list = head;
2406 ret->next = head->addresses;
2407 head->addresses = ret;
2413 * Closure for 'add_validated_address'.
2415 struct AddValidatedAddressContext
2418 * Entry that has been validated.
2420 const struct ValidationEntry *ve;
2423 * Flag set after we have added the address so
2424 * that we terminate the iteration next time.
2431 * Callback function used to fill a buffer of max bytes with a list of
2432 * addresses in the format used by HELLOs. Should use
2433 * "GNUNET_HELLO_add_address" as a helper function.
2435 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2436 * @param max maximum number of bytes that can be written to buf
2437 * @param buf where to write the address information
2438 * @return number of bytes written, 0 to signal the
2439 * end of the iteration.
2442 add_validated_address (void *cls,
2443 size_t max, void *buf)
2445 struct AddValidatedAddressContext *avac = cls;
2446 const struct ValidationEntry *ve = avac->ve;
2448 if (GNUNET_YES == avac->done)
2450 avac->done = GNUNET_YES;
2451 return GNUNET_HELLO_add_address (ve->transport_name,
2452 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2462 * Closure for 'check_address_exists'.
2464 struct CheckAddressExistsClosure
2467 * Address to check for.
2472 * Name of the transport.
2479 struct Session *session;
2482 * Set to GNUNET_YES if the address exists.
2495 * Iterator over hash map entries. Checks if the given
2496 * validation entry is for the same address as what is given
2499 * @param cls the 'struct CheckAddressExistsClosure*'
2500 * @param key current key code (ignored)
2501 * @param value value in the hash map ('struct ValidationEntry')
2502 * @return GNUNET_YES if we should continue to
2503 * iterate (mismatch), GNUNET_NO if not (entry matched)
2506 check_address_exists (void *cls,
2507 const GNUNET_HashCode * key,
2510 struct CheckAddressExistsClosure *caec = cls;
2511 struct ValidationEntry *ve = value;
2513 if ( (0 == strcmp (caec->tname,
2514 ve->transport_name)) &&
2515 (caec->addrlen == ve->addrlen) &&
2516 (0 == memcmp (caec->addr,
2520 caec->exists = GNUNET_YES;
2523 if ( (ve->session != NULL) &&
2524 (caec->session == ve->session) )
2526 caec->exists = GNUNET_YES;
2535 * Iterator to free entries in the validation_map.
2537 * @param cls closure (unused)
2538 * @param key current key code
2539 * @param value value in the hash map (validation to abort)
2540 * @return GNUNET_YES (always)
2543 abort_validation (void *cls,
2544 const GNUNET_HashCode * key,
2547 struct ValidationEntry *va = value;
2549 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2550 GNUNET_SCHEDULER_cancel (va->timeout_task);
2551 GNUNET_free (va->transport_name);
2552 if (va->chvc != NULL)
2554 va->chvc->ve_count--;
2555 if (va->chvc->ve_count == 0)
2557 GNUNET_CONTAINER_DLL_remove (chvc_head,
2560 GNUNET_free (va->chvc);
2570 * HELLO validation cleanup task (validation failed).
2572 * @param cls the 'struct ValidationEntry' that failed
2573 * @param tc scheduler context (unused)
2576 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2578 struct ValidationEntry *va = cls;
2579 struct GNUNET_PeerIdentity pid;
2581 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2582 GNUNET_STATISTICS_update (stats,
2583 gettext_noop ("# address validation timeouts"),
2586 GNUNET_CRYPTO_hash (&va->publicKey,
2588 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2590 GNUNET_break (GNUNET_OK ==
2591 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2594 abort_validation (NULL, NULL, va);
2599 neighbour_timeout_task (void *cls,
2600 const struct GNUNET_SCHEDULER_TaskContext *tc)
2602 struct NeighbourList *n = cls;
2605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2606 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2608 GNUNET_STATISTICS_update (stats,
2609 gettext_noop ("# disconnects due to timeout"),
2612 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2613 disconnect_neighbour (n, GNUNET_NO);
2618 * Schedule the job that will cause us to send a PING to the
2619 * foreign address to evaluate its validity and latency.
2621 * @param fal address to PING
2624 schedule_next_ping (struct ForeignAddressList *fal);
2628 * Add the given address to the list of foreign addresses
2629 * available for the given peer (check for duplicates).
2631 * @param cls the respective 'struct NeighbourList' to update
2632 * @param tname name of the transport
2633 * @param expiration expiration time
2634 * @param addr the address
2635 * @param addrlen length of the address
2636 * @return GNUNET_OK (always)
2639 add_to_foreign_address_list (void *cls,
2641 struct GNUNET_TIME_Absolute expiration,
2645 struct NeighbourList *n = cls;
2646 struct ForeignAddressList *fal;
2649 GNUNET_STATISTICS_update (stats,
2650 gettext_noop ("# valid peer addresses returned by PEERINFO"),
2654 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2657 #if DEBUG_TRANSPORT_HELLO
2658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2659 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2660 a2s (tname, addr, addrlen),
2662 GNUNET_i2s (&n->id),
2663 expiration.abs_value);
2665 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2668 GNUNET_STATISTICS_update (stats,
2669 gettext_noop ("# previously validated addresses lacking transport"),
2675 fal->expires = GNUNET_TIME_absolute_max (expiration,
2677 schedule_next_ping (fal);
2683 fal->expires = GNUNET_TIME_absolute_max (expiration,
2688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689 "Failed to add new address for `%4s'\n",
2690 GNUNET_i2s (&n->id));
2693 if (fal->validated == GNUNET_NO)
2695 fal->validated = GNUNET_YES;
2696 GNUNET_STATISTICS_update (stats,
2697 gettext_noop ("# peer addresses considered valid"),
2701 if (try == GNUNET_YES)
2703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704 "Have new addresses, will try to trigger transmissions.\n");
2705 try_transmission_to_peer (n);
2712 * Add addresses in validated HELLO "h" to the set of addresses
2713 * we have for this peer.
2715 * @param cls closure ('struct NeighbourList*')
2716 * @param peer id of the peer, NULL for last call
2717 * @param h hello message for the peer (can be NULL)
2718 * @param err_msg NULL if successful, otherwise contains error message
2721 add_hello_for_peer (void *cls,
2722 const struct GNUNET_PeerIdentity *peer,
2723 const struct GNUNET_HELLO_Message *h,
2724 const char *err_msg)
2726 struct NeighbourList *n = cls;
2728 if (err_msg != NULL)
2730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2731 _("Error in communication with PEERINFO service\n"));
2736 GNUNET_STATISTICS_update (stats,
2737 gettext_noop ("# outstanding peerinfo iterate requests"),
2744 return; /* no HELLO available */
2746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2747 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2751 if (GNUNET_YES != n->public_key_valid)
2753 GNUNET_HELLO_get_key (h, &n->publicKey);
2754 n->public_key_valid = GNUNET_YES;
2756 GNUNET_HELLO_iterate_addresses (h,
2758 &add_to_foreign_address_list,
2764 * Create a fresh entry in our neighbour list for the given peer.
2765 * Will try to transmit our current HELLO to the new neighbour.
2766 * Do not call this function directly, use 'setup_peer_check_blacklist.
2768 * @param peer the peer for which we create the entry
2769 * @param do_hello should we schedule transmitting a HELLO
2770 * @return the new neighbour list entry
2772 static struct NeighbourList *
2773 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2776 struct NeighbourList *n;
2777 struct TransportPlugin *tp;
2778 struct ReadyList *rl;
2781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2782 "Setting up state for neighbour `%4s'\n",
2785 GNUNET_assert (our_hello != NULL);
2786 GNUNET_STATISTICS_update (stats,
2787 gettext_noop ("# active neighbours"),
2790 n = GNUNET_malloc (sizeof (struct NeighbourList));
2791 n->next = neighbours;
2795 GNUNET_TIME_relative_to_absolute
2796 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2797 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2798 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2799 MAX_BANDWIDTH_CARRY_S);
2803 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2805 rl = GNUNET_malloc (sizeof (struct ReadyList));
2807 rl->next = n->plugins;
2810 rl->addresses = NULL;
2814 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2816 n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2817 &neighbour_timeout_task, n);
2820 GNUNET_STATISTICS_update (stats,
2821 gettext_noop ("# peerinfo new neighbor iterate requests"),
2824 GNUNET_STATISTICS_update (stats,
2825 gettext_noop ("# outstanding peerinfo iterate requests"),
2828 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2829 GNUNET_TIME_UNIT_FOREVER_REL,
2830 &add_hello_for_peer, n);
2832 GNUNET_STATISTICS_update (stats,
2833 gettext_noop ("# HELLO's sent to new neighbors"),
2836 transmit_to_peer (NULL, NULL, 0,
2837 HELLO_ADDRESS_EXPIRATION,
2838 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2846 * Function called after we have checked if communicating
2847 * with a given peer is acceptable.
2849 * @param cls closure
2850 * @param n NULL if communication is not acceptable
2852 typedef void (*SetupContinuation)(void *cls,
2853 struct NeighbourList *n);
2857 * Information kept for each client registered to perform
2863 * This is a linked list.
2865 struct Blacklisters *next;
2868 * This is a linked list.
2870 struct Blacklisters *prev;
2873 * Client responsible for this entry.
2875 struct GNUNET_SERVER_Client *client;
2878 * Blacklist check that we're currently performing.
2880 struct BlacklistCheck *bc;
2886 * Head of DLL of blacklisting clients.
2888 static struct Blacklisters *bl_head;
2891 * Tail of DLL of blacklisting clients.
2893 static struct Blacklisters *bl_tail;
2897 * Context we use when performing a blacklist check.
2899 struct BlacklistCheck
2903 * This is a linked list.
2905 struct BlacklistCheck *next;
2908 * This is a linked list.
2910 struct BlacklistCheck *prev;
2913 * Peer being checked.
2915 struct GNUNET_PeerIdentity peer;
2918 * Option for setup neighbour afterwards.
2923 * Continuation to call with the result.
2925 SetupContinuation cont;
2933 * Current transmission request handle for this client, or NULL if no
2934 * request is pending.
2936 struct GNUNET_CONNECTION_TransmitHandle *th;
2939 * Our current position in the blacklisters list.
2941 struct Blacklisters *bl_pos;
2944 * Current task performing the check.
2946 GNUNET_SCHEDULER_TaskIdentifier task;
2951 * Head of DLL of active blacklisting queries.
2953 static struct BlacklistCheck *bc_head;
2956 * Tail of DLL of active blacklisting queries.
2958 static struct BlacklistCheck *bc_tail;
2962 * Perform next action in the blacklist check.
2964 * @param cls the 'struct BlacklistCheck*'
2968 do_blacklist_check (void *cls,
2969 const struct GNUNET_SCHEDULER_TaskContext *tc);
2973 * Transmit blacklist query to the client.
2975 * @param cls the 'struct BlacklistCheck'
2976 * @param size number of bytes allowed
2977 * @param buf where to copy the message
2978 * @return number of bytes copied to buf
2981 transmit_blacklist_message (void *cls,
2985 struct BlacklistCheck *bc = cls;
2986 struct Blacklisters *bl;
2987 struct BlacklistMessage bm;
2992 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2993 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
2998 bm.header.size = htons (sizeof (struct BlacklistMessage));
2999 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
3000 bm.is_allowed = htonl (0);
3002 memcpy (buf, &bm, sizeof (bm));
3003 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
3009 * Perform next action in the blacklist check.
3011 * @param cls the 'struct BlacklistCheck*'
3015 do_blacklist_check (void *cls,
3016 const struct GNUNET_SCHEDULER_TaskContext *tc)
3018 struct BlacklistCheck *bc = cls;
3019 struct Blacklisters *bl;
3021 bc->task = GNUNET_SCHEDULER_NO_TASK;
3025 bc->cont (bc->cont_cls,
3026 setup_new_neighbour (&bc->peer, bc->do_hello));
3033 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
3034 sizeof (struct BlacklistMessage),
3035 GNUNET_TIME_UNIT_FOREVER_REL,
3036 &transmit_blacklist_message,
3043 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
3044 * does not yet exist, check the blacklist. If the blacklist says creating
3045 * one is acceptable, create one and call the continuation; otherwise
3046 * call the continuation with NULL.
3048 * @param peer peer to setup or look up a struct NeighbourList for
3049 * @param do_hello should we also schedule sending our HELLO to the peer
3050 * if this is a new record
3051 * @param cont function to call with the 'struct NeigbhbourList*'
3052 * @param cont_cls closure for cont
3055 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3057 SetupContinuation cont,
3060 struct NeighbourList *n;
3061 struct BlacklistCheck *bc;
3063 n = find_neighbour(peer);
3070 if (bl_head == NULL)
3073 cont (cont_cls, setup_new_neighbour (peer, do_hello));
3075 setup_new_neighbour(peer, do_hello);
3078 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3079 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3081 bc->do_hello = do_hello;
3083 bc->cont_cls = cont_cls;
3084 bc->bl_pos = bl_head;
3085 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3091 * Function called with the result of querying a new blacklister about
3092 * it being allowed (or not) to continue to talk to an existing neighbour.
3094 * @param cls the original 'struct NeighbourList'
3095 * @param n NULL if we need to disconnect
3098 confirm_or_drop_neighbour (void *cls,
3099 struct NeighbourList *n)
3101 struct NeighbourList * orig = cls;
3105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3106 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3107 "confirm_or_drop_neighboUr");
3108 disconnect_neighbour (orig, GNUNET_NO);
3114 * Handle a request to start a blacklist.
3116 * @param cls closure (always NULL)
3117 * @param client identification of the client
3118 * @param message the actual message
3121 handle_blacklist_init (void *cls,
3122 struct GNUNET_SERVER_Client *client,
3123 const struct GNUNET_MessageHeader *message)
3125 struct Blacklisters *bl;
3126 struct BlacklistCheck *bc;
3127 struct NeighbourList *n;
3132 if (bl->client == client)
3135 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3140 bl = GNUNET_malloc (sizeof (struct Blacklisters));
3141 bl->client = client;
3142 GNUNET_SERVER_client_keep (client);
3143 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3144 /* confirm that all existing connections are OK! */
3148 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3149 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3151 bc->do_hello = GNUNET_NO;
3152 bc->cont = &confirm_or_drop_neighbour;
3155 if (n == neighbours) /* all would wait for the same client, no need to
3156 create more than just the first task right now */
3157 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3165 * Handle a request to blacklist a peer.
3167 * @param cls closure (always NULL)
3168 * @param client identification of the client
3169 * @param message the actual message
3172 handle_blacklist_reply (void *cls,
3173 struct GNUNET_SERVER_Client *client,
3174 const struct GNUNET_MessageHeader *message)
3176 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3177 struct Blacklisters *bl;
3178 struct BlacklistCheck *bc;
3181 while ( (bl != NULL) &&
3182 (bl->client != client) )
3186 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3191 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3193 bc->cont (bc->cont_cls, NULL);
3194 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3199 bc->bl_pos = bc->bl_pos->next;
3200 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3203 /* check if any other bc's are waiting for this blacklister */
3207 if ( (bc->bl_pos == bl) &&
3208 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3209 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3217 * Send periodic PING messages to a given foreign address.
3219 * @param cls our 'struct PeriodicValidationContext*'
3220 * @param tc task context
3223 send_periodic_ping (void *cls,
3224 const struct GNUNET_SCHEDULER_TaskContext *tc)
3226 struct ForeignAddressList *peer_address = cls;
3227 struct TransportPlugin *tp;
3228 struct ValidationEntry *va;
3229 struct NeighbourList *neighbour;
3230 struct TransportPingMessage ping;
3231 struct CheckAddressExistsClosure caec;
3233 uint16_t hello_size;
3237 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3238 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3240 tp = peer_address->ready_list->plugin;
3241 neighbour = peer_address->ready_list->neighbour;
3242 if (GNUNET_YES != neighbour->public_key_valid)
3244 /* no public key yet, try again later */
3245 schedule_next_ping (peer_address);
3248 caec.addr = peer_address->addr;
3249 caec.addrlen = peer_address->addrlen;
3250 caec.tname = tp->short_name;
3251 caec.session = peer_address->session;
3252 caec.exists = GNUNET_NO;
3253 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3254 &check_address_exists,
3256 if (caec.exists == GNUNET_YES)
3258 /* During validation attempts we will likely trigger the other
3259 peer trying to validate our address which in turn will cause
3260 it to send us its HELLO, so we expect to hit this case rather
3261 frequently. Only print something if we are very verbose. */
3262 #if DEBUG_TRANSPORT > 1
3263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3264 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3265 (peer_address->addr != NULL)
3266 ? a2s (tp->short_name,
3268 peer_address->addrlen)
3271 GNUNET_i2s (&neighbour->id));
3273 schedule_next_ping (peer_address);
3276 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3277 va->transport_name = GNUNET_strdup (tp->short_name);
3278 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3280 va->send_time = GNUNET_TIME_absolute_get();
3281 va->session = peer_address->session;
3282 if (peer_address->addr != NULL)
3284 va->addr = (const void*) &va[1];
3285 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3286 va->addrlen = peer_address->addrlen;
3288 memcpy(&va->publicKey,
3289 &neighbour->publicKey,
3290 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3292 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3293 &timeout_hello_validation,
3295 GNUNET_CONTAINER_multihashmap_put (validation_map,
3296 &neighbour->id.hashPubKey,
3298 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3300 if (peer_address->validated != GNUNET_YES)
3301 hello_size = GNUNET_HELLO_size(our_hello);
3305 tsize = sizeof(struct TransportPingMessage) + hello_size;
3307 if (peer_address->addr != NULL)
3309 slen = strlen (tp->short_name) + 1;
3310 tsize += slen + peer_address->addrlen;
3314 slen = 0; /* make gcc happy */
3316 message_buf = GNUNET_malloc(tsize);
3317 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3318 ping.challenge = htonl(va->challenge);
3319 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3320 if (peer_address->validated != GNUNET_YES)
3322 memcpy(message_buf, our_hello, hello_size);
3325 if (peer_address->addr != NULL)
3327 ping.header.size = htons(sizeof(struct TransportPingMessage) +
3328 peer_address->addrlen +
3330 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3333 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3335 peer_address->addrlen);
3339 ping.header.size = htons(sizeof(struct TransportPingMessage));
3342 memcpy(&message_buf[hello_size],
3344 sizeof(struct TransportPingMessage));
3346 #if DEBUG_TRANSPORT_REVALIDATION
3347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3348 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3349 (peer_address->addr != NULL)
3350 ? a2s (peer_address->plugin->short_name,
3352 peer_address->addrlen)
3355 GNUNET_i2s (&neighbour->id),
3356 "HELLO", hello_size,
3359 if (peer_address->validated != GNUNET_YES)
3360 GNUNET_STATISTICS_update (stats,
3361 gettext_noop ("# PING with HELLO messages sent"),
3365 GNUNET_STATISTICS_update (stats,
3366 gettext_noop ("# PING without HELLO messages sent"),
3369 GNUNET_STATISTICS_update (stats,
3370 gettext_noop ("# PING messages sent for re-validation"),
3373 transmit_to_peer (NULL, peer_address,
3374 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3375 HELLO_VERIFICATION_TIMEOUT,
3377 GNUNET_YES, neighbour);
3378 GNUNET_free(message_buf);
3379 schedule_next_ping (peer_address);
3384 * Schedule the job that will cause us to send a PING to the
3385 * foreign address to evaluate its validity and latency.
3387 * @param fal address to PING
3390 schedule_next_ping (struct ForeignAddressList *fal)
3392 struct GNUNET_TIME_Relative delay;
3394 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3396 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3397 delay.rel_value /= 2; /* do before expiration */
3398 delay = GNUNET_TIME_relative_min (delay,
3399 LATENCY_EVALUATION_MAX_DELAY);
3400 if (GNUNET_YES != fal->estimated)
3402 delay = GNUNET_TIME_UNIT_ZERO;
3403 fal->estimated = GNUNET_YES;
3405 if (GNUNET_YES == fal->connected)
3407 delay = GNUNET_TIME_relative_min (delay,
3408 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3410 /* FIXME: also adjust delay based on how close the last
3411 observed latency is to the latency of the best alternative */
3412 /* bound how fast we can go */
3413 delay = GNUNET_TIME_relative_max (delay,
3414 GNUNET_TIME_UNIT_SECONDS);
3415 /* randomize a bit (to avoid doing all at the same time) */
3416 delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3417 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3418 &send_periodic_ping,
3426 * Function that will be called if we receive some payload
3427 * from another peer.
3429 * @param message the payload
3430 * @param n peer who claimed to be the sender
3433 handle_payload_message (const struct GNUNET_MessageHeader *message,
3434 struct NeighbourList *n)
3436 struct InboundMessage *im;
3437 struct TransportClient *cpos;
3440 msize = ntohs (message->size);
3441 if (n->received_pong == GNUNET_NO)
3443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3444 "Received message of type %u and size %u from `%4s', but no pong yet!!\n",
3445 ntohs (message->type),
3446 ntohs (message->size),
3447 GNUNET_i2s (&n->id));
3448 GNUNET_free_non_null (n->pre_connect_message_buffer);
3449 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3450 memcpy (n->pre_connect_message_buffer, message, msize);
3455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3456 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3457 ntohs (message->type),
3458 ntohs (message->size),
3459 GNUNET_i2s (&n->id));
3461 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3464 n->quota_violation_count++;
3466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3467 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3468 n->in_tracker.available_bytes_per_s__,
3469 n->quota_violation_count);
3471 /* Discount 32k per violation */
3472 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3477 if (n->quota_violation_count > 0)
3479 /* try to add 32k back */
3480 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3482 n->quota_violation_count--;
3485 GNUNET_STATISTICS_update (stats,
3486 gettext_noop ("# payload received from other peers"),
3489 /* transmit message to all clients */
3490 uint32_t ats_count = 2;
3491 size_t size = sizeof (struct InboundMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) + msize;
3492 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3495 im = GNUNET_malloc (size);
3496 im->header.size = htons (size);
3497 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3499 im->ats_count = htonl(ats_count);
3500 /* Setting ATS data */
3501 (&(im->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
3502 (&(im->ats))[0].value = htonl (n->distance);
3503 (&(im->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
3504 (&(im->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
3505 (&(im->ats))[ats_count].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
3506 (&(im->ats))[ats_count].value = htonl (0);
3508 memcpy (&((&(im->ats))[ats_count+1]), message, msize);
3510 while (cpos != NULL)
3512 transmit_to_client (cpos, &im->header, GNUNET_YES);
3520 * Iterator over hash map entries. Checks if the given validation
3521 * entry is for the same challenge as what is given in the PONG.
3523 * @param cls the 'struct TransportPongMessage*'
3524 * @param key peer identity
3525 * @param value value in the hash map ('struct ValidationEntry')
3526 * @return GNUNET_YES if we should continue to
3527 * iterate (mismatch), GNUNET_NO if not (entry matched)
3530 check_pending_validation (void *cls,
3531 const GNUNET_HashCode * key,
3534 const struct TransportPongMessage *pong = cls;
3535 struct ValidationEntry *ve = value;
3536 struct AddValidatedAddressContext avac;
3537 unsigned int challenge = ntohl(pong->challenge);
3538 struct GNUNET_HELLO_Message *hello;
3539 struct GNUNET_PeerIdentity target;
3540 struct NeighbourList *n;
3541 struct ForeignAddressList *fal;
3542 struct OwnAddressList *oal;
3543 struct TransportPlugin *tp;
3544 struct GNUNET_MessageHeader *prem;
3550 ps = ntohs (pong->header.size);
3551 if (ps < sizeof (struct TransportPongMessage))
3553 GNUNET_break_op (0);
3556 addr = (const char*) &pong[1];
3557 slen = strlen (ve->transport_name) + 1;
3558 if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
3559 (ve->challenge != challenge) ||
3560 (addr[slen-1] != '\0') ||
3561 (0 != strcmp (addr, ve->transport_name)) ||
3562 (ntohl (pong->purpose.size)
3563 != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3565 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3566 sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
3571 alen = ps - sizeof (struct TransportPongMessage) - slen;
3572 switch (ntohl (pong->purpose.purpose))
3574 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
3575 if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
3576 (0 != memcmp (&addr[slen],
3580 return GNUNET_YES; /* different entry, keep trying! */
3582 if (0 != memcmp (&pong->pid,
3584 sizeof (struct GNUNET_PeerIdentity)))
3586 GNUNET_break_op (0);
3590 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
3595 GNUNET_break_op (0);
3600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3601 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3603 a2s (ve->transport_name,
3604 (const struct sockaddr *) ve->addr,
3606 ve->transport_name);
3609 case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
3610 if (0 != memcmp (&pong->pid,
3612 sizeof (struct GNUNET_PeerIdentity)))
3614 GNUNET_break_op (0);
3617 if (ve->addrlen != 0)
3619 /* must have been for a different validation entry */
3622 tp = find_transport (ve->transport_name);
3628 oal = tp->addresses;
3631 if ( (oal->addrlen == alen) &&
3632 (0 == memcmp (&oal[1],
3640 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3641 _("Not accepting PONG with address `%s' since I cannot confirm having this address.\n"),
3642 a2s (ve->transport_name,
3648 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
3653 GNUNET_break_op (0);
3658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3659 "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
3661 a2s (ve->transport_name,
3664 ve->transport_name);
3668 GNUNET_break_op (0);
3671 if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
3673 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3674 _("Received expired signature. Check system time.\n"));
3677 GNUNET_STATISTICS_update (stats,
3678 gettext_noop ("# address validation successes"),
3681 /* create the updated HELLO */
3682 GNUNET_CRYPTO_hash (&ve->publicKey,
3683 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3684 &target.hashPubKey);
3685 if (ve->addr != NULL)
3687 avac.done = GNUNET_NO;
3689 hello = GNUNET_HELLO_create (&ve->publicKey,
3690 &add_validated_address,
3692 GNUNET_PEERINFO_add_peer (peerinfo,
3694 GNUNET_free (hello);
3696 n = find_neighbour (&target);
3699 n->publicKey = ve->publicKey;
3700 n->public_key_valid = GNUNET_YES;
3701 fal = add_peer_address (n,
3706 GNUNET_assert (fal != NULL);
3707 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3708 fal->validated = GNUNET_YES;
3709 mark_address_connected (fal);
3710 GNUNET_STATISTICS_update (stats,
3711 gettext_noop ("# peer addresses considered valid"),
3714 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3715 schedule_next_ping (fal);
3716 if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3717 n->latency = fal->latency;
3719 n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
3721 n->distance = fal->distance;
3722 if (GNUNET_NO == n->received_pong)
3724 n->received_pong = GNUNET_YES;
3725 notify_clients_connect (&target, n->latency, n->distance);
3726 if (NULL != (prem = n->pre_connect_message_buffer))
3728 n->pre_connect_message_buffer = NULL;
3729 handle_payload_message (prem, n);
3733 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3735 GNUNET_SCHEDULER_cancel (n->retry_task);
3736 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3737 try_transmission_to_peer (n);
3741 /* clean up validation entry */
3742 GNUNET_assert (GNUNET_YES ==
3743 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3746 abort_validation (NULL, NULL, ve);
3752 * Function that will be called if we receive a validation
3753 * of an address challenge that we transmitted to another
3754 * peer. Note that the validation should only be considered
3755 * acceptable if the challenge matches AND if the sender
3756 * address is at least a plausible address for this peer
3757 * (otherwise we may be seeing a MiM attack).
3759 * @param cls closure
3760 * @param message the pong message
3761 * @param peer who responded to our challenge
3762 * @param sender_address string describing our sender address (as observed
3763 * by the other peer in binary format)
3764 * @param sender_address_len number of bytes in 'sender_address'
3767 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3768 const struct GNUNET_PeerIdentity *peer,
3769 const char *sender_address,
3770 size_t sender_address_len)
3772 #if DEBUG_TRANSPORT > 1
3773 /* we get tons of these that just get discarded, only log
3774 if we are quite verbose */
3775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3776 "Receiving `%s' message from `%4s'.\n", "PONG",
3779 GNUNET_STATISTICS_update (stats,
3780 gettext_noop ("# PONG messages received"),
3783 if (GNUNET_SYSERR !=
3784 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3786 &check_pending_validation,
3789 /* This is *expected* to happen a lot since we send
3790 PONGs to *all* known addresses of the sender of
3791 the PING, so most likely we get multiple PONGs
3792 per PING, and all but the first PONG will end up
3793 here. So really we should not print anything here
3794 unless we want to be very, very verbose... */
3795 #if DEBUG_TRANSPORT > 2
3796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3797 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3809 * Try to validate a neighbour's address by sending him our HELLO and a PING.
3811 * @param cls the 'struct ValidationEntry*'
3812 * @param neighbour neighbour to validate, NULL if validation failed
3815 transmit_hello_and_ping (void *cls,
3816 struct NeighbourList *neighbour)
3818 struct ValidationEntry *va = cls;
3819 struct ForeignAddressList *peer_address;
3820 struct TransportPingMessage ping;
3821 uint16_t hello_size;
3824 struct GNUNET_PeerIdentity id;
3827 GNUNET_CRYPTO_hash (&va->publicKey,
3828 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3830 if (neighbour == NULL)
3832 /* FIXME: stats... */
3833 GNUNET_break (GNUNET_OK ==
3834 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3837 abort_validation (NULL, NULL, va);
3840 neighbour->publicKey = va->publicKey;
3841 neighbour->public_key_valid = GNUNET_YES;
3842 peer_address = add_peer_address (neighbour,
3843 va->transport_name, NULL,
3844 (const void*) &va[1],
3846 if (peer_address == NULL)
3848 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3849 "Failed to add peer `%4s' for plugin `%s'\n",
3850 GNUNET_i2s (&neighbour->id),
3851 va->transport_name);
3852 GNUNET_break (GNUNET_OK ==
3853 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3856 abort_validation (NULL, NULL, va);
3859 hello_size = GNUNET_HELLO_size(our_hello);
3860 slen = strlen(va->transport_name) + 1;
3861 tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
3862 message_buf = GNUNET_malloc(tsize);
3863 ping.challenge = htonl(va->challenge);
3864 ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
3865 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3866 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3867 memcpy(message_buf, our_hello, hello_size);
3868 memcpy(&message_buf[hello_size],
3870 sizeof(struct TransportPingMessage));
3871 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3874 memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3879 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3882 : a2s (va->transport_name,
3883 (const void*) &va[1], va->addrlen),
3885 GNUNET_i2s (&neighbour->id),
3886 "HELLO", hello_size,
3887 "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
3890 GNUNET_STATISTICS_update (stats,
3891 gettext_noop ("# PING messages sent for initial validation"),
3894 transmit_to_peer (NULL, peer_address,
3895 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3896 HELLO_VERIFICATION_TIMEOUT,
3898 GNUNET_YES, neighbour);
3899 GNUNET_free(message_buf);
3904 * Check if the given address is already being validated; if not,
3905 * append the given address to the list of entries that are being be
3906 * validated and initiate validation.
3908 * @param cls closure ('struct CheckHelloValidatedContext *')
3909 * @param tname name of the transport
3910 * @param expiration expiration time
3911 * @param addr the address
3912 * @param addrlen length of the address
3913 * @return GNUNET_OK (always)
3916 run_validation (void *cls,
3918 struct GNUNET_TIME_Absolute expiration,
3922 struct CheckHelloValidatedContext *chvc = cls;
3923 struct GNUNET_PeerIdentity id;
3924 struct TransportPlugin *tp;
3925 struct ValidationEntry *va;
3926 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3927 struct CheckAddressExistsClosure caec;
3928 struct OwnAddressList *oal;
3930 GNUNET_assert (addr != NULL);
3932 GNUNET_STATISTICS_update (stats,
3933 gettext_noop ("# peer addresses scheduled for validation"),
3936 tp = find_transport (tname);
3939 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3940 GNUNET_ERROR_TYPE_BULK,
3942 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3944 GNUNET_STATISTICS_update (stats,
3945 gettext_noop ("# peer addresses not validated (plugin not available)"),
3950 /* check if this is one of our own addresses */
3951 oal = tp->addresses;
3954 if ( (oal->addrlen == addrlen) &&
3955 (0 == memcmp (&oal[1],
3959 /* not plausible, this address is equivalent to our own address! */
3960 GNUNET_STATISTICS_update (stats,
3961 gettext_noop ("# peer addresses not validated (loopback)"),
3968 GNUNET_HELLO_get_key (chvc->hello, &pk);
3969 GNUNET_CRYPTO_hash (&pk,
3971 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3974 if (is_blacklisted(&id, tp))
3977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
3986 caec.addrlen = addrlen;
3987 caec.session = NULL;
3989 caec.exists = GNUNET_NO;
3990 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3991 &check_address_exists,
3993 if (caec.exists == GNUNET_YES)
3995 /* During validation attempts we will likely trigger the other
3996 peer trying to validate our address which in turn will cause
3997 it to send us its HELLO, so we expect to hit this case rather
3998 frequently. Only print something if we are very verbose. */
3999 #if DEBUG_TRANSPORT > 1
4000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4001 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
4002 a2s (tname, addr, addrlen),
4006 GNUNET_STATISTICS_update (stats,
4007 gettext_noop ("# peer addresses not validated (in progress)"),
4012 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
4015 va->transport_name = GNUNET_strdup (tname);
4016 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
4018 va->send_time = GNUNET_TIME_absolute_get();
4019 va->addr = (const void*) &va[1];
4020 memcpy (&va[1], addr, addrlen);
4021 va->addrlen = addrlen;
4022 GNUNET_HELLO_get_key (chvc->hello,
4024 va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
4025 &timeout_hello_validation,
4027 GNUNET_CONTAINER_multihashmap_put (validation_map,
4030 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4031 setup_peer_check_blacklist (&id, GNUNET_NO,
4032 &transmit_hello_and_ping,
4039 * Check if addresses in validated hello "h" overlap with
4040 * those in "chvc->hello" and validate the rest.
4042 * @param cls closure
4043 * @param peer id of the peer, NULL for last call
4044 * @param h hello message for the peer (can be NULL)
4045 * @param err_msg NULL if successful, otherwise contains error message
4048 check_hello_validated (void *cls,
4049 const struct GNUNET_PeerIdentity *peer,
4050 const struct GNUNET_HELLO_Message *h,
4051 const char *err_msg)
4053 struct CheckHelloValidatedContext *chvc = cls;
4054 struct GNUNET_HELLO_Message *plain_hello;
4055 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4056 struct GNUNET_PeerIdentity target;
4057 struct NeighbourList *n;
4059 if (err_msg != NULL)
4061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4062 _("Error in communication with PEERINFO service\n"));
4068 GNUNET_STATISTICS_update (stats,
4069 gettext_noop ("# outstanding peerinfo iterate requests"),
4073 if (GNUNET_NO == chvc->hello_known)
4075 /* notify PEERINFO about the peer now, so that we at least
4076 have the public key if some other component needs it */
4077 GNUNET_HELLO_get_key (chvc->hello, &pk);
4078 GNUNET_CRYPTO_hash (&pk,
4079 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4080 &target.hashPubKey);
4081 plain_hello = GNUNET_HELLO_create (&pk,
4084 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4085 GNUNET_free (plain_hello);
4086 #if DEBUG_TRANSPORT_HELLO
4087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4088 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4090 GNUNET_i2s (&target));
4092 GNUNET_STATISTICS_update (stats,
4093 gettext_noop ("# new HELLOs requiring full validation"),
4096 GNUNET_HELLO_iterate_addresses (chvc->hello,
4103 GNUNET_STATISTICS_update (stats,
4104 gettext_noop ("# duplicate HELLO (peer known)"),
4109 if (chvc->ve_count == 0)
4111 GNUNET_CONTAINER_DLL_remove (chvc_head,
4120 #if DEBUG_TRANSPORT_HELLO
4121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4122 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4126 chvc->hello_known = GNUNET_YES;
4127 n = find_neighbour (peer);
4130 #if DEBUG_TRANSPORT_HELLO
4131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132 "Calling hello_iterate_addresses for %s!\n",
4135 GNUNET_HELLO_iterate_addresses (h,
4137 &add_to_foreign_address_list,
4139 try_transmission_to_peer (n);
4143 #if DEBUG_TRANSPORT_HELLO
4144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4145 "No existing neighbor record for %s!\n",
4148 GNUNET_STATISTICS_update (stats,
4149 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4153 GNUNET_STATISTICS_update (stats,
4154 gettext_noop ("# HELLO validations (update case)"),
4157 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4159 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4166 * Process HELLO-message.
4168 * @param plugin transport involved, may be NULL
4169 * @param message the actual message
4170 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4173 process_hello (struct TransportPlugin *plugin,
4174 const struct GNUNET_MessageHeader *message)
4177 struct GNUNET_PeerIdentity target;
4178 const struct GNUNET_HELLO_Message *hello;
4179 struct CheckHelloValidatedContext *chvc;
4180 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4181 #if DEBUG_TRANSPORT_HELLO > 2
4184 hsize = ntohs (message->size);
4185 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4186 (hsize < sizeof (struct GNUNET_MessageHeader)))
4189 return GNUNET_SYSERR;
4191 GNUNET_STATISTICS_update (stats,
4192 gettext_noop ("# HELLOs received for validation"),
4196 /* first, check if load is too high */
4197 if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4199 GNUNET_STATISTICS_update (stats,
4200 gettext_noop ("# HELLOs ignored due to high load"),
4203 #if DEBUG_TRANSPORT_HELLO
4204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4205 "Ignoring `%s' for `%4s', load too high.\n",
4207 GNUNET_i2s (&target));
4211 hello = (const struct GNUNET_HELLO_Message *) message;
4212 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4214 #if DEBUG_TRANSPORT_HELLO
4215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4216 "Unable to get public key from `%s' for `%4s'!\n",
4218 GNUNET_i2s (&target));
4220 GNUNET_break_op (0);
4221 return GNUNET_SYSERR;
4224 GNUNET_CRYPTO_hash (&publicKey,
4225 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4226 &target.hashPubKey);
4228 #if DEBUG_TRANSPORT_HELLO
4229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4230 "Received `%s' message for `%4s'\n",
4232 GNUNET_i2s (&target));
4235 if (0 == memcmp (&my_identity,
4237 sizeof (struct GNUNET_PeerIdentity)))
4239 GNUNET_STATISTICS_update (stats,
4240 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4246 while (NULL != chvc)
4248 if (GNUNET_HELLO_equals (hello,
4250 GNUNET_TIME_absolute_get ()).abs_value > 0)
4252 #if DEBUG_TRANSPORT_HELLO > 2
4253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4254 "Received duplicate `%s' message for `%4s'; ignored\n",
4256 GNUNET_i2s (&target));
4258 return GNUNET_OK; /* validation already pending */
4260 if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
4261 GNUNET_break (0 != memcmp (hello, chvc->hello,
4262 GNUNET_HELLO_size(hello)));
4267 struct NeighbourList *temp_neighbor = find_neighbour(&target);
4268 if ((NULL != temp_neighbor))
4270 fprintf(stderr, "Already know peer, ignoring hello\n");
4275 #if DEBUG_TRANSPORT_HELLO > 2
4278 my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4280 "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4283 GNUNET_i2s (&target),
4285 GNUNET_HELLO_size(hello));
4289 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4291 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4292 memcpy (&chvc[1], hello, hsize);
4293 GNUNET_CONTAINER_DLL_insert (chvc_head,
4296 /* finally, check if HELLO was previously validated
4297 (continuation will then schedule actual validation) */
4298 GNUNET_STATISTICS_update (stats,
4299 gettext_noop ("# peerinfo process hello iterate requests"),
4302 GNUNET_STATISTICS_update (stats,
4303 gettext_noop ("# outstanding peerinfo iterate requests"),
4306 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4308 HELLO_VERIFICATION_TIMEOUT,
4309 &check_hello_validated, chvc);
4315 * The peer specified by the given neighbour has timed-out or a plugin
4316 * has disconnected. We may either need to do nothing (other plugins
4317 * still up), or trigger a full disconnect and clean up. This
4318 * function updates our state and does the necessary notifications.
4319 * Also notifies our clients that the neighbour is now officially
4322 * @param n the neighbour list entry for the peer
4323 * @param check GNUNET_YES to check if ALL addresses for this peer
4324 * are gone, GNUNET_NO to force a disconnect of the peer
4325 * regardless of whether other addresses exist.
4328 disconnect_neighbour (struct NeighbourList *n, int check)
4330 struct ReadyList *rpos;
4331 struct NeighbourList *npos;
4332 struct NeighbourList *nprev;
4333 struct MessageQueue *mq;
4334 struct ForeignAddressList *peer_addresses;
4335 struct ForeignAddressList *peer_pos;
4337 if (GNUNET_YES == check)
4340 while (NULL != rpos)
4342 peer_addresses = rpos->addresses;
4343 while (peer_addresses != NULL)
4345 if (GNUNET_YES == peer_addresses->connected)
4347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4348 "NOT Disconnecting from `%4s', still have live addresses!\n",
4349 GNUNET_i2s (&n->id));
4350 return; /* still connected */
4352 peer_addresses = peer_addresses->next;
4358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4359 "Disconnecting from `%4s'\n",
4360 GNUNET_i2s (&n->id));
4362 /* remove n from neighbours list */
4365 while ((npos != NULL) && (npos != n))
4370 GNUNET_assert (npos != NULL);
4372 neighbours = n->next;
4374 nprev->next = n->next;
4376 /* notify all clients about disconnect */
4377 if (GNUNET_YES == n->received_pong)
4378 notify_clients_disconnect (&n->id);
4380 /* clean up all plugins, cancel connections and pending transmissions */
4381 while (NULL != (rpos = n->plugins))
4383 n->plugins = rpos->next;
4384 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4385 while (rpos->addresses != NULL)
4387 peer_pos = rpos->addresses;
4388 rpos->addresses = peer_pos->next;
4389 if (peer_pos->connected == GNUNET_YES)
4390 GNUNET_STATISTICS_update (stats,
4391 gettext_noop ("# connected addresses"),
4394 if (GNUNET_YES == peer_pos->validated)
4395 GNUNET_STATISTICS_update (stats,
4396 gettext_noop ("# peer addresses considered valid"),
4399 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4401 GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4402 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4404 GNUNET_free(peer_pos);
4409 /* free all messages on the queue */
4410 while (NULL != (mq = n->messages_head))
4412 GNUNET_STATISTICS_update (stats,
4413 gettext_noop ("# bytes in message queue for other peers"),
4414 - (int64_t) mq->message_buf_size,
4416 GNUNET_STATISTICS_update (stats,
4417 gettext_noop ("# bytes discarded due to disconnect"),
4418 mq->message_buf_size,
4420 GNUNET_CONTAINER_DLL_remove (n->messages_head,
4423 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4425 sizeof(struct GNUNET_PeerIdentity)));
4428 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4430 GNUNET_SCHEDULER_cancel (n->timeout_task);
4431 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4433 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4435 GNUNET_SCHEDULER_cancel (n->retry_task);
4436 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4438 if (n->piter != NULL)
4440 GNUNET_PEERINFO_iterate_cancel (n->piter);
4441 GNUNET_STATISTICS_update (stats,
4442 gettext_noop ("# outstanding peerinfo iterate requests"),
4447 /* finally, free n itself */
4448 GNUNET_STATISTICS_update (stats,
4449 gettext_noop ("# active neighbours"),
4452 GNUNET_free_non_null (n->pre_connect_message_buffer);
4458 * We have received a PING message from someone. Need to send a PONG message
4459 * in response to the peer by any means necessary.
4462 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4463 const struct GNUNET_PeerIdentity *peer,
4464 struct Session *session,
4465 const char *sender_address,
4466 uint16_t sender_address_len)
4468 struct TransportPlugin *plugin = cls;
4469 struct SessionHeader *session_header = (struct SessionHeader*) session;
4470 struct TransportPingMessage *ping;
4471 struct TransportPongMessage *pong;
4472 struct NeighbourList *n;
4473 struct ReadyList *rl;
4474 struct ForeignAddressList *fal;
4475 struct OwnAddressList *oal;
4480 if (ntohs (message->size) < sizeof (struct TransportPingMessage))
4482 GNUNET_break_op (0);
4483 return GNUNET_SYSERR;
4486 ping = (struct TransportPingMessage *) message;
4487 if (0 != memcmp (&ping->target,
4488 plugin->env.my_identity,
4489 sizeof (struct GNUNET_PeerIdentity)))
4491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4492 _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
4494 (sender_address != NULL)
4495 ? a2s (plugin->short_name,
4496 (const struct sockaddr *)sender_address,
4499 GNUNET_i2s (&ping->target));
4500 return GNUNET_SYSERR;
4503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4504 "Processing `%s' from `%s'\n",
4506 (sender_address != NULL)
4507 ? a2s (plugin->short_name,
4508 (const struct sockaddr *)sender_address,
4512 GNUNET_STATISTICS_update (stats,
4513 gettext_noop ("# PING messages received"),
4516 addr = (const char*) &ping[1];
4517 alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
4518 slen = strlen (plugin->short_name) + 1;
4521 /* peer wants to confirm that we have an outbound connection to him */
4522 if (session == NULL)
4524 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4525 _("Refusing to create PONG since I do not have a session with `%s'.\n"),
4527 return GNUNET_SYSERR;
4529 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4530 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4531 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4532 pong->purpose.size =
4533 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4535 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4536 sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
4537 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
4538 pong->challenge = ping->challenge;
4539 pong->addrlen = htonl(sender_address_len + slen);
4542 sizeof(struct GNUNET_PeerIdentity));
4546 if ((sender_address!=NULL) && (sender_address_len > 0))
4547 memcpy (&((char*)&pong[1])[slen],
4549 sender_address_len);
4550 if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
4552 /* create / update cached sig */
4554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4555 "Creating PONG signature to indicate active connection.\n");
4557 session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
4558 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4559 GNUNET_assert (GNUNET_OK ==
4560 GNUNET_CRYPTO_rsa_sign (my_private_key,
4562 &session_header->pong_signature));
4566 pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4568 memcpy (&pong->signature,
4569 &session_header->pong_signature,
4570 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4576 /* peer wants to confirm that this is one of our addresses */
4580 plugin->api->check_address (plugin->api->cls,
4584 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4585 _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
4586 a2s (plugin->short_name,
4591 oal = plugin->addresses;
4594 if ( (oal->addrlen == alen) &&
4601 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
4602 pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
4603 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4604 pong->purpose.size =
4605 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4607 sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4608 sizeof (struct GNUNET_PeerIdentity) + alen + slen);
4609 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
4610 pong->challenge = ping->challenge;
4611 pong->addrlen = htonl(alen + slen);
4614 sizeof(struct GNUNET_PeerIdentity));
4615 memcpy (&pong[1], plugin->short_name, slen);
4616 memcpy (&((char*)&pong[1])[slen], addr, alen);
4617 if ( (oal != NULL) &&
4618 (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
4620 /* create / update cached sig */
4622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4623 "Creating PONG signature to indicate ownership.\n");
4625 oal->pong_sig_expires = GNUNET_TIME_absolute_min (oal->expires,
4626 GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4627 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4628 GNUNET_assert (GNUNET_OK ==
4629 GNUNET_CRYPTO_rsa_sign (my_private_key,
4631 &oal->pong_signature));
4632 memcpy (&pong->signature,
4633 &oal->pong_signature,
4634 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4636 else if (oal == NULL)
4638 /* not using cache (typically DV-only) */
4639 pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4640 GNUNET_assert (GNUNET_OK ==
4641 GNUNET_CRYPTO_rsa_sign (my_private_key,
4647 /* can used cached version */
4648 pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4649 memcpy (&pong->signature,
4650 &oal->pong_signature,
4651 sizeof (struct GNUNET_CRYPTO_RsaSignature));
4654 n = find_neighbour(peer);
4655 GNUNET_assert (n != NULL);
4656 /* first try reliable response transmission */
4660 fal = rl->addresses;
4663 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4666 ntohs (pong->header.size),
4667 TRANSPORT_PONG_PRIORITY,
4668 HELLO_VERIFICATION_TIMEOUT,
4676 GNUNET_STATISTICS_update (stats,
4677 gettext_noop ("# PONGs unicast via reliable transport"),
4687 /* no reliable method found, do multicast */
4688 GNUNET_STATISTICS_update (stats,
4689 gettext_noop ("# PONGs multicast to all available addresses"),
4695 fal = rl->addresses;
4698 transmit_to_peer(NULL, fal,
4699 TRANSPORT_PONG_PRIORITY,
4700 HELLO_VERIFICATION_TIMEOUT,
4702 ntohs(pong->header.size),
4715 * Function called by the plugin for each received message.
4716 * Update data volumes, possibly notify plugins about
4717 * reducing the rate at which they read from the socket
4718 * and generally forward to our receive callback.
4720 * @param cls the "struct TransportPlugin *" we gave to the plugin
4721 * @param peer (claimed) identity of the other peer
4722 * @param message the message, NULL if we only care about
4723 * learning about the delay until we should receive again
4724 * @param ats information for automatic transport selection
4725 * @param ats_count number of elements in ats not including 0-terminator
4726 * @param session identifier used for this session (can be NULL)
4727 * @param sender_address binary address of the sender (if observed)
4728 * @param sender_address_len number of bytes in sender_address
4729 * @return how long in ms the plugin should wait until receiving more data
4730 * (plugins that do not support this, can ignore the return value)
4732 static struct GNUNET_TIME_Relative
4733 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4734 const struct GNUNET_MessageHeader *message,
4735 const struct GNUNET_TRANSPORT_ATS_Information *ats,
4737 struct Session *session,
4738 const char *sender_address,
4739 uint16_t sender_address_len)
4741 struct TransportPlugin *plugin = cls;
4742 struct ReadyList *service_context;
4743 struct ForeignAddressList *peer_address;
4745 struct NeighbourList *n;
4746 struct GNUNET_TIME_Relative ret;
4747 if (is_blacklisted (peer, plugin))
4748 return GNUNET_TIME_UNIT_FOREVER_REL;
4752 n = find_neighbour (peer);
4754 n = setup_new_neighbour (peer, GNUNET_YES);
4755 service_context = n->plugins;
4756 while ((service_context != NULL) && (plugin != service_context->plugin))
4757 service_context = service_context->next;
4758 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4759 peer_address = NULL;
4761 for (c=0; c<ats_count; c++)
4763 if (ntohl(ats[c].type) == GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE)
4765 distance = ntohl(ats[c].value);
4769 if (message != NULL)
4771 if ( (session != NULL) ||
4772 (sender_address != NULL) )
4773 peer_address = add_peer_address (n,
4777 sender_address_len);
4778 if (peer_address != NULL)
4780 peer_address->distance = distance;
4781 if (GNUNET_YES == peer_address->validated)
4782 mark_address_connected (peer_address);
4783 peer_address->timeout
4785 GNUNET_TIME_relative_to_absolute
4786 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4787 schedule_next_ping (peer_address);
4789 /* update traffic received amount ... */
4790 msize = ntohs (message->size);
4791 GNUNET_STATISTICS_update (stats,
4792 gettext_noop ("# bytes received from other peers"),
4795 n->distance = distance;
4797 GNUNET_TIME_relative_to_absolute
4798 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4799 GNUNET_SCHEDULER_cancel (n->timeout_task);
4801 GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4802 &neighbour_timeout_task, n);
4803 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4805 /* dropping message due to frequent inbound volume violations! */
4806 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4807 GNUNET_ERROR_TYPE_BULK,
4809 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4810 n->in_tracker.available_bytes_per_s__,
4811 n->quota_violation_count);
4812 GNUNET_STATISTICS_update (stats,
4813 gettext_noop ("# bandwidth quota violations by other peers"),
4816 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4821 "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4822 ntohs (message->type),
4823 ntohs (message->size),
4826 switch (ntohs (message->type))
4828 case GNUNET_MESSAGE_TYPE_HELLO:
4829 GNUNET_STATISTICS_update (stats,
4830 gettext_noop ("# HELLO messages received from other peers"),
4833 process_hello (plugin, message);
4835 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4836 handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
4838 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4839 handle_pong (plugin, message, peer, sender_address, sender_address_len);
4842 handle_payload_message (message, n);
4846 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4847 if (ret.rel_value > 0)
4849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4850 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4851 (unsigned long long) n->in_tracker.consumption_since_last_update__,
4852 (unsigned int) n->in_tracker.available_bytes_per_s__,
4853 (unsigned long long) ret.rel_value);
4854 GNUNET_STATISTICS_update (stats,
4855 gettext_noop ("# ms throttling suggested"),
4856 (int64_t) ret.rel_value,
4863 * Handle START-message. This is the first message sent to us
4864 * by any client which causes us to add it to our list.
4866 * @param cls closure (always NULL)
4867 * @param client identification of the client
4868 * @param message the actual message
4871 handle_start (void *cls,
4872 struct GNUNET_SERVER_Client *client,
4873 const struct GNUNET_MessageHeader *message)
4875 const struct StartMessage *start;
4876 struct TransportClient *c;
4877 struct ConnectInfoMessage * cim;
4878 struct NeighbourList *n;
4882 start = (const struct StartMessage*) message;
4884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4885 "Received `%s' request from client\n", "START");
4890 if (c->client == client)
4892 /* client already on our list! */
4894 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4899 if ( (GNUNET_NO != ntohl (start->do_check)) &&
4900 (0 != memcmp (&start->self,
4902 sizeof (struct GNUNET_PeerIdentity))) )
4904 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4905 _("Rejecting control connection from peer `%s', which is not me!\n"),
4906 GNUNET_i2s (&start->self));
4907 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4910 c = GNUNET_malloc (sizeof (struct TransportClient));
4914 if (our_hello != NULL)
4917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4918 "Sending our own `%s' to new client\n", "HELLO");
4920 transmit_to_client (c,
4921 (const struct GNUNET_MessageHeader *) our_hello,
4923 /* tell new client about all existing connections */
4925 size = sizeof (struct ConnectInfoMessage) + ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information);
4926 if (size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
4930 cim = GNUNET_malloc (size);
4931 cim->header.size = htons (size);
4932 cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4933 cim->ats_count = htonl(ats_count);
4934 (&(cim->ats))[2].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
4935 (&(cim->ats))[2].value = htonl (0);
4939 if (GNUNET_YES == n->received_pong)
4941 (&(cim->ats))[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4942 (&(cim->ats))[0].value = htonl (n->distance);
4943 (&(cim->ats))[1].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4944 (&(cim->ats))[1].value = htonl ((uint32_t) n->latency.rel_value);
4946 transmit_to_client (c, &cim->header, GNUNET_NO);
4952 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4957 * Handle HELLO-message.
4959 * @param cls closure (always NULL)
4960 * @param client identification of the client
4961 * @param message the actual message
4964 handle_hello (void *cls,
4965 struct GNUNET_SERVER_Client *client,
4966 const struct GNUNET_MessageHeader *message)
4970 GNUNET_STATISTICS_update (stats,
4971 gettext_noop ("# HELLOs received from clients"),
4974 ret = process_hello (NULL, message);
4975 GNUNET_SERVER_receive_done (client, ret);
4980 * Closure for 'transmit_client_message'; followed by
4981 * 'msize' bytes of the actual message.
4983 struct TransmitClientMessageContext
4986 * Client on whom's behalf we are sending.
4988 struct GNUNET_SERVER_Client *client;
4991 * Timeout for the transmission.
4993 struct GNUNET_TIME_Absolute timeout;
5001 * Size of the message in bytes.
5008 * Schedule transmission of a message we got from a client to a peer.
5010 * @param cls the 'struct TransmitClientMessageContext*'
5011 * @param n destination, or NULL on error (in that case, drop the message)
5014 transmit_client_message (void *cls,
5015 struct NeighbourList *n)
5017 struct TransmitClientMessageContext *tcmc = cls;
5018 struct TransportClient *tc;
5021 while ((tc != NULL) && (tc->client != tcmc->client))
5026 transmit_to_peer (tc, NULL, tcmc->priority,
5027 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
5029 tcmc->msize, GNUNET_NO, n);
5031 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
5032 GNUNET_SERVER_client_drop (tcmc->client);
5038 * Handle SEND-message.
5040 * @param cls closure (always NULL)
5041 * @param client identification of the client
5042 * @param message the actual message
5045 handle_send (void *cls,
5046 struct GNUNET_SERVER_Client *client,
5047 const struct GNUNET_MessageHeader *message)
5049 const struct OutboundMessage *obm;
5050 const struct GNUNET_MessageHeader *obmm;
5051 struct TransmitClientMessageContext *tcmc;
5055 size = ntohs (message->size);
5057 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5060 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5063 GNUNET_STATISTICS_update (stats,
5064 gettext_noop ("# payload received for other peers"),
5067 obm = (const struct OutboundMessage *) message;
5068 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5069 msize = size - sizeof (struct OutboundMessage);
5071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5072 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5073 "SEND", GNUNET_i2s (&obm->peer),
5077 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5078 tcmc->client = client;
5079 tcmc->priority = ntohl (obm->priority);
5080 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5081 tcmc->msize = msize;
5082 /* FIXME: this memcpy can be up to 7% of our total runtime */
5083 memcpy (&tcmc[1], obmm, msize);
5084 GNUNET_SERVER_client_keep (client);
5085 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5086 &transmit_client_message,
5092 * Handle request connect message
5094 * @param cls closure (always NULL)
5095 * @param client identification of the client
5096 * @param message the actual message
5099 handle_request_connect (void *cls,
5100 struct GNUNET_SERVER_Client *client,
5101 const struct GNUNET_MessageHeader *message)
5103 const struct TransportRequestConnectMessage *trcm =
5104 (const struct TransportRequestConnectMessage *) message;
5106 GNUNET_STATISTICS_update (stats,
5107 gettext_noop ("# REQUEST CONNECT messages received"),
5110 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a request connect message for peer %s\n", GNUNET_i2s(&trcm->peer));
5111 setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5113 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5117 * Handle SET_QUOTA-message.
5119 * @param cls closure (always NULL)
5120 * @param client identification of the client
5121 * @param message the actual message
5124 handle_set_quota (void *cls,
5125 struct GNUNET_SERVER_Client *client,
5126 const struct GNUNET_MessageHeader *message)
5128 const struct QuotaSetMessage *qsm =
5129 (const struct QuotaSetMessage *) message;
5130 struct NeighbourList *n;
5132 GNUNET_STATISTICS_update (stats,
5133 gettext_noop ("# SET QUOTA messages received"),
5136 n = find_neighbour (&qsm->peer);
5139 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5140 GNUNET_STATISTICS_update (stats,
5141 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5148 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5150 (unsigned int) ntohl (qsm->quota.value__),
5151 (unsigned int) n->in_tracker.available_bytes_per_s__,
5152 GNUNET_i2s (&qsm->peer));
5154 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5156 if (0 == ntohl (qsm->quota.value__))
5158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5159 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5161 disconnect_neighbour (n, GNUNET_NO);
5163 GNUNET_SERVER_receive_done (client, GNUNET_OK);
5168 * Take the given address and append it to the set of results sent back to
5171 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5172 * @param address the resolved name, NULL to indicate the last response
5175 transmit_address_to_client (void *cls, const char *address)
5177 struct GNUNET_SERVER_TransmitContext *tc = cls;
5180 if (NULL == address)
5183 slen = strlen (address) + 1;
5185 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5186 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5187 if (NULL == address)
5188 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5193 * Handle AddressLookup-message.
5195 * @param cls closure (always NULL)
5196 * @param client identification of the client
5197 * @param message the actual message
5200 handle_address_lookup (void *cls,
5201 struct GNUNET_SERVER_Client *client,
5202 const struct GNUNET_MessageHeader *message)
5204 const struct AddressLookupMessage *alum;
5205 struct TransportPlugin *lsPlugin;
5206 const char *nameTransport;
5207 const char *address;
5209 struct GNUNET_SERVER_TransmitContext *tc;
5210 struct GNUNET_TIME_Absolute timeout;
5211 struct GNUNET_TIME_Relative rtimeout;
5214 size = ntohs (message->size);
5215 if (size < sizeof (struct AddressLookupMessage))
5217 GNUNET_break_op (0);
5218 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5221 alum = (const struct AddressLookupMessage *) message;
5222 uint32_t addressLen = ntohl (alum->addrlen);
5223 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5225 GNUNET_break_op (0);
5226 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5229 address = (const char *) &alum[1];
5230 nameTransport = (const char *) &address[addressLen];
5232 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5234 GNUNET_break_op (0);
5235 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5238 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5239 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5240 numeric = ntohl (alum->numeric_only);
5241 lsPlugin = find_transport (nameTransport);
5242 if (NULL == lsPlugin)
5244 tc = GNUNET_SERVER_transmit_context_create (client);
5245 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5246 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5247 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5250 tc = GNUNET_SERVER_transmit_context_create (client);
5251 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5253 address, addressLen,
5256 &transmit_address_to_client, tc);
5261 * Setup the environment for this plugin.
5264 create_environment (struct TransportPlugin *plug)
5266 plug->env.cfg = cfg;
5267 plug->env.my_identity = &my_identity;
5268 plug->env.our_hello = &our_hello;
5269 plug->env.cls = plug;
5270 plug->env.receive = &plugin_env_receive;
5271 plug->env.notify_address = &plugin_env_notify_address;
5272 plug->env.session_end = &plugin_env_session_end;
5273 plug->env.max_connections = max_connect_per_transport;
5274 plug->env.stats = stats;
5279 * Start the specified transport (load the plugin).
5282 start_transport (struct GNUNET_SERVER_Handle *server,
5285 struct TransportPlugin *plug;
5288 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5289 _("Loading `%s' transport plugin\n"), name);
5290 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
5291 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
5292 create_environment (plug);
5293 plug->short_name = GNUNET_strdup (name);
5294 plug->lib_name = libname;
5295 plug->next = plugins;
5297 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
5298 if (plug->api == NULL)
5300 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5301 _("Failed to load transport plugin for `%s'\n"), name);
5302 GNUNET_free (plug->short_name);
5303 plugins = plug->next;
5304 GNUNET_free (libname);
5311 * Called whenever a client is disconnected. Frees our
5312 * resources associated with that client.
5314 * @param cls closure
5315 * @param client identification of the client
5318 client_disconnect_notification (void *cls,
5319 struct GNUNET_SERVER_Client *client)
5321 struct TransportClient *pos;
5322 struct TransportClient *prev;
5323 struct ClientMessageQueueEntry *mqe;
5324 struct Blacklisters *bl;
5325 struct BlacklistCheck *bc;
5330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5331 "Client disconnected, cleaning up.\n");
5333 /* clean up blacklister */
5337 if (bl->client == client)
5342 if (bc->bl_pos == bl)
5344 bc->bl_pos = bl->next;
5347 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
5350 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
5351 bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
5357 GNUNET_CONTAINER_DLL_remove (bl_head,
5360 GNUNET_SERVER_client_drop (bl->client);
5366 /* clean up 'normal' clients */
5369 while ((pos != NULL) && (pos->client != client))
5376 while (NULL != (mqe = pos->message_queue_head))
5378 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
5379 pos->message_queue_tail,
5381 pos->message_count--;
5385 clients = pos->next;
5387 prev->next = pos->next;
5388 if (GNUNET_YES == pos->tcs_pending)
5393 if (pos->th != NULL)
5395 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
5398 GNUNET_break (0 == pos->message_count);
5404 * Function called when the service shuts down. Unloads our plugins
5405 * and cancels pending validations.
5407 * @param cls closure, unused
5408 * @param tc task context (unused)
5411 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5413 struct TransportPlugin *plug;
5414 struct OwnAddressList *al;
5415 struct CheckHelloValidatedContext *chvc;
5417 while (neighbours != NULL)
5419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5420 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
5422 disconnect_neighbour (neighbours, GNUNET_NO);
5425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5426 "Transport service is unloading plugins...\n");
5428 while (NULL != (plug = plugins))
5430 plugins = plug->next;
5431 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
5433 GNUNET_SCHEDULER_cancel (plug->address_update_task);
5434 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
5436 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
5437 GNUNET_free (plug->lib_name);
5438 GNUNET_free (plug->short_name);
5439 while (NULL != (al = plug->addresses))
5441 plug->addresses = al->next;
5446 if (my_private_key != NULL)
5447 GNUNET_CRYPTO_rsa_key_free (my_private_key);
5448 GNUNET_free_non_null (our_hello);
5450 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
5453 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5454 validation_map = NULL;
5456 /* free 'chvc' data structure */
5457 while (NULL != (chvc = chvc_head))
5459 chvc_head = chvc->next;
5460 if (chvc->piter != NULL)
5462 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
5463 GNUNET_STATISTICS_update (stats,
5464 gettext_noop ("# outstanding peerinfo iterate requests"),
5470 GNUNET_assert (chvc->ve_count == 0);
5477 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5480 if (peerinfo != NULL)
5482 GNUNET_PEERINFO_disconnect (peerinfo);
5485 /* Can we assume those are gone by now, or do we need to clean up
5487 GNUNET_break (bl_head == NULL);
5488 GNUNET_break (bc_head == NULL);
5493 * Initiate transport service.
5495 * @param cls closure
5496 * @param server the initialized server
5497 * @param c configuration to use
5501 struct GNUNET_SERVER_Handle *server,
5502 const struct GNUNET_CONFIGURATION_Handle *c)
5504 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
5505 {&handle_start, NULL,
5506 GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
5507 {&handle_hello, NULL,
5508 GNUNET_MESSAGE_TYPE_HELLO, 0},
5509 {&handle_send, NULL,
5510 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
5511 {&handle_request_connect, NULL,
5512 GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
5513 {&handle_set_quota, NULL,
5514 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
5515 {&handle_address_lookup, NULL,
5516 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
5518 {&handle_blacklist_init, NULL,
5519 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
5520 {&handle_blacklist_reply, NULL,
5521 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
5527 unsigned long long tneigh;
5531 stats = GNUNET_STATISTICS_create ("transport", cfg);
5532 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
5533 /* parse configuration */
5535 GNUNET_CONFIGURATION_get_value_number (c,
5540 GNUNET_CONFIGURATION_get_value_filename (c,
5542 "HOSTKEY", &keyfile)))
5544 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5546 ("Transport service is lacking key configuration settings. Exiting.\n"));
5547 GNUNET_SCHEDULER_shutdown ();
5550 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5553 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5554 validation_map = NULL;
5557 max_connect_per_transport = (uint32_t) tneigh;
5558 peerinfo = GNUNET_PEERINFO_connect (cfg);
5559 if (peerinfo == NULL)
5561 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5562 _("Could not access PEERINFO service. Exiting.\n"));
5563 GNUNET_SCHEDULER_shutdown ();
5566 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5569 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5570 validation_map = NULL;
5571 GNUNET_free (keyfile);
5574 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
5575 GNUNET_free (keyfile);
5576 if (my_private_key == NULL)
5578 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5580 ("Transport service could not access hostkey. Exiting.\n"));
5581 GNUNET_SCHEDULER_shutdown ();
5584 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5587 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5588 validation_map = NULL;
5591 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
5592 GNUNET_CRYPTO_hash (&my_public_key,
5593 sizeof (my_public_key), &my_identity.hashPubKey);
5594 /* setup notification */
5595 GNUNET_SERVER_disconnect_notify (server,
5596 &client_disconnect_notification, NULL);
5597 /* load plugins... */
5600 GNUNET_CONFIGURATION_get_value_string (c,
5601 "TRANSPORT", "PLUGINS", &plugs))
5603 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5604 _("Starting transport plugins `%s'\n"), plugs);
5605 pos = strtok (plugs, " ");
5608 start_transport (server, pos);
5610 pos = strtok (NULL, " ");
5612 GNUNET_free (plugs);
5614 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5615 &shutdown_task, NULL);
5620 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
5622 /* If we have a blacklist file, read from it */
5623 read_blacklist_file(cfg);
5624 /* process client requests */
5625 GNUNET_SERVER_add_handlers (server, handlers);
5630 * The main function for the transport service.
5632 * @param argc number of arguments from the command line
5633 * @param argv command line arguments
5634 * @return 0 ok, 1 on error
5637 main (int argc, char *const *argv)
5639 a2s (NULL, NULL, 0); /* make compiler happy */
5640 return (GNUNET_OK ==
5641 GNUNET_SERVICE_run (argc,
5644 GNUNET_SERVICE_OPTION_NONE,
5645 &run, NULL)) ? 0 : 1;
5648 /* end of gnunet-service-transport.c */