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 2, 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 "plugin_transport.h"
40 #include "transport.h"
42 #define DEBUG_BLACKLIST GNUNET_NO
44 #define DEBUG_PING_PONG GNUNET_NO
46 #define SIGN_USELESS GNUNET_NO
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.
63 #define MAX_PENDING 128
66 * Size of the per-transport blacklist hash maps.
68 #define TRANSPORT_BLACKLIST_HT_SIZE 16
71 * How often should we try to reconnect to a peer using a particular
72 * transport plugin before giving up? Note that the plugin may be
73 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
75 #define MAX_CONNECT_RETRY 3
78 * Limit on the number of ready-to-run tasks when validating
79 * HELLOs. If more tasks are ready to run, we will drop
80 * HELLOs instead of validating them.
82 #define MAX_HELLO_LOAD 4
85 * How often must a peer violate bandwidth quotas before we start
86 * to simply drop its messages?
88 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
91 * How long until a HELLO verification attempt should time out?
92 * Must be rather small, otherwise a partially successful HELLO
93 * validation (some addresses working) might not be available
94 * before a client's request for a connection fails for good.
95 * Besides, if a single request to an address takes a long time,
96 * then the peer is unlikely worthwhile anyway.
98 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
101 * Priority to use for PONG messages.
103 #define TRANSPORT_PONG_PRIORITY 4
106 * How often do we re-add (cheaper) plugins to our list of plugins
107 * to try for a given connected peer?
109 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
112 * After how long do we expire an address in a HELLO that we just
113 * validated? This value is also used for our own addresses when we
116 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
120 * How long before an existing address expires should we again try to
121 * validate it? Must be (significantly) smaller than
122 * HELLO_ADDRESS_EXPIRATION.
124 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
127 * Maximum frequency for re-evaluating latencies for all transport addresses.
129 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
132 * Maximum frequency for re-evaluating latencies for connected addresses.
134 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
138 * List of addresses of other peers
140 struct ForeignAddressList
143 * This is a linked list.
145 struct ForeignAddressList *next;
148 * Which ready list does this entry belong to.
150 struct ReadyList *ready_list;
153 * How long until we auto-expire this address (unless it is
154 * re-confirmed by the transport)?
156 struct GNUNET_TIME_Absolute expires;
159 * Task used to re-validate addresses, updates latencies and
162 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
170 * Session (or NULL if no valid session currently exists or if the
171 * plugin does not use sessions).
173 struct Session *session;
176 * What was the last latency observed for this address, plugin and peer?
178 struct GNUNET_TIME_Relative latency;
181 * If we did not successfully transmit a message to the given peer
182 * via this connection during the specified time, we should consider
183 * the connection to be dead. This is used in the case that a TCP
184 * transport simply stalls writing to the stream but does not
185 * formerly get a signal that the other peer died.
187 struct GNUNET_TIME_Absolute timeout;
190 * How often have we tried to connect using this plugin? Used to
191 * discriminate against addresses that do not work well.
192 * FIXME: not yet used, but should be!
194 unsigned int connect_attempts;
197 * DV distance to this peer (1 if no DV is used).
198 * FIXME: need to set this from transport plugins!
208 * Have we ever estimated the latency of this address? Used to
209 * ensure that the first time we add an address, we immediately
215 * Are we currently connected via this address? The first time we
216 * successfully transmit or receive data to a peer via a particular
217 * address, we set this to GNUNET_YES. If we later get an error
218 * (disconnect notification, transmission failure, timeout), we set
219 * it back to GNUNET_NO.
224 * Is this plugin currently busy transmitting to the specific target?
225 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
226 * messages do not count as 'in transmit'.
231 * Has this address been validated yet?
239 * Entry in linked list of network addresses for ourselves.
241 struct OwnAddressList
244 * This is a linked list.
246 struct OwnAddressList *next;
249 * The address, actually a pointer to the end
250 * of this struct. Do not free!
255 * How long until we auto-expire this address (unless it is
256 * re-confirmed by the transport)?
258 struct GNUNET_TIME_Absolute expires;
269 * Entry in linked list of all of our plugins.
271 struct TransportPlugin
275 * This is a linked list.
277 struct TransportPlugin *next;
280 * API of the transport as returned by the plugin's
281 * initialization function.
283 struct GNUNET_TRANSPORT_PluginFunctions *api;
286 * Short name for the plugin (i.e. "tcp").
291 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
296 * List of our known addresses for this transport.
298 struct OwnAddressList *addresses;
301 * Environment this transport service is using
304 struct GNUNET_TRANSPORT_PluginEnvironment env;
307 * ID of task that is used to clean up expired addresses.
309 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
312 * Set to GNUNET_YES if we need to scrap the existing list of
313 * "addresses" and start fresh when we receive the next address
314 * update from a transport. Set to GNUNET_NO if we should just add
315 * the new address to the list and wait for the commit call.
320 * Hashmap of blacklisted peers for this particular transport.
322 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
325 struct NeighbourList;
328 * For each neighbour we keep a list of messages
329 * that we still want to transmit to the neighbour.
335 * This is a doubly linked list.
337 struct MessageQueue *next;
340 * This is a doubly linked list.
342 struct MessageQueue *prev;
345 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
346 * stuck together in memory. Allocated at the end of this struct.
348 const char *message_buf;
351 * Size of the message buf
353 size_t message_buf_size;
356 * Client responsible for queueing the message;
357 * used to check that a client has no two messages
358 * pending for the same target. Can be NULL.
360 struct TransportClient *client;
363 * Using which specific address should we send this message?
365 struct ForeignAddressList *specific_address;
368 * Peer ID of the Neighbour this entry belongs to.
370 struct GNUNET_PeerIdentity neighbour_id;
373 * Plugin that we used for the transmission.
374 * NULL until we scheduled a transmission.
376 struct TransportPlugin *plugin;
379 * At what time should we fail?
381 struct GNUNET_TIME_Absolute timeout;
384 * Internal message of the transport system that should not be
385 * included in the usual SEND-SEND_OK transmission confirmation
386 * traffic management scheme. Typically, "internal_msg" will
387 * be set whenever "client" is NULL (but it is not strictly
393 * How important is the message?
395 unsigned int priority;
401 * For a given Neighbour, which plugins are available
402 * to talk to this peer and what are their costs?
407 * This is a linked list.
409 struct ReadyList *next;
412 * Which of our transport plugins does this entry
415 struct TransportPlugin *plugin;
418 * Transport addresses, latency, and readiness for
419 * this particular plugin.
421 struct ForeignAddressList *addresses;
424 * To which neighbour does this ready list belong to?
426 struct NeighbourList *neighbour;
432 * Entry in linked list of all of our current neighbours.
438 * This is a linked list.
440 struct NeighbourList *next;
443 * Which of our transports is connected to this peer
444 * and what is their status?
446 struct ReadyList *plugins;
449 * Head of list of messages we would like to send to this peer;
450 * must contain at most one message per client.
452 struct MessageQueue *messages_head;
455 * Tail of list of messages we would like to send to this peer; must
456 * contain at most one message per client.
458 struct MessageQueue *messages_tail;
461 * Buffer for at most one payload message used when we receive
462 * payload data before our PING-PONG has succeeded. We then
463 * store such messages in this intermediary buffer until the
464 * connection is fully up.
466 struct GNUNET_MessageHeader *pre_connect_message_buffer;
469 * Context for peerinfo iteration.
470 * NULL after we are done processing peerinfo's information.
472 struct GNUNET_PEERINFO_IteratorContext *piter;
475 * Public key for this peer. Valid only if the respective flag is set below.
477 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
480 * Identity of this neighbour.
482 struct GNUNET_PeerIdentity id;
485 * ID of task scheduled to run when this peer is about to
486 * time out (will free resources associated with the peer).
488 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
491 * ID of task scheduled to run when we should retry transmitting
492 * the head of the message queue. Actually triggered when the
493 * transmission is timing out (we trigger instantly when we have
494 * a chance of success).
496 GNUNET_SCHEDULER_TaskIdentifier retry_task;
499 * How long until we should consider this peer dead
500 * (if we don't receive another message in the
503 struct GNUNET_TIME_Absolute peer_timeout;
506 * Tracker for inbound bandwidth.
508 struct GNUNET_BANDWIDTH_Tracker in_tracker;
511 * The latency we have seen for this particular address for
512 * this particular peer. This latency may have been calculated
513 * over multiple transports. This value reflects how long it took
514 * us to receive a response when SENDING via this particular
515 * transport/neighbour/address combination!
517 * FIXME: we need to periodically send PINGs to update this
518 * latency (at least more often than the current "huge" (11h?)
521 struct GNUNET_TIME_Relative latency;
524 * How often has the other peer (recently) violated the
525 * inbound traffic limit? Incremented by 10 per violation,
526 * decremented by 1 per non-violation (for each
529 unsigned int quota_violation_count;
532 * DV distance to this peer (1 if no DV is used).
537 * Have we seen an PONG from this neighbour in the past (and
538 * not had a disconnect since)?
543 * Do we have a valid public key for this neighbour?
545 int public_key_valid;
550 * Message used to ask a peer to validate receipt (to check an address
553 struct TransportPingMessage
557 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
559 struct GNUNET_MessageHeader header;
562 * Random challenge number (in network byte order).
564 uint32_t challenge GNUNET_PACKED;
567 * Who is the intended recipient?
569 struct GNUNET_PeerIdentity target;
575 * Message used to validate a HELLO. The challenge is included in the
576 * confirmation to make matching of replies to requests possible. The
577 * signature signs the original challenge number, our public key, the
578 * sender's address (so that the sender can check that the address we
579 * saw is plausible for him and possibly detect a MiM attack) and a
580 * timestamp (to limit replay).<p>
582 * This message is followed by the address of the
583 * client that we are observing (which is part of what
586 struct TransportPongMessage
590 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
592 struct GNUNET_MessageHeader header;
595 * For padding, always zero.
597 uint32_t reserved GNUNET_PACKED;
602 struct GNUNET_CRYPTO_RsaSignature signature;
605 * What are we signing and why?
607 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
610 * Random challenge number (in network byte order).
612 uint32_t challenge GNUNET_PACKED;
615 * Who signed this message?
617 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
620 * Size of address appended to this message
628 * Linked list of messages to be transmitted to the client. Each
629 * entry is followed by the actual message.
631 struct ClientMessageQueueEntry
634 * This is a doubly-linked list.
636 struct ClientMessageQueueEntry *next;
639 * This is a doubly-linked list.
641 struct ClientMessageQueueEntry *prev;
646 * Client connected to the transport service.
648 struct TransportClient
652 * This is a linked list.
654 struct TransportClient *next;
657 * Handle to the client.
659 struct GNUNET_SERVER_Client *client;
662 * Linked list of messages yet to be transmitted to
665 struct ClientMessageQueueEntry *message_queue_head;
668 * Tail of linked list of messages yet to be transmitted to the
671 struct ClientMessageQueueEntry *message_queue_tail;
674 * Current transmit request handle.
676 struct GNUNET_CONNECTION_TransmitHandle *th;
679 * Is a call to "transmit_send_continuation" pending? If so, we
680 * must not free this struct (even if the corresponding client
681 * disconnects) and instead only remove it from the linked list and
682 * set the "client" field to NULL.
687 * Length of the list of messages pending for this client.
689 unsigned int message_count;
695 * Context of currently active requests to peerinfo
696 * for validation of HELLOs.
698 struct CheckHelloValidatedContext;
702 * Entry in map of all HELLOs awaiting validation.
704 struct ValidationEntry
708 * NULL if this entry is not part of a larger HELLO validation.
710 struct CheckHelloValidatedContext *chvc;
713 * The address, actually a pointer to the end
714 * of this struct. Do not free!
719 * Name of the transport.
721 char *transport_name;
724 * The public key of the peer.
726 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
729 * ID of task that will clean up this entry if we don't succeed
730 * with the validation first.
732 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
735 * At what time did we send this validation?
737 struct GNUNET_TIME_Absolute send_time;
740 * Session being validated (or NULL for none).
742 struct Session *session;
745 * Challenge number we used.
758 * Context of currently active requests to peerinfo
759 * for validation of HELLOs.
761 struct CheckHelloValidatedContext
765 * This is a doubly-linked list.
767 struct CheckHelloValidatedContext *next;
770 * This is a doubly-linked list.
772 struct CheckHelloValidatedContext *prev;
775 * Hello that we are validating.
777 const struct GNUNET_HELLO_Message *hello;
780 * Context for peerinfo iteration.
781 * NULL after we are done processing peerinfo's information.
783 struct GNUNET_PEERINFO_IteratorContext *piter;
786 * Was a HELLO known for this peer to peerinfo?
791 * Number of validation entries currently referring to this
794 unsigned int ve_count;
802 static struct GNUNET_HELLO_Message *our_hello;
805 * "version" of "our_hello". Used to see if a given neighbour has
806 * already been sent the latest version of our HELLO message.
808 static unsigned int our_hello_version;
813 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
818 static struct GNUNET_PeerIdentity my_identity;
823 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
828 struct GNUNET_SCHEDULER_Handle *sched;
833 const struct GNUNET_CONFIGURATION_Handle *cfg;
836 * Linked list of all clients to this service.
838 static struct TransportClient *clients;
841 * All loaded plugins.
843 static struct TransportPlugin *plugins;
848 static struct GNUNET_SERVER_Handle *server;
851 * Handle to peerinfo service.
853 static struct GNUNET_PEERINFO_Handle *peerinfo;
856 * All known neighbours and their HELLOs.
858 static struct NeighbourList *neighbours;
861 * Number of neighbours we'd like to have.
863 static uint32_t max_connect_per_transport;
866 * Head of linked list.
868 static struct CheckHelloValidatedContext *chvc_head;
871 * Tail of linked list.
873 static struct CheckHelloValidatedContext *chvc_tail;
876 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
877 * of the given peer that we are currently validating).
879 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
882 * Handle for reporting statistics.
884 static struct GNUNET_STATISTICS_Handle *stats;
888 * The peer specified by the given neighbour has timed-out or a plugin
889 * has disconnected. We may either need to do nothing (other plugins
890 * still up), or trigger a full disconnect and clean up. This
891 * function updates our state and do the necessary notifications.
892 * Also notifies our clients that the neighbour is now officially
895 * @param n the neighbour list entry for the peer
896 * @param check should we just check if all plugins
897 * disconnected or must we ask all plugins to
900 static void disconnect_neighbour (struct NeighbourList *n, int check);
903 * Check the ready list for the given neighbour and if a plugin is
904 * ready for transmission (and if we have a message), do so!
906 * @param neighbour target peer for which to transmit
908 static void try_transmission_to_peer (struct NeighbourList *neighbour);
912 * Find an entry in the neighbour list for a particular peer.
914 * @return NULL if not found.
916 static struct NeighbourList *
917 find_neighbour (const struct GNUNET_PeerIdentity *key)
919 struct NeighbourList *head = neighbours;
921 while ((head != NULL) &&
922 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
929 * Find an entry in the transport list for a particular transport.
931 * @return NULL if not found.
933 static struct TransportPlugin *
934 find_transport (const char *short_name)
936 struct TransportPlugin *head = plugins;
937 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
943 * Is a particular peer blacklisted for a particular transport?
945 * @param peer the peer to check for
946 * @param plugin the plugin used to connect to the peer
948 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
951 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
954 if (plugin->blacklist != NULL)
956 if (GNUNET_CONTAINER_multihashmap_contains(plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960 _("Peer `%s:%s' is blacklisted!\n"),
961 plugin->short_name, GNUNET_i2s (peer));
972 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
974 struct TransportPlugin *plugin;
976 plugin = find_transport(transport_name);
977 if (plugin == NULL) /* Nothing to do */
979 if (plugin->blacklist == NULL)
980 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
981 GNUNET_assert(plugin->blacklist != NULL);
982 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
984 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
989 * Read the blacklist file, containing transport:peer entries.
990 * Provided the transport is loaded, set up hashmap with these
991 * entries to blacklist peers by transport.
995 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1002 struct GNUNET_PeerIdentity pid;
1004 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1005 unsigned int entries_found;
1006 char *transport_name;
1009 GNUNET_CONFIGURATION_get_value_filename (cfg,
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016 _("Option `%s' in section `%s' not specified!\n"),
1022 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1023 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1024 | GNUNET_DISK_PERM_USER_WRITE);
1025 if (0 != STAT (fn, &frstat))
1027 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1028 _("Could not read blacklist file `%s'\n"), fn);
1032 if (frstat.st_size == 0)
1034 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1035 _("Blacklist file `%s' is empty.\n"),
1040 /* FIXME: use mmap */
1041 data = GNUNET_malloc_large (frstat.st_size);
1042 if (frstat.st_size !=
1043 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1045 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1046 _("Failed to read blacklist from `%s'\n"), fn);
1053 while ((pos < frstat.st_size) && isspace (data[pos]))
1055 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1056 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1059 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace (data[colon_pos]))
1062 if (colon_pos >= frstat.st_size)
1064 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1065 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1066 (unsigned long long) colon_pos);
1072 if (isspace(data[colon_pos]))
1074 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1075 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1076 (unsigned long long) colon_pos);
1078 while ((pos < frstat.st_size) && isspace (data[pos]))
1082 tsize = colon_pos - pos;
1083 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size))
1085 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1086 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1087 (unsigned long long) colon_pos);
1093 transport_name = GNUNET_malloc(tsize);
1094 memcpy(transport_name, &data[pos], tsize);
1095 pos = colon_pos + 1;
1098 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099 _("Read transport name %s in blacklist file.\n"),
1102 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1103 if (!isspace (enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1105 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1106 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1107 (unsigned long long) pos);
1109 while ((pos < frstat.st_size) && (!isspace (data[pos])))
1111 GNUNET_free_non_null(transport_name);
1114 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1115 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1117 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1118 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1119 (unsigned long long) pos,
1124 if (0 != memcmp (&pid,
1126 sizeof (struct GNUNET_PeerIdentity)))
1129 add_peer_to_blacklist (&pid,
1131 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1132 _("Found blacklisted peer `%s:%s' in configuration\n"),
1133 transport_name, GNUNET_i2s (&pid));
1137 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1138 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1142 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1143 GNUNET_free_non_null(transport_name);
1144 while ((pos < frstat.st_size) && isspace (data[pos]))
1153 * Function called to notify a client about the socket being ready to
1154 * queue more data. "buf" will be NULL and "size" zero if the socket
1155 * was closed for writing in the meantime.
1157 * @param cls closure
1158 * @param size number of bytes available in buf
1159 * @param buf where the callee should write the message
1160 * @return number of bytes written to buf
1163 transmit_to_client_callback (void *cls, size_t size, void *buf)
1165 struct TransportClient *client = cls;
1166 struct ClientMessageQueueEntry *q;
1169 const struct GNUNET_MessageHeader *msg;
1175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1176 "Transmission to client failed, closing connection.\n");
1177 /* fatal error with client, free message queue! */
1178 while (NULL != (q = client->message_queue_head))
1180 GNUNET_STATISTICS_update (stats,
1181 gettext_noop ("# bytes discarded (could not transmit to client)"),
1182 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1184 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1185 client->message_queue_tail,
1189 client->message_count = 0;
1194 while (NULL != (q = client->message_queue_head))
1196 msg = (const struct GNUNET_MessageHeader *) &q[1];
1197 msize = ntohs (msg->size);
1198 if (msize + tsize > size)
1201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1202 "Transmitting message of type %u to client.\n",
1205 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1206 client->message_queue_tail,
1208 memcpy (&cbuf[tsize], msg, msize);
1211 client->message_count--;
1215 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1216 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1218 GNUNET_TIME_UNIT_FOREVER_REL,
1219 &transmit_to_client_callback,
1221 GNUNET_assert (client->th != NULL);
1228 * Mark the given FAL entry as 'connected' (and hence preferred for
1229 * sending); also mark all others for the same peer as 'not connected'
1230 * (since only one can be preferred).
1232 * @param fal address to set to 'connected'
1235 mark_address_connected (struct ForeignAddressList *fal)
1237 struct ForeignAddressList *pos;
1240 GNUNET_assert (GNUNET_YES == fal->validated);
1241 if (fal->connected == GNUNET_YES)
1242 return; /* nothing to do */
1244 pos = fal->ready_list->addresses;
1247 if (GNUNET_YES == pos->connected)
1249 GNUNET_break (cnt == GNUNET_YES);
1251 pos->connected = GNUNET_NO;
1255 fal->connected = GNUNET_YES;
1256 if (GNUNET_YES == cnt)
1258 GNUNET_STATISTICS_update (stats,
1259 gettext_noop ("# connected addresses"),
1267 * Send the specified message to the specified client. Since multiple
1268 * messages may be pending for the same client at a time, this code
1269 * makes sure that no message is lost.
1271 * @param client client to transmit the message to
1272 * @param msg the message to send
1273 * @param may_drop can this message be dropped if the
1274 * message queue for this client is getting far too large?
1277 transmit_to_client (struct TransportClient *client,
1278 const struct GNUNET_MessageHeader *msg, int may_drop)
1280 struct ClientMessageQueueEntry *q;
1283 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1285 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1287 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1288 client->message_count, MAX_PENDING);
1289 /* TODO: call to statistics... */
1292 msize = ntohs (msg->size);
1293 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1294 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1295 memcpy (&q[1], msg, msize);
1296 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1297 client->message_queue_tail,
1298 client->message_queue_tail,
1300 client->message_count++;
1301 if (client->th == NULL)
1303 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1305 GNUNET_TIME_UNIT_FOREVER_REL,
1306 &transmit_to_client_callback,
1308 GNUNET_assert (client->th != NULL);
1314 * Transmit a 'SEND_OK' notification to the given client for the
1317 * @param client who to notify
1318 * @param n neighbour to notify about
1319 * @param result status code for the transmission request
1322 transmit_send_ok (struct TransportClient *client,
1323 struct NeighbourList *n,
1326 struct SendOkMessage send_ok_msg;
1328 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1329 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1330 send_ok_msg.success = htonl (result);
1331 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1332 send_ok_msg.peer = n->id;
1333 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1338 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1339 * upon "completion" of a send request. This tells the API
1340 * that it is now legal to send another message to the given
1343 * @param cls closure, identifies the entry on the
1344 * message queue that was transmitted and the
1345 * client responsible for queueing the message
1346 * @param target the peer receiving the message
1347 * @param result GNUNET_OK on success, if the transmission
1348 * failed, we should not tell the client to transmit
1352 transmit_send_continuation (void *cls,
1353 const struct GNUNET_PeerIdentity *target,
1356 struct MessageQueue *mq = cls;
1357 struct NeighbourList *n;
1359 GNUNET_STATISTICS_update (stats,
1360 gettext_noop ("# bytes pending with plugins"),
1361 - (int64_t) mq->message_buf_size,
1363 if (result == GNUNET_OK)
1365 GNUNET_STATISTICS_update (stats,
1366 gettext_noop ("# bytes successfully transmitted by plugins"),
1367 mq->message_buf_size,
1372 GNUNET_STATISTICS_update (stats,
1373 gettext_noop ("# bytes with transmission failure by plugins"),
1374 mq->message_buf_size,
1377 n = find_neighbour(&mq->neighbour_id);
1378 GNUNET_assert (n != NULL);
1379 if (mq->specific_address != NULL)
1381 if (result == GNUNET_OK)
1383 mq->specific_address->timeout =
1384 GNUNET_TIME_relative_to_absolute
1385 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1386 if (mq->specific_address->validated == GNUNET_YES)
1387 mark_address_connected (mq->specific_address);
1391 if (mq->specific_address->connected != GNUNET_NO)
1393 GNUNET_STATISTICS_update (stats,
1394 gettext_noop ("# connected addresses"),
1397 mq->specific_address->connected = GNUNET_NO;
1400 if (! mq->internal_msg)
1401 mq->specific_address->in_transmit = GNUNET_NO;
1403 if (mq->client != NULL)
1404 transmit_send_ok (mq->client, n, result);
1406 try_transmission_to_peer (n);
1411 * Convert an address to a string.
1413 * @param plugin name of the plugin responsible for the address
1414 * @param addr binary address
1415 * @param addr_len number of bytes in addr
1416 * @return NULL on error, otherwise address string
1419 a2s (const char *plugin,
1423 struct TransportPlugin *p;
1427 p = find_transport (plugin);
1430 return p->api->address_to_string (p->api->cls,
1437 * Find an address in any of the available transports for
1438 * the given neighbour that would be good for message
1439 * transmission. This is essentially the transport selection
1442 * @param neighbour for whom to select an address
1443 * @return selected address, NULL if we have none
1445 struct ForeignAddressList *
1446 find_ready_address(struct NeighbourList *neighbour)
1448 struct ReadyList *head = neighbour->plugins;
1449 struct ForeignAddressList *addresses;
1450 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1451 struct ForeignAddressList *best_address;
1453 best_address = NULL;
1454 while (head != NULL)
1456 addresses = head->addresses;
1457 while (addresses != NULL)
1459 if ( (addresses->timeout.value < now.value) &&
1460 (addresses->connected == GNUNET_YES) )
1463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1464 "Marking long-time inactive connection to `%4s' as down.\n",
1465 GNUNET_i2s (&neighbour->id));
1467 GNUNET_STATISTICS_update (stats,
1468 gettext_noop ("# connected addresses"),
1471 addresses->connected = GNUNET_NO;
1473 addresses = addresses->next;
1476 addresses = head->addresses;
1477 while (addresses != NULL)
1479 #if DEBUG_TRANSPORT > 1
1480 if (addresses->addr != NULL)
1481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1482 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1483 a2s (head->plugin->short_name,
1485 addresses->addrlen),
1486 GNUNET_i2s (&neighbour->id),
1487 addresses->connected,
1488 addresses->in_transmit,
1489 addresses->validated,
1490 addresses->connect_attempts,
1491 (unsigned long long) addresses->timeout.value,
1492 (unsigned int) addresses->distance);
1494 if ( ( (best_address == NULL) ||
1495 (addresses->connected == GNUNET_YES) ||
1496 (best_address->connected == GNUNET_NO) ) &&
1497 (addresses->in_transmit == GNUNET_NO) &&
1498 ( (best_address == NULL) ||
1499 (addresses->latency.value < best_address->latency.value)) )
1500 best_address = addresses;
1501 /* FIXME: also give lower-latency addresses that are not
1502 connected a chance some times... */
1503 addresses = addresses->next;
1507 if (best_address != NULL)
1510 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1511 "Best address found has latency of %llu ms.\n",
1512 best_address->latency.value);
1517 GNUNET_STATISTICS_update (stats,
1518 gettext_noop ("# transmission attempts failed (no address)"),
1522 return best_address;
1528 * We should re-try transmitting to the given peer,
1529 * hopefully we've learned something in the meantime.
1532 retry_transmission_task (void *cls,
1533 const struct GNUNET_SCHEDULER_TaskContext *tc)
1535 struct NeighbourList *n = cls;
1537 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1538 try_transmission_to_peer (n);
1543 * Check the ready list for the given neighbour and if a plugin is
1544 * ready for transmission (and if we have a message), do so!
1546 * @param neighbour target peer for which to transmit
1549 try_transmission_to_peer (struct NeighbourList *neighbour)
1551 struct ReadyList *rl;
1552 struct MessageQueue *mq;
1553 struct GNUNET_TIME_Relative timeout;
1557 if (neighbour->messages_head == NULL)
1560 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1561 "Transmission queue for `%4s' is empty\n",
1562 GNUNET_i2s (&neighbour->id));
1564 return; /* nothing to do */
1567 mq = neighbour->messages_head;
1568 force_address = GNUNET_YES;
1569 if (mq->specific_address == NULL)
1571 mq->specific_address = find_ready_address(neighbour);
1572 GNUNET_STATISTICS_update (stats,
1573 gettext_noop ("# transport selected peer address freely"),
1576 force_address = GNUNET_NO;
1578 if (mq->specific_address == NULL)
1580 GNUNET_STATISTICS_update (stats,
1581 gettext_noop ("# transport failed to selected peer address"),
1584 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1585 if (timeout.value == 0)
1588 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1589 "No destination address available to transmit message of size %u to peer `%4s'\n",
1590 mq->message_buf_size,
1591 GNUNET_i2s (&mq->neighbour_id));
1593 GNUNET_STATISTICS_update (stats,
1594 gettext_noop ("# bytes in message queue for other peers"),
1595 - (int64_t) mq->message_buf_size,
1597 GNUNET_STATISTICS_update (stats,
1598 gettext_noop ("# bytes discarded (no destination address available)"),
1599 mq->message_buf_size,
1601 if (mq->client != NULL)
1602 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1603 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1604 neighbour->messages_tail,
1607 return; /* nobody ready */
1609 GNUNET_STATISTICS_update (stats,
1610 gettext_noop ("# message delivery deferred (no address)"),
1613 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1614 GNUNET_SCHEDULER_cancel (sched,
1615 neighbour->retry_task);
1616 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1618 &retry_transmission_task,
1621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1622 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1623 mq->message_buf_size,
1624 GNUNET_i2s (&mq->neighbour_id),
1627 /* FIXME: might want to trigger peerinfo lookup here
1628 (unless that's already pending...) */
1631 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1632 neighbour->messages_tail,
1634 if (mq->specific_address->connected == GNUNET_NO)
1635 mq->specific_address->connect_attempts++;
1636 rl = mq->specific_address->ready_list;
1637 mq->plugin = rl->plugin;
1638 if (!mq->internal_msg)
1639 mq->specific_address->in_transmit = GNUNET_YES;
1641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1642 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1643 mq->message_buf_size,
1644 GNUNET_i2s (&neighbour->id),
1645 (mq->specific_address->addr != NULL)
1646 ? a2s (mq->plugin->short_name,
1647 mq->specific_address->addr,
1648 mq->specific_address->addrlen)
1650 rl->plugin->short_name);
1652 GNUNET_STATISTICS_update (stats,
1653 gettext_noop ("# bytes in message queue for other peers"),
1654 - (int64_t) mq->message_buf_size,
1656 GNUNET_STATISTICS_update (stats,
1657 gettext_noop ("# bytes pending with plugins"),
1658 mq->message_buf_size,
1660 ret = rl->plugin->api->send (rl->plugin->api->cls,
1663 mq->message_buf_size,
1665 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1666 mq->specific_address->session,
1667 mq->specific_address->addr,
1668 mq->specific_address->addrlen,
1670 &transmit_send_continuation, mq);
1673 /* failure, but 'send' would not call continuation in this case,
1674 so we need to do it here! */
1675 transmit_send_continuation (mq,
1683 * Send the specified message to the specified peer.
1685 * @param client source of the transmission request (can be NULL)
1686 * @param peer_address ForeignAddressList where we should send this message
1687 * @param priority how important is the message
1688 * @param timeout how long do we have to transmit?
1689 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1690 * @param message_buf_size total size of all messages in message_buf
1691 * @param is_internal is this an internal message; these are pre-pended and
1692 * also do not count for plugins being "ready" to transmit
1693 * @param neighbour handle to the neighbour for transmission
1696 transmit_to_peer (struct TransportClient *client,
1697 struct ForeignAddressList *peer_address,
1698 unsigned int priority,
1699 struct GNUNET_TIME_Relative timeout,
1700 const char *message_buf,
1701 size_t message_buf_size,
1702 int is_internal, struct NeighbourList *neighbour)
1704 struct MessageQueue *mq;
1709 /* check for duplicate submission */
1710 mq = neighbour->messages_head;
1713 if (mq->client == client)
1715 /* client transmitted to same peer twice
1716 before getting SEND_OK! */
1724 GNUNET_STATISTICS_update (stats,
1725 gettext_noop ("# bytes in message queue for other peers"),
1728 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1729 mq->specific_address = peer_address;
1730 mq->client = client;
1731 memcpy (&mq[1], message_buf, message_buf_size);
1732 mq->message_buf = (const char*) &mq[1];
1733 mq->message_buf_size = message_buf_size;
1734 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1735 mq->internal_msg = is_internal;
1736 mq->priority = priority;
1737 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1739 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1740 neighbour->messages_tail,
1743 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1744 neighbour->messages_tail,
1745 neighbour->messages_tail,
1747 try_transmission_to_peer (neighbour);
1754 struct GeneratorContext
1756 struct TransportPlugin *plug_pos;
1757 struct OwnAddressList *addr_pos;
1758 struct GNUNET_TIME_Absolute expiration;
1766 address_generator (void *cls, size_t max, void *buf)
1768 struct GeneratorContext *gc = cls;
1771 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1773 gc->plug_pos = gc->plug_pos->next;
1774 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1776 if (NULL == gc->plug_pos)
1781 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1784 gc->addr_pos->addrlen, buf, max);
1785 gc->addr_pos = gc->addr_pos->next;
1791 * Construct our HELLO message from all of the addresses of
1792 * all of the transports.
1797 struct GNUNET_HELLO_Message *hello;
1798 struct TransportClient *cpos;
1799 struct NeighbourList *npos;
1800 struct GeneratorContext gc;
1802 gc.plug_pos = plugins;
1803 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1804 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1805 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1807 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1808 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1810 GNUNET_STATISTICS_update (stats,
1811 gettext_noop ("# refreshed my HELLO"),
1815 while (cpos != NULL)
1817 transmit_to_client (cpos,
1818 (const struct GNUNET_MessageHeader *) hello,
1823 GNUNET_free_non_null (our_hello);
1825 our_hello_version++;
1826 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1828 while (npos != NULL)
1831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1832 "Transmitting updated `%s' to neighbour `%4s'\n",
1833 "HELLO", GNUNET_i2s (&npos->id));
1835 GNUNET_STATISTICS_update (stats,
1836 gettext_noop ("# transmitted my HELLO to other peers"),
1839 transmit_to_peer (NULL, NULL, 0,
1840 HELLO_ADDRESS_EXPIRATION,
1841 (const char *) our_hello,
1842 GNUNET_HELLO_size(our_hello),
1850 * Task used to clean up expired addresses for a plugin.
1852 * @param cls closure
1856 expire_address_task (void *cls,
1857 const struct GNUNET_SCHEDULER_TaskContext *tc);
1861 * Update the list of addresses for this plugin,
1862 * expiring those that are past their expiration date.
1864 * @param plugin addresses of which plugin should be recomputed?
1865 * @param fresh set to GNUNET_YES if a new address was added
1866 * and we need to regenerate the HELLO even if nobody
1870 update_addresses (struct TransportPlugin *plugin, int fresh)
1872 static struct GNUNET_TIME_Absolute last_update;
1873 struct GNUNET_TIME_Relative min_remaining;
1874 struct GNUNET_TIME_Relative remaining;
1875 struct GNUNET_TIME_Absolute now;
1876 struct OwnAddressList *pos;
1877 struct OwnAddressList *prev;
1878 struct OwnAddressList *next;
1881 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1882 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1883 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1884 now = GNUNET_TIME_absolute_get ();
1885 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1886 expired = (GNUNET_TIME_absolute_get_duration (last_update).value > (HELLO_ADDRESS_EXPIRATION.value / 4));
1888 pos = plugin->addresses;
1892 if (pos->expires.value < now.value)
1894 expired = GNUNET_YES;
1896 plugin->addresses = pos->next;
1898 prev->next = pos->next;
1903 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1904 if (remaining.value < min_remaining.value)
1905 min_remaining = remaining;
1911 if (expired || fresh)
1916 min_remaining = GNUNET_TIME_relative_min (min_remaining,
1917 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1919 plugin->address_update_task
1920 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1922 &expire_address_task, plugin);
1927 * Task used to clean up expired addresses for a plugin.
1929 * @param cls closure
1933 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1935 struct TransportPlugin *plugin = cls;
1937 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1938 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1939 update_addresses (plugin, GNUNET_NO);
1944 * Iterator over hash map entries that NULLs the session of validation
1945 * entries that match the given session.
1947 * @param cls closure (the 'struct Session*' to match against)
1948 * @param key current key code (peer ID, not used)
1949 * @param value value in the hash map ('struct ValidationEntry*')
1950 * @return GNUNET_YES (we should continue to iterate)
1953 remove_session_validations (void *cls,
1954 const GNUNET_HashCode * key,
1957 struct Session *session = cls;
1958 struct ValidationEntry *ve = value;
1960 if (session == ve->session)
1967 * Function that will be called whenever the plugin internally
1968 * cleans up a session pointer and hence the service needs to
1969 * discard all of those sessions as well. Plugins that do not
1970 * use sessions can simply omit calling this function and always
1971 * use NULL wherever a session pointer is needed.
1973 * @param cls closure
1974 * @param peer which peer was the session for
1975 * @param session which session is being destoyed
1978 plugin_env_session_end (void *cls,
1979 const struct GNUNET_PeerIdentity *peer,
1980 struct Session *session)
1982 struct TransportPlugin *p = cls;
1983 struct NeighbourList *nl;
1984 struct ReadyList *rl;
1985 struct ForeignAddressList *pos;
1986 struct ForeignAddressList *prev;
1988 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
1989 &remove_session_validations,
1991 nl = find_neighbour (peer);
1997 if (rl->plugin == p)
2004 pos = rl->addresses;
2005 while ( (pos != NULL) &&
2006 (pos->session != session) )
2013 pos->session = NULL;
2014 if (pos->addrlen != 0)
2017 rl->addresses = pos->next;
2019 prev->next = pos->next;
2020 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2022 GNUNET_SCHEDULER_cancel (sched,
2023 pos->revalidate_task);
2024 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2027 if (nl->received_pong == GNUNET_NO)
2028 return; /* nothing to do */
2029 /* check if we have any validated addresses left */
2030 pos = rl->addresses;
2037 /* no valid addresses left, signal disconnect! */
2038 disconnect_neighbour (nl, GNUNET_NO);
2043 * Function that must be called by each plugin to notify the
2044 * transport service about the addresses under which the transport
2045 * provided by the plugin can be reached.
2047 * @param cls closure
2048 * @param name name of the transport that generated the address
2049 * @param addr one of the addresses of the host, NULL for the last address
2050 * the specific address format depends on the transport
2051 * @param addrlen length of the address
2052 * @param expires when should this address automatically expire?
2055 plugin_env_notify_address (void *cls,
2059 struct GNUNET_TIME_Relative expires)
2061 struct TransportPlugin *p = cls;
2062 struct OwnAddressList *al;
2063 struct GNUNET_TIME_Absolute abex;
2065 GNUNET_assert (addr != NULL);
2066 abex = GNUNET_TIME_relative_to_absolute (expires);
2067 GNUNET_assert (p == find_transport (name));
2071 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2073 if (al->expires.value < abex.value)
2080 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2082 al->next = p->addresses;
2085 al->addrlen = addrlen;
2086 memcpy (&al[1], addr, addrlen);
2087 update_addresses (p, GNUNET_YES);
2092 * Notify all of our clients about a peer connecting.
2095 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2096 struct GNUNET_TIME_Relative latency,
2099 struct ConnectInfoMessage cim;
2100 struct TransportClient *cpos;
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "Notifying clients about connection from `%s'\n",
2107 GNUNET_STATISTICS_update (stats,
2108 gettext_noop ("# peers connected"),
2111 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2112 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2113 cim.distance = htonl (distance);
2114 cim.latency = GNUNET_TIME_relative_hton (latency);
2115 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
2117 while (cpos != NULL)
2119 transmit_to_client (cpos, &cim.header, GNUNET_NO);
2126 * Notify all of our clients about a peer disconnecting.
2129 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2131 struct DisconnectInfoMessage dim;
2132 struct TransportClient *cpos;
2135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136 "Notifying clients about lost connection to `%s'\n",
2139 GNUNET_STATISTICS_update (stats,
2140 gettext_noop ("# peers connected"),
2143 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2144 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2145 dim.reserved = htonl (0);
2146 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2148 while (cpos != NULL)
2150 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2157 * Find a ForeignAddressList entry for the given neighbour
2158 * that matches the given address and transport.
2160 * @param neighbour which peer we care about
2161 * @param tname name of the transport plugin
2162 * @param session session to look for, NULL for 'any'; otherwise
2163 * can be used for the service to "learn" this session ID
2165 * @param addr binary address
2166 * @param addrlen length of addr
2167 * @return NULL if no such entry exists
2169 static struct ForeignAddressList *
2170 find_peer_address(struct NeighbourList *neighbour,
2172 struct Session *session,
2176 struct ReadyList *head;
2177 struct ForeignAddressList *pos;
2179 head = neighbour->plugins;
2180 while (head != NULL)
2182 if (0 == strcmp (tname, head->plugin->short_name))
2188 pos = head->addresses;
2189 while ( (pos != NULL) &&
2190 ( (pos->addrlen != addrlen) ||
2191 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2193 if ( (session != NULL) &&
2194 (pos->session == session) )
2198 if ( (session != NULL) && (pos != NULL) )
2199 pos->session = session; /* learn it! */
2205 * Get the peer address struct for the given neighbour and
2206 * address. If it doesn't yet exist, create it.
2208 * @param neighbour which peer we care about
2209 * @param tname name of the transport plugin
2210 * @param session session of the plugin, or NULL for none
2211 * @param addr binary address
2212 * @param addrlen length of addr
2213 * @return NULL if we do not have a transport plugin for 'tname'
2215 static struct ForeignAddressList *
2216 add_peer_address (struct NeighbourList *neighbour,
2218 struct Session *session,
2222 struct ReadyList *head;
2223 struct ForeignAddressList *ret;
2225 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2228 head = neighbour->plugins;
2230 while (head != NULL)
2232 if (0 == strcmp (tname, head->plugin->short_name))
2238 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2239 ret->session = session;
2242 ret->addr = (const char*) &ret[1];
2243 memcpy (&ret[1], addr, addrlen);
2249 ret->addrlen = addrlen;
2250 ret->expires = GNUNET_TIME_relative_to_absolute
2251 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2252 ret->latency = GNUNET_TIME_relative_get_forever();
2254 ret->timeout = GNUNET_TIME_relative_to_absolute
2255 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2256 ret->ready_list = head;
2257 ret->next = head->addresses;
2258 head->addresses = ret;
2264 * Closure for 'add_validated_address'.
2266 struct AddValidatedAddressContext
2269 * Entry that has been validated.
2271 const struct ValidationEntry *ve;
2274 * Flag set after we have added the address so
2275 * that we terminate the iteration next time.
2282 * Callback function used to fill a buffer of max bytes with a list of
2283 * addresses in the format used by HELLOs. Should use
2284 * "GNUNET_HELLO_add_address" as a helper function.
2286 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2287 * @param max maximum number of bytes that can be written to buf
2288 * @param buf where to write the address information
2289 * @return number of bytes written, 0 to signal the
2290 * end of the iteration.
2293 add_validated_address (void *cls,
2294 size_t max, void *buf)
2296 struct AddValidatedAddressContext *avac = cls;
2297 const struct ValidationEntry *ve = avac->ve;
2299 if (GNUNET_YES == avac->done)
2301 avac->done = GNUNET_YES;
2302 return GNUNET_HELLO_add_address (ve->transport_name,
2303 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2313 * Closure for 'check_address_exists'.
2315 struct CheckAddressExistsClosure
2318 * Address to check for.
2323 * Name of the transport.
2330 struct Session *session;
2333 * Set to GNUNET_YES if the address exists.
2346 * Iterator over hash map entries. Checks if the given
2347 * validation entry is for the same address as what is given
2350 * @param cls the 'struct CheckAddressExistsClosure*'
2351 * @param key current key code (ignored)
2352 * @param value value in the hash map ('struct ValidationEntry')
2353 * @return GNUNET_YES if we should continue to
2354 * iterate (mismatch), GNUNET_NO if not (entry matched)
2357 check_address_exists (void *cls,
2358 const GNUNET_HashCode * key,
2361 struct CheckAddressExistsClosure *caec = cls;
2362 struct ValidationEntry *ve = value;
2364 if ( (0 == strcmp (caec->tname,
2365 ve->transport_name)) &&
2366 (caec->addrlen == ve->addrlen) &&
2367 (0 == memcmp (caec->addr,
2371 caec->exists = GNUNET_YES;
2374 if ( (ve->session != NULL) &&
2375 (caec->session == ve->session) )
2377 caec->exists = GNUNET_YES;
2386 * Iterator to free entries in the validation_map.
2388 * @param cls closure (unused)
2389 * @param key current key code
2390 * @param value value in the hash map (validation to abort)
2391 * @return GNUNET_YES (always)
2394 abort_validation (void *cls,
2395 const GNUNET_HashCode * key,
2398 struct ValidationEntry *va = value;
2400 if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2401 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
2402 GNUNET_free (va->transport_name);
2403 if (va->chvc != NULL)
2405 va->chvc->ve_count--;
2406 if (va->chvc->ve_count == 0)
2408 GNUNET_CONTAINER_DLL_remove (chvc_head,
2411 GNUNET_free (va->chvc);
2420 * HELLO validation cleanup task (validation failed).
2422 * @param cls the 'struct ValidationEntry' that failed
2423 * @param tc scheduler context (unused)
2426 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2428 struct ValidationEntry *va = cls;
2429 struct GNUNET_PeerIdentity pid;
2431 va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2432 GNUNET_STATISTICS_update (stats,
2433 gettext_noop ("# address validation timeouts"),
2436 GNUNET_CRYPTO_hash (&va->publicKey,
2438 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2440 GNUNET_break (GNUNET_OK ==
2441 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2444 abort_validation (NULL, NULL, va);
2449 neighbour_timeout_task (void *cls,
2450 const struct GNUNET_SCHEDULER_TaskContext *tc)
2452 struct NeighbourList *n = cls;
2455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2456 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2458 GNUNET_STATISTICS_update (stats,
2459 gettext_noop ("# disconnects due to timeout"),
2462 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2463 disconnect_neighbour (n, GNUNET_NO);
2468 * Schedule the job that will cause us to send a PING to the
2469 * foreign address to evaluate its validity and latency.
2471 * @param fal address to PING
2474 schedule_next_ping (struct ForeignAddressList *fal);
2478 * Add the given address to the list of foreign addresses
2479 * available for the given peer (check for duplicates).
2481 * @param cls the respective 'struct NeighbourList' to update
2482 * @param tname name of the transport
2483 * @param expiration expiration time
2484 * @param addr the address
2485 * @param addrlen length of the address
2486 * @return GNUNET_OK (always)
2489 add_to_foreign_address_list (void *cls,
2491 struct GNUNET_TIME_Absolute expiration,
2495 struct NeighbourList *n = cls;
2496 struct ForeignAddressList *fal;
2499 GNUNET_STATISTICS_update (stats,
2500 gettext_noop ("# valid peer addresses returned by PEERINFO"),
2504 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2509 "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2510 a2s (tname, addr, addrlen),
2512 GNUNET_i2s (&n->id),
2515 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2518 GNUNET_STATISTICS_update (stats,
2519 gettext_noop ("# previously validated addresses lacking transport"),
2525 fal->expires = GNUNET_TIME_absolute_max (expiration,
2527 schedule_next_ping (fal);
2533 fal->expires = GNUNET_TIME_absolute_max (expiration,
2538 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2539 "Failed to add new address for `%4s'\n",
2540 GNUNET_i2s (&n->id));
2543 if (fal->validated == GNUNET_NO)
2545 fal->validated = GNUNET_YES;
2546 GNUNET_STATISTICS_update (stats,
2547 gettext_noop ("# peer addresses considered valid"),
2551 if (try == GNUNET_YES)
2553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2554 "Have new addresses, will try to trigger transmissions.\n");
2555 try_transmission_to_peer (n);
2562 * Add addresses in validated HELLO "h" to the set of addresses
2563 * we have for this peer.
2565 * @param cls closure ('struct NeighbourList*')
2566 * @param peer id of the peer, NULL for last call
2567 * @param h hello message for the peer (can be NULL)
2568 * @param trust amount of trust we have in the peer (not used)
2571 add_hello_for_peer (void *cls,
2572 const struct GNUNET_PeerIdentity *peer,
2573 const struct GNUNET_HELLO_Message *h,
2576 struct NeighbourList *n = cls;
2584 return; /* no HELLO available */
2586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2587 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2591 if (GNUNET_YES != n->public_key_valid)
2593 GNUNET_HELLO_get_key (h, &n->publicKey);
2594 n->public_key_valid = GNUNET_YES;
2596 GNUNET_HELLO_iterate_addresses (h,
2598 &add_to_foreign_address_list,
2604 * Create a fresh entry in our neighbour list for the given peer.
2605 * Will try to transmit our current HELLO to the new neighbour.
2606 * Do not call this function directly, use 'setup_peer_check_blacklist.
2608 * @param peer the peer for which we create the entry
2609 * @param do_hello should we schedule transmitting a HELLO
2610 * @return the new neighbour list entry
2612 static struct NeighbourList *
2613 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2616 struct NeighbourList *n;
2617 struct TransportPlugin *tp;
2618 struct ReadyList *rl;
2620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2621 "Setting up state for neighbour `%4s'\n",
2623 GNUNET_assert (our_hello != NULL);
2624 GNUNET_STATISTICS_update (stats,
2625 gettext_noop ("# active neighbours"),
2628 n = GNUNET_malloc (sizeof (struct NeighbourList));
2629 n->next = neighbours;
2633 GNUNET_TIME_relative_to_absolute
2634 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2635 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2636 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2637 MAX_BANDWIDTH_CARRY_S);
2641 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2643 rl = GNUNET_malloc (sizeof (struct ReadyList));
2645 rl->next = n->plugins;
2648 rl->addresses = NULL;
2652 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2654 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2655 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2656 &neighbour_timeout_task, n);
2659 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2660 0, GNUNET_TIME_UNIT_FOREVER_REL,
2661 &add_hello_for_peer, n);
2662 transmit_to_peer (NULL, NULL, 0,
2663 HELLO_ADDRESS_EXPIRATION,
2664 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2672 * Function called after we have checked if communicating
2673 * with a given peer is acceptable.
2675 * @param cls closure
2676 * @param n NULL if communication is not acceptable
2678 typedef void (*SetupContinuation)(void *cls,
2679 struct NeighbourList *n);
2683 * Information kept for each client registered to perform
2689 * This is a linked list.
2691 struct Blacklisters *next;
2694 * This is a linked list.
2696 struct Blacklisters *prev;
2699 * Client responsible for this entry.
2701 struct GNUNET_SERVER_Client *client;
2704 * Blacklist check that we're currently performing.
2706 struct BlacklistCheck *bc;
2712 * Head of DLL of blacklisting clients.
2714 static struct Blacklisters *bl_head;
2717 * Tail of DLL of blacklisting clients.
2719 static struct Blacklisters *bl_tail;
2723 * Context we use when performing a blacklist check.
2725 struct BlacklistCheck
2729 * This is a linked list.
2731 struct BlacklistCheck *next;
2734 * This is a linked list.
2736 struct BlacklistCheck *prev;
2739 * Peer being checked.
2741 struct GNUNET_PeerIdentity peer;
2744 * Option for setup neighbour afterwards.
2749 * Continuation to call with the result.
2751 SetupContinuation cont;
2759 * Current transmission request handle for this client, or NULL if no
2760 * request is pending.
2762 struct GNUNET_CONNECTION_TransmitHandle *th;
2765 * Our current position in the blacklisters list.
2767 struct Blacklisters *bl_pos;
2770 * Current task performing the check.
2772 GNUNET_SCHEDULER_TaskIdentifier task;
2777 * Head of DLL of active blacklisting queries.
2779 static struct BlacklistCheck *bc_head;
2782 * Tail of DLL of active blacklisting queries.
2784 static struct BlacklistCheck *bc_tail;
2788 * Perform next action in the blacklist check.
2790 * @param cls the 'struct BlacklistCheck*'
2794 do_blacklist_check (void *cls,
2795 const struct GNUNET_SCHEDULER_TaskContext *tc);
2799 * Transmit blacklist query to the client.
2801 * @param cls the 'struct BlacklistCheck'
2802 * @param size number of bytes allowed
2803 * @param buf where to copy the message
2804 * @return number of bytes copied to buf
2807 transmit_blacklist_message (void *cls,
2811 struct BlacklistCheck *bc = cls;
2812 struct Blacklisters *bl;
2813 struct BlacklistMessage bm;
2818 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2819 bc->task = GNUNET_SCHEDULER_add_now (sched,
2820 &do_blacklist_check,
2825 bm.header.size = htons (sizeof (struct BlacklistMessage));
2826 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
2827 bm.is_allowed = htonl (0);
2829 memcpy (buf, &bm, sizeof (bm));
2830 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
2836 * Perform next action in the blacklist check.
2838 * @param cls the 'struct BlacklistCheck*'
2842 do_blacklist_check (void *cls,
2843 const struct GNUNET_SCHEDULER_TaskContext *tc)
2845 struct BlacklistCheck *bc = cls;
2846 struct Blacklisters *bl;
2848 bc->task = GNUNET_SCHEDULER_NO_TASK;
2852 bc->cont (bc->cont_cls,
2853 setup_new_neighbour (&bc->peer, bc->do_hello));
2860 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
2861 sizeof (struct BlacklistMessage),
2862 GNUNET_TIME_UNIT_FOREVER_REL,
2863 &transmit_blacklist_message,
2870 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
2871 * does not yet exist, check the blacklist. If the blacklist says creating
2872 * one is acceptable, create one and call the continuation; otherwise
2873 * call the continuation with NULL.
2875 * @param peer peer to setup or look up a struct NeighbourList for
2876 * @param do_hello should we also schedule sending our HELLO to the peer
2877 * if this is a new record
2878 * @param cont function to call with the 'struct NeigbhbourList*'
2879 * @param cont_cls closure for cont
2882 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
2884 SetupContinuation cont,
2887 struct NeighbourList *n;
2888 struct BlacklistCheck *bc;
2890 n = find_neighbour(peer);
2896 if (bl_head == NULL)
2899 setup_new_neighbour (peer, do_hello));
2902 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2903 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2905 bc->do_hello = do_hello;
2907 bc->cont_cls = cont_cls;
2908 bc->bl_pos = bl_head;
2909 bc->task = GNUNET_SCHEDULER_add_now (sched,
2910 &do_blacklist_check,
2916 * Function called with the result of querying a new blacklister about
2917 * it being allowed (or not) to continue to talk to an existing neighbour.
2919 * @param cls the original 'struct NeighbourList'
2920 * @param n NULL if we need to disconnect
2923 confirm_or_drop_neighbour (void *cls,
2924 struct NeighbourList *n)
2926 struct NeighbourList * orig = cls;
2929 disconnect_neighbour (orig, GNUNET_NO);
2934 * Handle a request to start a blacklist.
2936 * @param cls closure (always NULL)
2937 * @param client identification of the client
2938 * @param message the actual message
2941 handle_blacklist_init (void *cls,
2942 struct GNUNET_SERVER_Client *client,
2943 const struct GNUNET_MessageHeader *message)
2945 struct Blacklisters *bl;
2946 struct BlacklistCheck *bc;
2947 struct NeighbourList *n;
2952 if (bl->client == client)
2955 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2960 bl = GNUNET_malloc (sizeof (struct Blacklisters));
2961 bl->client = client;
2962 GNUNET_SERVER_client_keep (client);
2963 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
2964 /* confirm that all existing connections are OK! */
2968 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2969 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2971 bc->do_hello = GNUNET_NO;
2972 bc->cont = &confirm_or_drop_neighbour;
2975 if (n == neighbours) /* all would wait for the same client, no need to
2976 create more than just the first task right now */
2977 bc->task = GNUNET_SCHEDULER_add_now (sched,
2978 &do_blacklist_check,
2986 * Handle a request to blacklist a peer.
2988 * @param cls closure (always NULL)
2989 * @param client identification of the client
2990 * @param message the actual message
2993 handle_blacklist_reply (void *cls,
2994 struct GNUNET_SERVER_Client *client,
2995 const struct GNUNET_MessageHeader *message)
2997 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
2998 struct Blacklisters *bl;
2999 struct BlacklistCheck *bc;
3002 while ( (bl != NULL) &&
3003 (bl->client != client) )
3007 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3012 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3014 bc->cont (bc->cont_cls, NULL);
3015 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3020 bc->bl_pos = bc->bl_pos->next;
3021 bc->task = GNUNET_SCHEDULER_add_now (sched,
3022 &do_blacklist_check,
3025 /* check if any other bc's are waiting for this blacklister */
3029 if ( (bc->bl_pos == bl) &&
3030 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3031 bc->task = GNUNET_SCHEDULER_add_now (sched,
3032 &do_blacklist_check,
3040 * Send periodic PING messages to a given foreign address.
3042 * @param cls our 'struct PeriodicValidationContext*'
3043 * @param tc task context
3046 send_periodic_ping (void *cls,
3047 const struct GNUNET_SCHEDULER_TaskContext *tc)
3049 struct ForeignAddressList *peer_address = cls;
3050 struct TransportPlugin *tp;
3051 struct ValidationEntry *va;
3052 struct NeighbourList *neighbour;
3053 struct TransportPingMessage ping;
3054 struct CheckAddressExistsClosure caec;
3056 uint16_t hello_size;
3059 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3060 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3062 tp = peer_address->ready_list->plugin;
3063 neighbour = peer_address->ready_list->neighbour;
3064 if (GNUNET_YES != neighbour->public_key_valid)
3066 /* no public key yet, try again later */
3067 schedule_next_ping (peer_address);
3070 caec.addr = peer_address->addr;
3071 caec.addrlen = peer_address->addrlen;
3072 caec.tname = tp->short_name;
3073 caec.session = peer_address->session;
3074 caec.exists = GNUNET_NO;
3075 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3076 &check_address_exists,
3078 if (caec.exists == GNUNET_YES)
3080 /* During validation attempts we will likely trigger the other
3081 peer trying to validate our address which in turn will cause
3082 it to send us its HELLO, so we expect to hit this case rather
3083 frequently. Only print something if we are very verbose. */
3084 #if DEBUG_TRANSPORT > 1
3085 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3086 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3087 (peer_address->addr != NULL)
3088 ? a2s (tp->short_name,
3090 peer_address->addrlen)
3093 GNUNET_i2s (&neighbour->id));
3095 schedule_next_ping (peer_address);
3098 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3099 va->transport_name = GNUNET_strdup (tp->short_name);
3100 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3102 va->send_time = GNUNET_TIME_absolute_get();
3103 va->session = peer_address->session;
3104 if (peer_address->addr != NULL)
3106 va->addr = (const void*) &va[1];
3107 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3108 va->addrlen = peer_address->addrlen;
3110 memcpy(&va->publicKey,
3111 &neighbour->publicKey,
3112 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3114 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3115 HELLO_VERIFICATION_TIMEOUT,
3116 &timeout_hello_validation,
3118 GNUNET_CONTAINER_multihashmap_put (validation_map,
3119 &neighbour->id.hashPubKey,
3121 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3122 hello_size = GNUNET_HELLO_size(our_hello);
3123 tsize = sizeof(struct TransportPingMessage) + hello_size;
3124 message_buf = GNUNET_malloc(tsize);
3125 ping.challenge = htonl(va->challenge);
3126 ping.header.size = htons(sizeof(struct TransportPingMessage));
3127 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3128 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3129 memcpy(message_buf, our_hello, hello_size);
3130 memcpy(&message_buf[hello_size],
3132 sizeof(struct TransportPingMessage));
3133 #if DEBUG_TRANSPORT_REVALIDATION
3134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3135 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3136 (peer_address->addr != NULL)
3137 ? a2s (peer_address->plugin->short_name,
3139 peer_address->addrlen)
3142 GNUNET_i2s (&neighbour->id),
3143 "HELLO", hello_size,
3144 "PING", sizeof (struct TransportPingMessage));
3146 GNUNET_STATISTICS_update (stats,
3147 gettext_noop ("# PING messages sent for re-validation"),
3150 transmit_to_peer (NULL, peer_address,
3151 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3152 HELLO_VERIFICATION_TIMEOUT,
3154 GNUNET_YES, neighbour);
3155 GNUNET_free(message_buf);
3156 schedule_next_ping (peer_address);
3161 * Schedule the job that will cause us to send a PING to the
3162 * foreign address to evaluate its validity and latency.
3164 * @param fal address to PING
3167 schedule_next_ping (struct ForeignAddressList *fal)
3169 struct GNUNET_TIME_Relative delay;
3171 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3173 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3174 delay.value /= 2; /* do before expiration */
3175 delay = GNUNET_TIME_relative_min (delay,
3176 LATENCY_EVALUATION_MAX_DELAY);
3177 if (GNUNET_YES != fal->estimated)
3179 delay = GNUNET_TIME_UNIT_ZERO;
3180 fal->estimated = GNUNET_YES;
3182 if (GNUNET_YES == fal->connected)
3184 delay = GNUNET_TIME_relative_min (delay,
3185 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3187 /* FIXME: also adjust delay based on how close the last
3188 observed latency is to the latency of the best alternative */
3189 /* bound how fast we can go */
3190 delay = GNUNET_TIME_relative_max (delay,
3191 GNUNET_TIME_UNIT_SECONDS);
3192 /* randomize a bit (to avoid doing all at the same time) */
3193 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3194 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
3196 &send_periodic_ping,
3204 * Function that will be called if we receive some payload
3205 * from another peer.
3207 * @param message the payload
3208 * @param n peer who claimed to be the sender
3211 handle_payload_message (const struct GNUNET_MessageHeader *message,
3212 struct NeighbourList *n)
3214 struct InboundMessage *im;
3215 struct TransportClient *cpos;
3218 msize = ntohs (message->size);
3219 if (n->received_pong == GNUNET_NO)
3221 GNUNET_free_non_null (n->pre_connect_message_buffer);
3222 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3223 memcpy (n->pre_connect_message_buffer, message, msize);
3227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3228 "Received message of type %u from `%4s', sending to all clients.\n",
3229 ntohs (message->type),
3230 GNUNET_i2s (&n->id));
3232 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3235 n->quota_violation_count++;
3237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3238 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3239 n->in_tracker.available_bytes_per_s__,
3240 n->quota_violation_count);
3242 /* Discount 32k per violation */
3243 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3248 if (n->quota_violation_count > 0)
3250 /* try to add 32k back */
3251 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3253 n->quota_violation_count--;
3256 GNUNET_STATISTICS_update (stats,
3257 gettext_noop ("# payload received from other peers"),
3260 /* transmit message to all clients */
3261 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3262 im->header.size = htons (sizeof (struct InboundMessage) + msize);
3263 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3264 im->latency = GNUNET_TIME_relative_hton (n->latency);
3266 im->distance = ntohl(n->distance);
3267 memcpy (&im[1], message, msize);
3269 while (cpos != NULL)
3271 transmit_to_client (cpos, &im->header, GNUNET_YES);
3279 * Iterator over hash map entries. Checks if the given validation
3280 * entry is for the same challenge as what is given in the PONG.
3282 * @param cls the 'struct TransportPongMessage*'
3283 * @param key peer identity
3284 * @param value value in the hash map ('struct ValidationEntry')
3285 * @return GNUNET_YES if we should continue to
3286 * iterate (mismatch), GNUNET_NO if not (entry matched)
3289 check_pending_validation (void *cls,
3290 const GNUNET_HashCode * key,
3293 const struct TransportPongMessage *pong = cls;
3294 struct ValidationEntry *ve = value;
3295 struct AddValidatedAddressContext avac;
3296 unsigned int challenge = ntohl(pong->challenge);
3297 struct GNUNET_HELLO_Message *hello;
3298 struct GNUNET_PeerIdentity target;
3299 struct NeighbourList *n;
3300 struct ForeignAddressList *fal;
3301 struct GNUNET_MessageHeader *prem;
3303 if (ve->challenge != challenge)
3308 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING,
3313 GNUNET_break_op (0);
3319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3323 ? a2s (ve->transport_name,
3324 (const struct sockaddr *) ve->addr,
3327 ve->transport_name);
3329 GNUNET_STATISTICS_update (stats,
3330 gettext_noop ("# address validation successes"),
3333 /* create the updated HELLO */
3334 GNUNET_CRYPTO_hash (&ve->publicKey,
3335 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3336 &target.hashPubKey);
3337 if (ve->addr != NULL)
3339 avac.done = GNUNET_NO;
3341 hello = GNUNET_HELLO_create (&ve->publicKey,
3342 &add_validated_address,
3344 GNUNET_PEERINFO_add_peer (peerinfo,
3346 GNUNET_free (hello);
3348 n = find_neighbour (&target);
3351 n->publicKey = ve->publicKey;
3352 n->public_key_valid = GNUNET_YES;
3353 fal = add_peer_address (n,
3358 GNUNET_assert (fal != NULL);
3359 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3360 fal->validated = GNUNET_YES;
3361 mark_address_connected (fal);
3362 GNUNET_STATISTICS_update (stats,
3363 gettext_noop ("# peer addresses considered valid"),
3366 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3367 schedule_next_ping (fal);
3368 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
3369 n->latency = fal->latency;
3371 n->latency.value = (fal->latency.value + n->latency.value) / 2;
3373 n->distance = fal->distance;
3374 if (GNUNET_NO == n->received_pong)
3376 n->received_pong = GNUNET_YES;
3377 notify_clients_connect (&target, n->latency, n->distance);
3378 if (NULL != (prem = n->pre_connect_message_buffer))
3380 n->pre_connect_message_buffer = NULL;
3381 handle_payload_message (prem, n);
3385 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3387 GNUNET_SCHEDULER_cancel (sched,
3389 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3390 try_transmission_to_peer (n);
3394 /* clean up validation entry */
3395 GNUNET_assert (GNUNET_YES ==
3396 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3399 abort_validation (NULL, NULL, ve);
3405 * Function that will be called if we receive a validation
3406 * of an address challenge that we transmitted to another
3407 * peer. Note that the validation should only be considered
3408 * acceptable if the challenge matches AND if the sender
3409 * address is at least a plausible address for this peer
3410 * (otherwise we may be seeing a MiM attack).
3412 * @param cls closure
3413 * @param message the pong message
3414 * @param peer who responded to our challenge
3415 * @param sender_address string describing our sender address (as observed
3416 * by the other peer in binary format)
3417 * @param sender_address_len number of bytes in 'sender_address'
3420 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3421 const struct GNUNET_PeerIdentity *peer,
3422 const char *sender_address,
3423 size_t sender_address_len)
3425 #if DEBUG_TRANSPORT > 1
3426 /* we get tons of these that just get discarded, only log
3427 if we are quite verbose */
3428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3429 "Receiving `%s' message from `%4s'.\n", "PONG",
3432 GNUNET_STATISTICS_update (stats,
3433 gettext_noop ("# PONG messages received"),
3436 if (GNUNET_SYSERR !=
3437 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3439 &check_pending_validation,
3442 /* This is *expected* to happen a lot since we send
3443 PONGs to *all* known addresses of the sender of
3444 the PING, so most likely we get multiple PONGs
3445 per PING, and all but the first PONG will end up
3446 here. So really we should not print anything here
3447 unless we want to be very, very verbose... */
3448 #if DEBUG_TRANSPORT > 2
3449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3450 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3462 * Try to validate a neighbour's address by sending him our HELLO and a PING.
3464 * @param cls the 'struct ValidationEntry*'
3465 * @param neighbour neighbour to validate, NULL if validation failed
3468 transmit_hello_and_ping (void *cls,
3469 struct NeighbourList *neighbour)
3471 struct ValidationEntry *va = cls;
3472 struct ForeignAddressList *peer_address;
3473 struct TransportPingMessage ping;
3474 uint16_t hello_size;
3478 if (neighbour == NULL)
3480 /* FIXME: stats... */
3481 GNUNET_free (va->transport_name);
3485 neighbour->publicKey = va->publicKey;
3486 neighbour->public_key_valid = GNUNET_YES;
3487 peer_address = add_peer_address (neighbour,
3488 va->transport_name, NULL,
3489 (const void*) &va[1],
3491 if (peer_address == NULL)
3493 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3494 "Failed to add peer `%4s' for plugin `%s'\n",
3495 GNUNET_i2s (&neighbour->id),
3496 va->transport_name);
3497 GNUNET_free (va->transport_name);
3501 hello_size = GNUNET_HELLO_size(our_hello);
3502 tsize = sizeof(struct TransportPingMessage) + hello_size;
3503 message_buf = GNUNET_malloc(tsize);
3504 ping.challenge = htonl(va->challenge);
3505 ping.header.size = htons(sizeof(struct TransportPingMessage));
3506 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3507 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3508 memcpy(message_buf, our_hello, hello_size);
3509 memcpy(&message_buf[hello_size],
3511 sizeof(struct TransportPingMessage));
3513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3514 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3515 a2s (va->transport_name,
3516 (const void*) &va[1], va->addrlen),
3518 GNUNET_i2s (&neighbour->id),
3519 "HELLO", hello_size,
3520 "PING", sizeof (struct TransportPingMessage));
3522 GNUNET_STATISTICS_update (stats,
3523 gettext_noop ("# PING messages sent for initial validation"),
3526 transmit_to_peer (NULL, peer_address,
3527 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3528 HELLO_VERIFICATION_TIMEOUT,
3530 GNUNET_YES, neighbour);
3531 GNUNET_free(message_buf);
3536 * Check if the given address is already being validated; if not,
3537 * append the given address to the list of entries that are being be
3538 * validated and initiate validation.
3540 * @param cls closure ('struct CheckHelloValidatedContext *')
3541 * @param tname name of the transport
3542 * @param expiration expiration time
3543 * @param addr the address
3544 * @param addrlen length of the address
3545 * @return GNUNET_OK (always)
3548 run_validation (void *cls,
3550 struct GNUNET_TIME_Absolute expiration,
3554 struct CheckHelloValidatedContext *chvc = cls;
3555 struct GNUNET_PeerIdentity id;
3556 struct TransportPlugin *tp;
3557 struct ValidationEntry *va;
3558 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3559 struct CheckAddressExistsClosure caec;
3560 struct OwnAddressList *oal;
3562 GNUNET_assert (addr != NULL);
3563 GNUNET_STATISTICS_update (stats,
3564 gettext_noop ("# peer addresses scheduled for validation"),
3567 tp = find_transport (tname);
3570 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3571 GNUNET_ERROR_TYPE_BULK,
3573 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3575 GNUNET_STATISTICS_update (stats,
3576 gettext_noop ("# peer addresses not validated (plugin not available)"),
3581 /* check if this is one of our own addresses */
3582 oal = tp->addresses;
3585 if ( (oal->addrlen == addrlen) &&
3586 (0 == memcmp (oal->addr,
3590 /* not plausible, this address is equivalent to our own address! */
3591 GNUNET_STATISTICS_update (stats,
3592 gettext_noop ("# peer addresses not validated (loopback)"),
3599 GNUNET_HELLO_get_key (chvc->hello, &pk);
3600 GNUNET_CRYPTO_hash (&pk,
3602 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3605 if (is_blacklisted(&id, tp))
3608 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3609 "Attempted to validate blacklisted peer `%s' using `%s'!\n",
3617 caec.addrlen = addrlen;
3618 caec.session = NULL;
3620 caec.exists = GNUNET_NO;
3621 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3622 &check_address_exists,
3624 if (caec.exists == GNUNET_YES)
3626 /* During validation attempts we will likely trigger the other
3627 peer trying to validate our address which in turn will cause
3628 it to send us its HELLO, so we expect to hit this case rather
3629 frequently. Only print something if we are very verbose. */
3630 #if DEBUG_TRANSPORT > 1
3631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3632 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3633 a2s (tname, addr, addrlen),
3637 GNUNET_STATISTICS_update (stats,
3638 gettext_noop ("# peer addresses not validated (in progress)"),
3643 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
3646 va->transport_name = GNUNET_strdup (tname);
3647 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3649 va->send_time = GNUNET_TIME_absolute_get();
3650 va->addr = (const void*) &va[1];
3651 memcpy (&va[1], addr, addrlen);
3652 va->addrlen = addrlen;
3653 GNUNET_HELLO_get_key (chvc->hello,
3655 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3656 HELLO_VERIFICATION_TIMEOUT,
3657 &timeout_hello_validation,
3659 GNUNET_CONTAINER_multihashmap_put (validation_map,
3662 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3663 setup_peer_check_blacklist (&id, GNUNET_NO,
3664 &transmit_hello_and_ping,
3671 * Check if addresses in validated hello "h" overlap with
3672 * those in "chvc->hello" and validate the rest.
3674 * @param cls closure
3675 * @param peer id of the peer, NULL for last call
3676 * @param h hello message for the peer (can be NULL)
3677 * @param trust amount of trust we have in the peer (not used)
3680 check_hello_validated (void *cls,
3681 const struct GNUNET_PeerIdentity *peer,
3682 const struct GNUNET_HELLO_Message *h,
3685 struct CheckHelloValidatedContext *chvc = cls;
3686 struct GNUNET_HELLO_Message *plain_hello;
3687 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3688 struct GNUNET_PeerIdentity target;
3689 struct NeighbourList *n;
3694 if (GNUNET_NO == chvc->hello_known)
3696 /* notify PEERINFO about the peer now, so that we at least
3697 have the public key if some other component needs it */
3698 GNUNET_HELLO_get_key (chvc->hello, &pk);
3699 GNUNET_CRYPTO_hash (&pk,
3700 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3701 &target.hashPubKey);
3702 plain_hello = GNUNET_HELLO_create (&pk,
3705 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
3706 GNUNET_free (plain_hello);
3707 #if DEBUG_TRANSPORT || 1
3708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3709 "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
3711 GNUNET_i2s (&target));
3713 GNUNET_STATISTICS_update (stats,
3714 gettext_noop ("# new HELLOs requiring full validation"),
3717 GNUNET_HELLO_iterate_addresses (chvc->hello,
3724 GNUNET_STATISTICS_update (stats,
3725 gettext_noop ("# duplicate HELLO (peer known)"),
3729 if (chvc->ve_count == 0)
3731 GNUNET_CONTAINER_DLL_remove (chvc_head,
3741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3742 "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
3746 chvc->hello_known = GNUNET_YES;
3747 n = find_neighbour (peer);
3750 GNUNET_HELLO_iterate_addresses (h,
3752 &add_to_foreign_address_list,
3754 try_transmission_to_peer (n);
3758 GNUNET_STATISTICS_update (stats,
3759 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3763 GNUNET_STATISTICS_update (stats,
3764 gettext_noop ("# HELLO validations (update case)"),
3767 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3769 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3776 * Process HELLO-message.
3778 * @param plugin transport involved, may be NULL
3779 * @param message the actual message
3780 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3783 process_hello (struct TransportPlugin *plugin,
3784 const struct GNUNET_MessageHeader *message)
3787 struct GNUNET_PeerIdentity target;
3788 const struct GNUNET_HELLO_Message *hello;
3789 struct CheckHelloValidatedContext *chvc;
3790 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3792 hsize = ntohs (message->size);
3793 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3794 (hsize < sizeof (struct GNUNET_MessageHeader)))
3797 return GNUNET_SYSERR;
3799 GNUNET_STATISTICS_update (stats,
3800 gettext_noop ("# HELLOs received for validation"),
3803 /* first, check if load is too high */
3804 if (GNUNET_SCHEDULER_get_load (sched,
3805 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3807 GNUNET_STATISTICS_update (stats,
3808 gettext_noop ("# HELLOs ignored due to high load"),
3813 hello = (const struct GNUNET_HELLO_Message *) message;
3814 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3816 GNUNET_break_op (0);
3817 return GNUNET_SYSERR;
3819 GNUNET_CRYPTO_hash (&publicKey,
3820 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3821 &target.hashPubKey);
3822 if (0 == memcmp (&my_identity,
3824 sizeof (struct GNUNET_PeerIdentity)))
3826 GNUNET_STATISTICS_update (stats,
3827 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3833 while (NULL != chvc)
3835 if (GNUNET_HELLO_equals (hello,
3837 GNUNET_TIME_absolute_get ()).value > 0)
3839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3840 "Received duplicate `%s' message for `%4s'; ignored\n",
3842 GNUNET_i2s (&target));
3843 return GNUNET_OK; /* validation already pending */
3845 if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
3846 GNUNET_break (0 != memcmp (hello, chvc->hello,
3847 GNUNET_HELLO_size(hello)));
3851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3852 "Starting validation of `%s' message for `%4s' of size %u\n",
3854 GNUNET_i2s (&target),
3855 GNUNET_HELLO_size(hello));
3857 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3858 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3859 memcpy (&chvc[1], hello, hsize);
3860 GNUNET_CONTAINER_DLL_insert (chvc_head,
3863 /* finally, check if HELLO was previously validated
3864 (continuation will then schedule actual validation) */
3865 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
3868 HELLO_VERIFICATION_TIMEOUT,
3869 &check_hello_validated, chvc);
3875 * The peer specified by the given neighbour has timed-out or a plugin
3876 * has disconnected. We may either need to do nothing (other plugins
3877 * still up), or trigger a full disconnect and clean up. This
3878 * function updates our state and does the necessary notifications.
3879 * Also notifies our clients that the neighbour is now officially
3882 * @param n the neighbour list entry for the peer
3883 * @param check should we just check if all plugins
3884 * disconnected or must we ask all plugins to
3888 disconnect_neighbour (struct NeighbourList *n, int check)
3890 struct ReadyList *rpos;
3891 struct NeighbourList *npos;
3892 struct NeighbourList *nprev;
3893 struct MessageQueue *mq;
3894 struct ForeignAddressList *peer_addresses;
3895 struct ForeignAddressList *peer_pos;
3897 if (GNUNET_YES == check)
3900 while (NULL != rpos)
3902 peer_addresses = rpos->addresses;
3903 while (peer_addresses != NULL)
3905 if (GNUNET_YES == peer_addresses->connected)
3906 return; /* still connected */
3907 peer_addresses = peer_addresses->next;
3913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3914 "Disconnecting from `%4s'\n",
3915 GNUNET_i2s (&n->id));
3917 /* remove n from neighbours list */
3920 while ((npos != NULL) && (npos != n))
3925 GNUNET_assert (npos != NULL);
3927 neighbours = n->next;
3929 nprev->next = n->next;
3931 /* notify all clients about disconnect */
3932 if (GNUNET_YES == n->received_pong)
3933 notify_clients_disconnect (&n->id);
3935 /* clean up all plugins, cancel connections and pending transmissions */
3936 while (NULL != (rpos = n->plugins))
3938 n->plugins = rpos->next;
3939 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3940 while (rpos->addresses != NULL)
3942 peer_pos = rpos->addresses;
3943 rpos->addresses = peer_pos->next;
3944 if (peer_pos->connected == GNUNET_YES)
3945 GNUNET_STATISTICS_update (stats,
3946 gettext_noop ("# connected addresses"),
3949 if (GNUNET_YES == peer_pos->validated)
3950 GNUNET_STATISTICS_update (stats,
3951 gettext_noop ("# peer addresses considered valid"),
3954 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3956 GNUNET_SCHEDULER_cancel (sched,
3957 peer_pos->revalidate_task);
3958 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3960 GNUNET_free(peer_pos);
3965 /* free all messages on the queue */
3966 while (NULL != (mq = n->messages_head))
3968 GNUNET_STATISTICS_update (stats,
3969 gettext_noop ("# bytes in message queue for other peers"),
3970 - (int64_t) mq->message_buf_size,
3972 GNUNET_STATISTICS_update (stats,
3973 gettext_noop ("# bytes discarded due to disconnect"),
3974 mq->message_buf_size,
3976 GNUNET_CONTAINER_DLL_remove (n->messages_head,
3979 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
3981 sizeof(struct GNUNET_PeerIdentity)));
3984 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
3986 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
3987 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3989 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3991 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
3992 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3994 if (n->piter != NULL)
3996 GNUNET_PEERINFO_iterate_cancel (n->piter);
3999 /* finally, free n itself */
4000 GNUNET_STATISTICS_update (stats,
4001 gettext_noop ("# active neighbours"),
4004 GNUNET_free_non_null (n->pre_connect_message_buffer);
4010 * We have received a PING message from someone. Need to send a PONG message
4011 * in response to the peer by any means necessary.
4014 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4015 const struct GNUNET_PeerIdentity *peer,
4016 const char *sender_address,
4017 uint16_t sender_address_len)
4019 struct TransportPlugin *plugin = cls;
4020 struct TransportPingMessage *ping;
4021 struct TransportPongMessage *pong;
4022 struct NeighbourList *n;
4023 struct ReadyList *rl;
4024 struct ForeignAddressList *fal;
4026 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
4028 GNUNET_break_op (0);
4029 return GNUNET_SYSERR;
4032 ping = (struct TransportPingMessage *) message;
4033 if (0 != memcmp (&ping->target,
4034 plugin->env.my_identity,
4035 sizeof (struct GNUNET_PeerIdentity)))
4037 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4038 _("Received `%s' message not destined for me!\n"),
4040 return GNUNET_SYSERR;
4043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4044 "Processing `%s' from `%s'\n",
4046 (sender_address != NULL)
4047 ? a2s (plugin->short_name,
4048 (const struct sockaddr *)sender_address,
4052 GNUNET_STATISTICS_update (stats,
4053 gettext_noop ("# PING messages received"),
4056 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
4057 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
4058 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4059 pong->purpose.size =
4060 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4062 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
4063 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
4064 pong->challenge = ping->challenge;
4065 pong->addrlen = htons(sender_address_len);
4066 memcpy(&pong->signer,
4068 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
4069 if (sender_address != NULL)
4070 memcpy (&pong[1], sender_address, sender_address_len);
4072 GNUNET_assert (GNUNET_OK ==
4073 GNUNET_CRYPTO_rsa_sign (my_private_key,
4074 &pong->purpose, &pong->signature));
4076 n = find_neighbour(peer);
4077 GNUNET_assert (n != NULL);
4078 /* first try reliable response transmission */
4082 fal = rl->addresses;
4085 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4088 ntohs (pong->header.size),
4089 TRANSPORT_PONG_PRIORITY,
4090 HELLO_VERIFICATION_TIMEOUT,
4098 GNUNET_STATISTICS_update (stats,
4099 gettext_noop ("# PONGs unicast via reliable transport"),
4109 /* no reliable method found, do multicast */
4110 GNUNET_STATISTICS_update (stats,
4111 gettext_noop ("# PONGs multicast to all available addresses"),
4117 fal = rl->addresses;
4120 transmit_to_peer(NULL, fal,
4121 TRANSPORT_PONG_PRIORITY,
4122 HELLO_VERIFICATION_TIMEOUT,
4124 ntohs(pong->header.size),
4137 * Function called by the plugin for each received message.
4138 * Update data volumes, possibly notify plugins about
4139 * reducing the rate at which they read from the socket
4140 * and generally forward to our receive callback.
4142 * @param cls the "struct TransportPlugin *" we gave to the plugin
4143 * @param peer (claimed) identity of the other peer
4144 * @param message the message, NULL if we only care about
4145 * learning about the delay until we should receive again
4146 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
4147 * @param session identifier used for this session (can be NULL)
4148 * @param sender_address binary address of the sender (if observed)
4149 * @param sender_address_len number of bytes in sender_address
4150 * @return how long the plugin should wait until receiving more data
4151 * (plugins that do not support this, can ignore the return value)
4153 static struct GNUNET_TIME_Relative
4154 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4155 const struct GNUNET_MessageHeader *message,
4157 struct Session *session,
4158 const char *sender_address,
4159 uint16_t sender_address_len)
4161 struct TransportPlugin *plugin = cls;
4162 struct ReadyList *service_context;
4163 struct ForeignAddressList *peer_address;
4165 struct NeighbourList *n;
4166 struct GNUNET_TIME_Relative ret;
4168 if (is_blacklisted (peer, plugin))
4169 return GNUNET_TIME_UNIT_FOREVER_REL;
4171 n = find_neighbour (peer);
4173 n = setup_new_neighbour (peer, GNUNET_YES);
4174 service_context = n->plugins;
4175 while ((service_context != NULL) && (plugin != service_context->plugin))
4176 service_context = service_context->next;
4177 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4178 peer_address = NULL;
4179 if (message != NULL)
4181 if ( (session != NULL) ||
4182 (sender_address != NULL) )
4183 peer_address = add_peer_address (n,
4187 sender_address_len);
4188 if (peer_address != NULL)
4190 peer_address->distance = distance;
4191 if (GNUNET_YES == peer_address->validated)
4192 mark_address_connected (peer_address);
4193 peer_address->timeout
4195 GNUNET_TIME_relative_to_absolute
4196 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4197 schedule_next_ping (peer_address);
4199 /* update traffic received amount ... */
4200 msize = ntohs (message->size);
4201 GNUNET_STATISTICS_update (stats,
4202 gettext_noop ("# bytes received from other peers"),
4205 n->distance = distance;
4207 GNUNET_TIME_relative_to_absolute
4208 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4209 GNUNET_SCHEDULER_cancel (sched,
4212 GNUNET_SCHEDULER_add_delayed (sched,
4213 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4214 &neighbour_timeout_task, n);
4215 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4217 /* dropping message due to frequent inbound volume violations! */
4218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4219 GNUNET_ERROR_TYPE_BULK,
4221 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4222 n->in_tracker.available_bytes_per_s__,
4223 n->quota_violation_count);
4224 GNUNET_STATISTICS_update (stats,
4225 gettext_noop ("# bandwidth quota violations by other peers"),
4228 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4232 "Received message of type %u from `%4s', sending to all clients.\n",
4233 ntohs (message->type), GNUNET_i2s (peer));
4235 switch (ntohs (message->type))
4237 case GNUNET_MESSAGE_TYPE_HELLO:
4238 GNUNET_STATISTICS_update (stats,
4239 gettext_noop ("# HELLO messages received from other peers"),
4242 process_hello (plugin, message);
4244 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4245 handle_ping (plugin, message, peer, sender_address, sender_address_len);
4247 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4248 handle_pong (plugin, message, peer, sender_address, sender_address_len);
4251 handle_payload_message (message, n);
4255 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4258 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4259 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4260 (unsigned long long) n->in_tracker.consumption_since_last_update__,
4261 (unsigned int) n->in_tracker.available_bytes_per_s__,
4262 (unsigned long long) ret.value);
4263 GNUNET_STATISTICS_update (stats,
4264 gettext_noop ("# ms throttling suggested"),
4265 (int64_t) ret.value,
4272 * Handle START-message. This is the first message sent to us
4273 * by any client which causes us to add it to our list.
4275 * @param cls closure (always NULL)
4276 * @param client identification of the client
4277 * @param message the actual message
4280 handle_start (void *cls,
4281 struct GNUNET_SERVER_Client *client,
4282 const struct GNUNET_MessageHeader *message)
4284 struct TransportClient *c;
4285 struct ConnectInfoMessage cim;
4286 struct NeighbourList *n;
4289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4290 "Received `%s' request from client\n", "START");
4295 if (c->client == client)
4297 /* client already on our list! */
4299 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4304 c = GNUNET_malloc (sizeof (struct TransportClient));
4308 if (our_hello != NULL)
4311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4312 "Sending our own `%s' to new client\n", "HELLO");
4314 transmit_to_client (c,
4315 (const struct GNUNET_MessageHeader *) our_hello,
4317 /* tell new client about all existing connections */
4318 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
4319 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4323 if (GNUNET_YES == n->received_pong)
4326 cim.latency = GNUNET_TIME_relative_hton (n->latency);
4327 cim.distance = htonl (n->distance);
4328 transmit_to_client (c, &cim.header, GNUNET_NO);
4333 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4338 * Handle HELLO-message.
4340 * @param cls closure (always NULL)
4341 * @param client identification of the client
4342 * @param message the actual message
4345 handle_hello (void *cls,
4346 struct GNUNET_SERVER_Client *client,
4347 const struct GNUNET_MessageHeader *message)
4351 GNUNET_STATISTICS_update (stats,
4352 gettext_noop ("# HELLOs received from clients"),
4355 ret = process_hello (NULL, message);
4356 GNUNET_SERVER_receive_done (client, ret);
4361 * Closure for 'transmit_client_message'; followed by
4362 * 'msize' bytes of the actual message.
4364 struct TransmitClientMessageContext
4367 * Client on whom's behalf we are sending.
4369 struct GNUNET_SERVER_Client *client;
4372 * Timeout for the transmission.
4374 struct GNUNET_TIME_Absolute timeout;
4382 * Size of the message in bytes.
4389 * Schedule transmission of a message we got from a client to a peer.
4391 * @param cls the 'struct TransmitClientMessageContext*'
4392 * @param n destination, or NULL on error (in that case, drop the message)
4395 transmit_client_message (void *cls,
4396 struct NeighbourList *n)
4398 struct TransmitClientMessageContext *tcmc = cls;
4399 struct TransportClient *tc;
4402 while ((tc != NULL) && (tc->client != tcmc->client))
4407 transmit_to_peer (tc, NULL, tcmc->priority,
4408 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
4410 tcmc->msize, GNUNET_NO, n);
4412 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
4413 GNUNET_SERVER_client_drop (tcmc->client);
4419 * Handle SEND-message.
4421 * @param cls closure (always NULL)
4422 * @param client identification of the client
4423 * @param message the actual message
4426 handle_send (void *cls,
4427 struct GNUNET_SERVER_Client *client,
4428 const struct GNUNET_MessageHeader *message)
4430 const struct OutboundMessage *obm;
4431 const struct GNUNET_MessageHeader *obmm;
4432 struct TransmitClientMessageContext *tcmc;
4436 size = ntohs (message->size);
4438 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
4441 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4444 GNUNET_STATISTICS_update (stats,
4445 gettext_noop ("# payload received for other peers"),
4448 obm = (const struct OutboundMessage *) message;
4449 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
4450 msize = size - sizeof (struct OutboundMessage);
4452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4453 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
4454 "SEND", GNUNET_i2s (&obm->peer),
4458 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
4459 tcmc->client = client;
4460 tcmc->priority = ntohl (obm->priority);
4461 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
4462 tcmc->msize = msize;
4463 memcpy (&tcmc[1], obmm, msize);
4464 GNUNET_SERVER_client_keep (client);
4465 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
4466 &transmit_client_message,
4472 * Handle SET_QUOTA-message.
4474 * @param cls closure (always NULL)
4475 * @param client identification of the client
4476 * @param message the actual message
4479 handle_set_quota (void *cls,
4480 struct GNUNET_SERVER_Client *client,
4481 const struct GNUNET_MessageHeader *message)
4483 const struct QuotaSetMessage *qsm =
4484 (const struct QuotaSetMessage *) message;
4485 struct NeighbourList *n;
4487 GNUNET_STATISTICS_update (stats,
4488 gettext_noop ("# SET QUOTA messages received"),
4491 n = find_neighbour (&qsm->peer);
4494 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4495 GNUNET_STATISTICS_update (stats,
4496 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
4502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4503 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
4505 (unsigned int) ntohl (qsm->quota.value__),
4506 (unsigned int) n->in_tracker.available_bytes_per_s__,
4507 GNUNET_i2s (&qsm->peer));
4509 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
4511 if (0 == ntohl (qsm->quota.value__))
4512 disconnect_neighbour (n, GNUNET_NO);
4513 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4518 * Take the given address and append it to the set of results send back to
4521 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
4522 * @param address the resolved name, NULL to indicate the last response
4525 transmit_address_to_client (void *cls, const char *address)
4527 struct GNUNET_SERVER_TransmitContext *tc = cls;
4530 if (NULL == address)
4533 slen = strlen (address) + 1;
4534 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
4535 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4536 if (NULL == address)
4537 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
4542 * Handle AddressLookup-message.
4544 * @param cls closure (always NULL)
4545 * @param client identification of the client
4546 * @param message the actual message
4549 handle_address_lookup (void *cls,
4550 struct GNUNET_SERVER_Client *client,
4551 const struct GNUNET_MessageHeader *message)
4553 const struct AddressLookupMessage *alum;
4554 struct TransportPlugin *lsPlugin;
4555 const char *nameTransport;
4556 const char *address;
4558 struct GNUNET_SERVER_TransmitContext *tc;
4559 struct GNUNET_TIME_Absolute timeout;
4560 struct GNUNET_TIME_Relative rtimeout;
4563 size = ntohs (message->size);
4564 if (size < sizeof (struct AddressLookupMessage))
4566 GNUNET_break_op (0);
4567 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4570 alum = (const struct AddressLookupMessage *) message;
4571 uint32_t addressLen = ntohl (alum->addrlen);
4572 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
4574 GNUNET_break_op (0);
4575 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4578 address = (const char *) &alum[1];
4579 nameTransport = (const char *) &address[addressLen];
4581 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
4583 GNUNET_break_op (0);
4584 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4587 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
4588 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
4589 numeric = ntohl (alum->numeric_only);
4590 lsPlugin = find_transport (nameTransport);
4591 if (NULL == lsPlugin)
4593 tc = GNUNET_SERVER_transmit_context_create (client);
4594 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
4595 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4596 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
4599 tc = GNUNET_SERVER_transmit_context_create (client);
4600 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
4602 address, addressLen,
4605 &transmit_address_to_client, tc);
4609 * List of handlers for the messages understood by this
4612 static struct GNUNET_SERVER_MessageHandler handlers[] = {
4613 {&handle_start, NULL,
4614 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
4615 {&handle_hello, NULL,
4616 GNUNET_MESSAGE_TYPE_HELLO, 0},
4617 {&handle_send, NULL,
4618 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
4619 {&handle_set_quota, NULL,
4620 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
4621 {&handle_address_lookup, NULL,
4622 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
4624 {&handle_blacklist_init, NULL,
4625 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
4626 {&handle_blacklist_reply, NULL,
4627 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
4633 * Setup the environment for this plugin.
4636 create_environment (struct TransportPlugin *plug)
4638 plug->env.cfg = cfg;
4639 plug->env.sched = sched;
4640 plug->env.my_identity = &my_identity;
4641 plug->env.cls = plug;
4642 plug->env.receive = &plugin_env_receive;
4643 plug->env.notify_address = &plugin_env_notify_address;
4644 plug->env.session_end = &plugin_env_session_end;
4645 plug->env.max_connections = max_connect_per_transport;
4646 plug->env.stats = stats;
4651 * Start the specified transport (load the plugin).
4654 start_transport (struct GNUNET_SERVER_Handle *server,
4657 struct TransportPlugin *plug;
4660 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4661 _("Loading `%s' transport plugin\n"), name);
4662 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
4663 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
4664 create_environment (plug);
4665 plug->short_name = GNUNET_strdup (name);
4666 plug->lib_name = libname;
4667 plug->next = plugins;
4669 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
4670 if (plug->api == NULL)
4672 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4673 _("Failed to load transport plugin for `%s'\n"), name);
4674 GNUNET_free (plug->short_name);
4675 plugins = plug->next;
4676 GNUNET_free (libname);
4683 * Called whenever a client is disconnected. Frees our
4684 * resources associated with that client.
4686 * @param cls closure
4687 * @param client identification of the client
4690 client_disconnect_notification (void *cls,
4691 struct GNUNET_SERVER_Client *client)
4693 struct TransportClient *pos;
4694 struct TransportClient *prev;
4695 struct ClientMessageQueueEntry *mqe;
4696 struct Blacklisters *bl;
4697 struct BlacklistCheck *bc;
4702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4703 "Client disconnected, cleaning up.\n");
4705 /* clean up blacklister */
4709 if (bl->client == client)
4714 if (bc->bl_pos == bl)
4716 bc->bl_pos = bl->next;
4719 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
4722 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
4723 bc->task = GNUNET_SCHEDULER_add_now (sched,
4724 &do_blacklist_check,
4730 GNUNET_CONTAINER_DLL_remove (bl_head,
4733 GNUNET_SERVER_client_drop (bl->client);
4739 /* clean up 'normal' clients */
4742 while ((pos != NULL) && (pos->client != client))
4749 while (NULL != (mqe = pos->message_queue_head))
4751 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
4752 pos->message_queue_tail,
4754 pos->message_count--;
4758 clients = pos->next;
4760 prev->next = pos->next;
4761 if (GNUNET_YES == pos->tcs_pending)
4766 if (pos->th != NULL)
4768 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
4771 GNUNET_break (0 == pos->message_count);
4777 * Function called when the service shuts down. Unloads our plugins
4778 * and cancels pending validations.
4780 * @param cls closure, unused
4781 * @param tc task context (unused)
4784 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4786 struct TransportPlugin *plug;
4787 struct OwnAddressList *al;
4788 struct CheckHelloValidatedContext *chvc;
4790 while (neighbours != NULL)
4791 disconnect_neighbour (neighbours, GNUNET_NO);
4793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4794 "Transport service is unloading plugins...\n");
4796 while (NULL != (plug = plugins))
4798 plugins = plug->next;
4799 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
4801 GNUNET_SCHEDULER_cancel (plug->env.sched,
4802 plug->address_update_task);
4803 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
4805 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
4806 GNUNET_free (plug->lib_name);
4807 GNUNET_free (plug->short_name);
4808 while (NULL != (al = plug->addresses))
4810 plug->addresses = al->next;
4815 if (my_private_key != NULL)
4816 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4817 GNUNET_free_non_null (our_hello);
4819 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4822 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4823 validation_map = NULL;
4825 /* free 'chvc' data structure */
4826 while (NULL != (chvc = chvc_head))
4828 chvc_head = chvc->next;
4829 if (chvc->piter != NULL)
4830 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
4831 GNUNET_assert (chvc->ve_count == 0);
4838 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4841 if (peerinfo != NULL)
4843 GNUNET_PEERINFO_disconnect (peerinfo);
4846 /* Can we assume those are gone by now, or do we need to clean up
4848 GNUNET_break (bl_head == NULL);
4849 GNUNET_break (bc_head == NULL);
4854 * Initiate transport service.
4856 * @param cls closure
4857 * @param s scheduler to use
4858 * @param serv the initialized server
4859 * @param c configuration to use
4863 struct GNUNET_SCHEDULER_Handle *s,
4864 struct GNUNET_SERVER_Handle *serv,
4865 const struct GNUNET_CONFIGURATION_Handle *c)
4870 unsigned long long tneigh;
4875 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4876 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4877 /* parse configuration */
4879 GNUNET_CONFIGURATION_get_value_number (c,
4884 GNUNET_CONFIGURATION_get_value_filename (c,
4886 "HOSTKEY", &keyfile)))
4888 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4890 ("Transport service is lacking key configuration settings. Exiting.\n"));
4891 GNUNET_SCHEDULER_shutdown (s);
4894 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4897 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4898 validation_map = NULL;
4901 max_connect_per_transport = (uint32_t) tneigh;
4902 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
4903 if (peerinfo == NULL)
4905 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4906 _("Could not access PEERINFO service. Exiting.\n"));
4907 GNUNET_SCHEDULER_shutdown (s);
4910 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4913 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4914 validation_map = NULL;
4915 GNUNET_free (keyfile);
4918 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4919 GNUNET_free (keyfile);
4920 if (my_private_key == NULL)
4922 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4924 ("Transport service could not access hostkey. Exiting.\n"));
4925 GNUNET_SCHEDULER_shutdown (s);
4928 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4931 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4932 validation_map = NULL;
4935 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4936 GNUNET_CRYPTO_hash (&my_public_key,
4937 sizeof (my_public_key), &my_identity.hashPubKey);
4938 /* setup notification */
4940 GNUNET_SERVER_disconnect_notify (server,
4941 &client_disconnect_notification, NULL);
4942 /* load plugins... */
4945 GNUNET_CONFIGURATION_get_value_string (c,
4946 "TRANSPORT", "PLUGINS", &plugs))
4948 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4949 _("Starting transport plugins `%s'\n"), plugs);
4950 pos = strtok (plugs, " ");
4953 start_transport (server, pos);
4955 pos = strtok (NULL, " ");
4957 GNUNET_free (plugs);
4959 GNUNET_SCHEDULER_add_delayed (sched,
4960 GNUNET_TIME_UNIT_FOREVER_REL,
4961 &shutdown_task, NULL);
4966 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
4968 /* If we have a blacklist file, read from it */
4969 read_blacklist_file(cfg);
4970 /* process client requests */
4971 GNUNET_SERVER_add_handlers (server, handlers);
4976 * The main function for the transport service.
4978 * @param argc number of arguments from the command line
4979 * @param argv command line arguments
4980 * @return 0 ok, 1 on error
4983 main (int argc, char *const *argv)
4985 a2s (NULL, NULL, 0); /* make compiler happy */
4986 return (GNUNET_OK ==
4987 GNUNET_SERVICE_run (argc,
4990 GNUNET_SERVICE_OPTION_NONE,
4991 &run, NULL)) ? 0 : 1;
4994 /* end of gnunet-service-transport.c */