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
27 * - This code uses 'GNUNET_a2s' for debug printing in many places,
28 * which is technically wrong since it assumes we have IP+Port
29 * (v4/v6) addresses. Once we add transports like http or smtp
30 * this will have to be changed!
31 * - Already wrong with dv.
34 #include "gnunet_client_lib.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet_constants.h"
37 #include "gnunet_getopt_lib.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_os_lib.h"
40 #include "gnunet_peerinfo_service.h"
41 #include "gnunet_plugin_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_service_lib.h"
44 #include "gnunet_signatures.h"
45 #include "plugin_transport.h"
46 #include "transport.h"
48 #define DEBUG_BLACKLIST GNUNET_NO
50 #define DEBUG_PING_PONG GNUNET_NO
53 * Should we do some additional checks (to validate behavior
56 #define EXTRA_CHECKS GNUNET_YES
59 * How many messages can we have pending for a given client process
60 * before we start to drop incoming messages? We typically should
61 * have only one client and so this would be the primary buffer for
62 * messages, so the number should be chosen rather generously.
64 * The expectation here is that most of the time the queue is large
65 * enough so that a drop is virtually never required.
67 #define MAX_PENDING 128
70 * Size of the per-transport blacklist hash maps.
72 #define TRANSPORT_BLACKLIST_HT_SIZE 16
75 * How often should we try to reconnect to a peer using a particular
76 * transport plugin before giving up? Note that the plugin may be
77 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
79 #define MAX_CONNECT_RETRY 3
82 * Limit on the number of ready-to-run tasks when validating
83 * HELLOs. If more tasks are ready to run, we will drop
84 * HELLOs instead of validating them.
86 #define MAX_HELLO_LOAD 4
89 * How often must a peer violate bandwidth quotas before we start
90 * to simply drop its messages?
92 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
95 * How long until a HELLO verification attempt should time out?
96 * Must be rather small, otherwise a partially successful HELLO
97 * validation (some addresses working) might not be available
98 * before a client's request for a connection fails for good.
99 * Besides, if a single request to an address takes a long time,
100 * then the peer is unlikely worthwhile anyway.
102 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
105 * Priority to use for PONG messages.
107 #define TRANSPORT_PONG_PRIORITY 4
110 * How often do we re-add (cheaper) plugins to our list of plugins
111 * to try for a given connected peer?
113 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
116 * After how long do we expire an address in a HELLO that we just
117 * validated? This value is also used for our own addresses when we
120 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
124 * How long before an existing address expires should we again try to
125 * validate it? Must be (significantly) smaller than
126 * HELLO_ADDRESS_EXPIRATION.
128 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
131 * Maximum frequency for re-evaluating latencies for all transport addresses.
133 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
136 * Maximum frequency for re-evaluating latencies for connected addresses.
138 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
142 * List of addresses of other peers
144 struct ForeignAddressList
147 * This is a linked list.
149 struct ForeignAddressList *next;
152 * Which ready list does this entry belong to.
154 struct ReadyList *ready_list;
157 * How long until we auto-expire this address (unless it is
158 * re-confirmed by the transport)?
160 struct GNUNET_TIME_Absolute expires;
163 * Task used to re-validate addresses, updates latencies and
166 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
179 * Session (or NULL if no valid session currently exists or if the
180 * plugin does not use sessions).
182 struct Session *session;
185 * What was the last latency observed for this address, plugin and peer?
187 struct GNUNET_TIME_Relative latency;
190 * If we did not successfully transmit a message to the given peer
191 * via this connection during the specified time, we should consider
192 * the connection to be dead. This is used in the case that a TCP
193 * transport simply stalls writing to the stream but does not
194 * formerly get a signal that the other peer died.
196 struct GNUNET_TIME_Absolute timeout;
199 * How often have we tried to connect using this plugin? Used to
200 * discriminate against addresses that do not work well.
201 * FIXME: not yet used, but should be!
203 unsigned int connect_attempts;
206 * DV distance to this peer (1 if no DV is used).
207 * FIXME: need to set this from transport plugins!
212 * Have we ever estimated the latency of this address? Used to
213 * ensure that the first time we add an address, we immediately
219 * Are we currently connected via this address? The first time we
220 * successfully transmit or receive data to a peer via a particular
221 * address, we set this to GNUNET_YES. If we later get an error
222 * (disconnect notification, transmission failure, timeout), we set
223 * it back to GNUNET_NO.
228 * Is this plugin currently busy transmitting to the specific target?
229 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
230 * messages do not count as 'in transmit'.
235 * Has this address been validated yet?
243 * Entry in linked list of network addresses for ourselves.
245 struct OwnAddressList
248 * This is a linked list.
250 struct OwnAddressList *next;
253 * The address, actually a pointer to the end
254 * of this struct. Do not free!
259 * How long until we auto-expire this address (unless it is
260 * re-confirmed by the transport)?
262 struct GNUNET_TIME_Absolute expires;
273 * Entry in linked list of all of our plugins.
275 struct TransportPlugin
279 * This is a linked list.
281 struct TransportPlugin *next;
284 * API of the transport as returned by the plugin's
285 * initialization function.
287 struct GNUNET_TRANSPORT_PluginFunctions *api;
290 * Short name for the plugin (i.e. "tcp").
295 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
300 * List of our known addresses for this transport.
302 struct OwnAddressList *addresses;
305 * Environment this transport service is using
308 struct GNUNET_TRANSPORT_PluginEnvironment env;
311 * ID of task that is used to clean up expired addresses.
313 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
316 * Set to GNUNET_YES if we need to scrap the existing list of
317 * "addresses" and start fresh when we receive the next address
318 * update from a transport. Set to GNUNET_NO if we should just add
319 * the new address to the list and wait for the commit call.
324 * Hashmap of blacklisted peers for this particular transport.
326 struct GNUNET_CONTAINER_MultiHashMap *blacklist;
329 struct NeighbourList;
332 * For each neighbour we keep a list of messages
333 * that we still want to transmit to the neighbour.
339 * This is a doubly linked list.
341 struct MessageQueue *next;
344 * This is a doubly linked list.
346 struct MessageQueue *prev;
349 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
350 * stuck together in memory. Allocated at the end of this struct.
352 const char *message_buf;
355 * Size of the message buf
357 size_t message_buf_size;
360 * Client responsible for queueing the message;
361 * used to check that a client has no two messages
362 * pending for the same target. Can be NULL.
364 struct TransportClient *client;
367 * Using which specific address should we send this message?
369 struct ForeignAddressList *specific_address;
372 * Peer ID of the Neighbour this entry belongs to.
374 struct GNUNET_PeerIdentity neighbour_id;
377 * Plugin that we used for the transmission.
378 * NULL until we scheduled a transmission.
380 struct TransportPlugin *plugin;
383 * At what time should we fail?
385 struct GNUNET_TIME_Absolute timeout;
388 * Internal message of the transport system that should not be
389 * included in the usual SEND-SEND_OK transmission confirmation
390 * traffic management scheme. Typically, "internal_msg" will
391 * be set whenever "client" is NULL (but it is not strictly
397 * How important is the message?
399 unsigned int priority;
405 * For a given Neighbour, which plugins are available
406 * to talk to this peer and what are their costs?
411 * This is a linked list.
413 struct ReadyList *next;
416 * Which of our transport plugins does this entry
419 struct TransportPlugin *plugin;
422 * Transport addresses, latency, and readiness for
423 * this particular plugin.
425 struct ForeignAddressList *addresses;
428 * To which neighbour does this ready list belong to?
430 struct NeighbourList *neighbour;
436 * Entry in linked list of all of our current neighbours.
442 * This is a linked list.
444 struct NeighbourList *next;
447 * Which of our transports is connected to this peer
448 * and what is their status?
450 struct ReadyList *plugins;
453 * Head of list of messages we would like to send to this peer;
454 * must contain at most one message per client.
456 struct MessageQueue *messages_head;
459 * Tail of list of messages we would like to send to this peer; must
460 * contain at most one message per client.
462 struct MessageQueue *messages_tail;
465 * Buffer for at most one payload message used when we receive
466 * payload data before our PING-PONG has succeeded. We then
467 * store such messages in this intermediary buffer until the
468 * connection is fully up.
470 struct GNUNET_MessageHeader *pre_connect_message_buffer;
473 * Context for peerinfo iteration.
474 * NULL after we are done processing peerinfo's information.
476 struct GNUNET_PEERINFO_IteratorContext *piter;
479 * Public key for this peer. Valid only if the respective flag is set below.
481 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
484 * Identity of this neighbour.
486 struct GNUNET_PeerIdentity id;
489 * ID of task scheduled to run when this peer is about to
490 * time out (will free resources associated with the peer).
492 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
495 * ID of task scheduled to run when we should retry transmitting
496 * the head of the message queue. Actually triggered when the
497 * transmission is timing out (we trigger instantly when we have
498 * a chance of success).
500 GNUNET_SCHEDULER_TaskIdentifier retry_task;
503 * How long until we should consider this peer dead
504 * (if we don't receive another message in the
507 struct GNUNET_TIME_Absolute peer_timeout;
510 * Tracker for inbound bandwidth.
512 struct GNUNET_BANDWIDTH_Tracker in_tracker;
515 * The latency we have seen for this particular address for
516 * this particular peer. This latency may have been calculated
517 * over multiple transports. This value reflects how long it took
518 * us to receive a response when SENDING via this particular
519 * transport/neighbour/address combination!
521 * FIXME: we need to periodically send PINGs to update this
522 * latency (at least more often than the current "huge" (11h?)
525 struct GNUNET_TIME_Relative latency;
528 * How often has the other peer (recently) violated the
529 * inbound traffic limit? Incremented by 10 per violation,
530 * decremented by 1 per non-violation (for each
533 unsigned int quota_violation_count;
536 * DV distance to this peer (1 if no DV is used).
541 * Have we seen an PONG from this neighbour in the past (and
542 * not had a disconnect since)?
547 * Do we have a valid public key for this neighbour?
549 int public_key_valid;
554 * Message used to ask a peer to validate receipt (to check an address
557 struct TransportPingMessage
561 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
563 struct GNUNET_MessageHeader header;
566 * Random challenge number (in network byte order).
568 uint32_t challenge GNUNET_PACKED;
571 * Who is the intended recipient?
573 struct GNUNET_PeerIdentity target;
579 * Message used to validate a HELLO. The challenge is included in the
580 * confirmation to make matching of replies to requests possible. The
581 * signature signs the original challenge number, our public key, the
582 * sender's address (so that the sender can check that the address we
583 * saw is plausible for him and possibly detect a MiM attack) and a
584 * timestamp (to limit replay).<p>
586 * This message is followed by the address of the
587 * client that we are observing (which is part of what
590 struct TransportPongMessage
594 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
596 struct GNUNET_MessageHeader header;
599 * For padding, always zero.
601 uint32_t reserved GNUNET_PACKED;
606 struct GNUNET_CRYPTO_RsaSignature signature;
609 * What are we signing and why?
611 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
614 * Random challenge number (in network byte order).
616 uint32_t challenge GNUNET_PACKED;
619 * Who signed this message?
621 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
624 * Size of address appended to this message
632 * Linked list of messages to be transmitted to the client. Each
633 * entry is followed by the actual message.
635 struct ClientMessageQueueEntry
638 * This is a doubly-linked list.
640 struct ClientMessageQueueEntry *next;
643 * This is a doubly-linked list.
645 struct ClientMessageQueueEntry *prev;
650 * Client connected to the transport service.
652 struct TransportClient
656 * This is a linked list.
658 struct TransportClient *next;
661 * Handle to the client.
663 struct GNUNET_SERVER_Client *client;
666 * Linked list of messages yet to be transmitted to
669 struct ClientMessageQueueEntry *message_queue_head;
672 * Tail of linked list of messages yet to be transmitted to the
675 struct ClientMessageQueueEntry *message_queue_tail;
678 * Current transmit request handle.
680 struct GNUNET_CONNECTION_TransmitHandle *th;
683 * Is a call to "transmit_send_continuation" pending? If so, we
684 * must not free this struct (even if the corresponding client
685 * disconnects) and instead only remove it from the linked list and
686 * set the "client" field to NULL.
691 * Length of the list of messages pending for this client.
693 unsigned int message_count;
699 * Entry in map of all HELLOs awaiting validation.
701 struct ValidationEntry
705 * The address, actually a pointer to the end
706 * of this struct. Do not free!
711 * Name of the transport.
713 char *transport_name;
716 * The public key of the peer.
718 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
721 * ID of task that will clean up this entry if we don't succeed
722 * with the validation first.
724 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
727 * At what time did we send this validation?
729 struct GNUNET_TIME_Absolute send_time;
732 * Session being validated (or NULL for none).
734 struct Session *session;
742 * Challenge number we used.
750 * Context of currently active requests to peerinfo
751 * for validation of HELLOs.
753 struct CheckHelloValidatedContext
757 * This is a doubly-linked list.
759 struct CheckHelloValidatedContext *next;
762 * This is a doubly-linked list.
764 struct CheckHelloValidatedContext *prev;
767 * Hello that we are validating.
769 const struct GNUNET_HELLO_Message *hello;
772 * Context for peerinfo iteration.
773 * NULL after we are done processing peerinfo's information.
775 struct GNUNET_PEERINFO_IteratorContext *piter;
778 * Was a HELLO known for this peer to peerinfo?
789 static struct GNUNET_HELLO_Message *our_hello;
792 * "version" of "our_hello". Used to see if a given neighbour has
793 * already been sent the latest version of our HELLO message.
795 static unsigned int our_hello_version;
800 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
805 static struct GNUNET_PeerIdentity my_identity;
810 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
815 struct GNUNET_SCHEDULER_Handle *sched;
820 const struct GNUNET_CONFIGURATION_Handle *cfg;
823 * Linked list of all clients to this service.
825 static struct TransportClient *clients;
828 * All loaded plugins.
830 static struct TransportPlugin *plugins;
835 static struct GNUNET_SERVER_Handle *server;
838 * Handle to peerinfo service.
840 static struct GNUNET_PEERINFO_Handle *peerinfo;
843 * All known neighbours and their HELLOs.
845 static struct NeighbourList *neighbours;
848 * Number of neighbours we'd like to have.
850 static uint32_t max_connect_per_transport;
853 * Head of linked list.
855 static struct CheckHelloValidatedContext *chvc_head;
858 * Tail of linked list.
860 static struct CheckHelloValidatedContext *chvc_tail;
863 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
864 * of the given peer that we are currently validating).
866 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
869 * Handle for reporting statistics.
871 static struct GNUNET_STATISTICS_Handle *stats;
875 * The peer specified by the given neighbour has timed-out or a plugin
876 * has disconnected. We may either need to do nothing (other plugins
877 * still up), or trigger a full disconnect and clean up. This
878 * function updates our state and do the necessary notifications.
879 * Also notifies our clients that the neighbour is now officially
882 * @param n the neighbour list entry for the peer
883 * @param check should we just check if all plugins
884 * disconnected or must we ask all plugins to
887 static void disconnect_neighbour (struct NeighbourList *n, int check);
890 * Check the ready list for the given neighbour and if a plugin is
891 * ready for transmission (and if we have a message), do so!
893 * @param neighbour target peer for which to transmit
895 static void try_transmission_to_peer (struct NeighbourList *neighbour);
899 * Find an entry in the neighbour list for a particular peer.
901 * @return NULL if not found.
903 static struct NeighbourList *
904 find_neighbour (const struct GNUNET_PeerIdentity *key)
906 struct NeighbourList *head = neighbours;
908 while ((head != NULL) &&
909 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
916 * Find an entry in the transport list for a particular transport.
918 * @return NULL if not found.
920 static struct TransportPlugin *
921 find_transport (const char *short_name)
923 struct TransportPlugin *head = plugins;
924 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
930 * Is a particular peer blacklisted for a particular transport?
932 * @param peer the peer to check for
933 * @param plugin the plugin used to connect to the peer
935 * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
938 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
941 if (plugin->blacklist != NULL)
943 if (GNUNET_CONTAINER_multihashmap_contains(plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
946 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
947 _("Peer `%s:%s' is blacklisted!\n"),
948 plugin->short_name, GNUNET_i2s (peer));
959 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
961 struct TransportPlugin *plugin;
963 plugin = find_transport(transport_name);
964 if (plugin == NULL) /* Nothing to do */
966 if (plugin->blacklist == NULL)
967 plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
968 GNUNET_assert(plugin->blacklist != NULL);
969 GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
971 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
976 * Read the blacklist file, containing transport:peer entries.
977 * Provided the transport is loaded, set up hashmap with these
978 * entries to blacklist peers by transport.
982 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
989 struct GNUNET_PeerIdentity pid;
991 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
992 unsigned int entries_found;
993 char *transport_name;
996 GNUNET_CONFIGURATION_get_value_filename (cfg,
1001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1002 _("Option `%s' in section `%s' not specified!\n"),
1007 if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1008 GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1009 | GNUNET_DISK_PERM_USER_WRITE);
1010 if (0 != STAT (fn, &frstat))
1012 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1013 _("Could not read blacklist file `%s'\n"), fn);
1017 if (frstat.st_size == 0)
1019 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1020 _("Blacklist file `%s' is empty.\n"),
1025 /* FIXME: use mmap */
1026 data = GNUNET_malloc_large (frstat.st_size);
1027 if (frstat.st_size !=
1028 GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1030 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1031 _("Failed to read blacklist from `%s'\n"), fn);
1038 while ((pos < frstat.st_size) && isspace (data[pos]))
1040 while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1041 (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1044 while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace (data[colon_pos]))
1047 if (colon_pos >= frstat.st_size)
1049 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1050 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1051 (unsigned long long) colon_pos);
1057 if (isspace(data[colon_pos]))
1059 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1060 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1061 (unsigned long long) colon_pos);
1063 while ((pos < frstat.st_size) && isspace (data[pos]))
1067 tsize = colon_pos - pos;
1068 if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size))
1070 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1071 _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1072 (unsigned long long) colon_pos);
1078 transport_name = GNUNET_malloc(tsize);
1079 memcpy(transport_name, &data[pos], tsize);
1080 pos = colon_pos + 1;
1083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084 _("Read transport name %s in blacklist file.\n"),
1087 memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1088 if (!isspace (enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1090 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1091 _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1092 (unsigned long long) pos);
1094 while ((pos < frstat.st_size) && (!isspace (data[pos])))
1096 GNUNET_free_non_null(transport_name);
1099 enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1100 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1102 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1103 _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1104 (unsigned long long) pos,
1109 if (0 != memcmp (&pid,
1111 sizeof (struct GNUNET_PeerIdentity)))
1114 add_peer_to_blacklist (&pid,
1116 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1117 _("Found blacklisted peer `%s:%s' in configuration\n"),
1118 transport_name, GNUNET_i2s (&pid));
1122 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1123 _("Found myself `%s' in blacklist (useless, ignored)\n"),
1127 pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1128 GNUNET_free_non_null(transport_name);
1129 while ((pos < frstat.st_size) && isspace (data[pos]))
1138 * Function called to notify a client about the socket being ready to
1139 * queue more data. "buf" will be NULL and "size" zero if the socket
1140 * was closed for writing in the meantime.
1142 * @param cls closure
1143 * @param size number of bytes available in buf
1144 * @param buf where the callee should write the message
1145 * @return number of bytes written to buf
1148 transmit_to_client_callback (void *cls, size_t size, void *buf)
1150 struct TransportClient *client = cls;
1151 struct ClientMessageQueueEntry *q;
1154 const struct GNUNET_MessageHeader *msg;
1160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1161 "Transmission to client failed, closing connection.\n");
1162 /* fatal error with client, free message queue! */
1163 while (NULL != (q = client->message_queue_head))
1165 GNUNET_STATISTICS_update (stats,
1166 gettext_noop ("# bytes discarded (could not transmit to client)"),
1167 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1169 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1170 client->message_queue_tail,
1174 client->message_count = 0;
1179 while (NULL != (q = client->message_queue_head))
1181 msg = (const struct GNUNET_MessageHeader *) &q[1];
1182 msize = ntohs (msg->size);
1183 if (msize + tsize > size)
1186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187 "Transmitting message of type %u to client.\n",
1190 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1191 client->message_queue_tail,
1193 memcpy (&cbuf[tsize], msg, msize);
1196 client->message_count--;
1200 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1201 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1203 GNUNET_TIME_UNIT_FOREVER_REL,
1204 &transmit_to_client_callback,
1206 GNUNET_assert (client->th != NULL);
1213 * Mark the given FAL entry as 'connected' (and hence preferred for
1214 * sending); also mark all others for the same peer as 'not connected'
1215 * (since only one can be preferred).
1217 * @param fal address to set to 'connected'
1220 mark_address_connected (struct ForeignAddressList *fal)
1222 struct ForeignAddressList *pos;
1225 GNUNET_assert (GNUNET_YES == fal->validated);
1226 if (fal->connected == GNUNET_YES)
1227 return; /* nothing to do */
1229 pos = fal->ready_list->addresses;
1232 if (GNUNET_YES == pos->connected)
1234 GNUNET_break (cnt == GNUNET_YES);
1236 pos->connected = GNUNET_NO;
1240 fal->connected = GNUNET_YES;
1241 if (GNUNET_YES == cnt)
1243 GNUNET_STATISTICS_update (stats,
1244 gettext_noop ("# connected addresses"),
1252 * Send the specified message to the specified client. Since multiple
1253 * messages may be pending for the same client at a time, this code
1254 * makes sure that no message is lost.
1256 * @param client client to transmit the message to
1257 * @param msg the message to send
1258 * @param may_drop can this message be dropped if the
1259 * message queue for this client is getting far too large?
1262 transmit_to_client (struct TransportClient *client,
1263 const struct GNUNET_MessageHeader *msg, int may_drop)
1265 struct ClientMessageQueueEntry *q;
1268 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1270 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1272 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1273 client->message_count, MAX_PENDING);
1274 /* TODO: call to statistics... */
1277 msize = ntohs (msg->size);
1278 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1279 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1280 memcpy (&q[1], msg, msize);
1281 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1282 client->message_queue_tail,
1283 client->message_queue_tail,
1285 client->message_count++;
1286 if (client->th == NULL)
1288 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1290 GNUNET_TIME_UNIT_FOREVER_REL,
1291 &transmit_to_client_callback,
1293 GNUNET_assert (client->th != NULL);
1299 * Transmit a 'SEND_OK' notification to the given client for the
1302 * @param client who to notify
1303 * @param n neighbour to notify about
1304 * @param result status code for the transmission request
1307 transmit_send_ok (struct TransportClient *client,
1308 struct NeighbourList *n,
1311 struct SendOkMessage send_ok_msg;
1313 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1314 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1315 send_ok_msg.success = htonl (result);
1316 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1317 send_ok_msg.peer = n->id;
1318 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1323 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1324 * upon "completion" of a send request. This tells the API
1325 * that it is now legal to send another message to the given
1328 * @param cls closure, identifies the entry on the
1329 * message queue that was transmitted and the
1330 * client responsible for queueing the message
1331 * @param target the peer receiving the message
1332 * @param result GNUNET_OK on success, if the transmission
1333 * failed, we should not tell the client to transmit
1337 transmit_send_continuation (void *cls,
1338 const struct GNUNET_PeerIdentity *target,
1341 struct MessageQueue *mq = cls;
1342 struct NeighbourList *n;
1344 GNUNET_STATISTICS_update (stats,
1345 gettext_noop ("# bytes pending with plugins"),
1346 - (int64_t) mq->message_buf_size,
1348 if (result == GNUNET_OK)
1350 GNUNET_STATISTICS_update (stats,
1351 gettext_noop ("# bytes successfully transmitted by plugins"),
1352 mq->message_buf_size,
1357 GNUNET_STATISTICS_update (stats,
1358 gettext_noop ("# bytes with transmission failure by plugins"),
1359 mq->message_buf_size,
1362 n = find_neighbour(&mq->neighbour_id);
1363 GNUNET_assert (n != NULL);
1364 if (mq->specific_address != NULL)
1366 if (result == GNUNET_OK)
1368 mq->specific_address->timeout =
1369 GNUNET_TIME_relative_to_absolute
1370 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1371 if (mq->specific_address->validated == GNUNET_YES)
1372 mark_address_connected (mq->specific_address);
1376 if (mq->specific_address->connected != GNUNET_NO)
1378 GNUNET_STATISTICS_update (stats,
1379 gettext_noop ("# connected addresses"),
1382 mq->specific_address->connected = GNUNET_NO;
1385 if (! mq->internal_msg)
1386 mq->specific_address->in_transmit = GNUNET_NO;
1388 if (mq->client != NULL)
1389 transmit_send_ok (mq->client, n, result);
1391 try_transmission_to_peer (n);
1396 * Find an address in any of the available transports for
1397 * the given neighbour that would be good for message
1398 * transmission. This is essentially the transport selection
1401 * @param neighbour for whom to select an address
1402 * @return selected address, NULL if we have none
1404 struct ForeignAddressList *
1405 find_ready_address(struct NeighbourList *neighbour)
1407 struct ReadyList *head = neighbour->plugins;
1408 struct ForeignAddressList *addresses;
1409 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1410 struct ForeignAddressList *best_address;
1412 best_address = NULL;
1413 while (head != NULL)
1415 addresses = head->addresses;
1416 while (addresses != NULL)
1418 if ( (addresses->timeout.value < now.value) &&
1419 (addresses->connected == GNUNET_YES) )
1422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1423 "Marking long-time inactive connection to `%4s' as down.\n",
1424 GNUNET_i2s (&neighbour->id));
1426 GNUNET_STATISTICS_update (stats,
1427 gettext_noop ("# connected addresses"),
1430 addresses->connected = GNUNET_NO;
1432 addresses = addresses->next;
1435 addresses = head->addresses;
1436 while (addresses != NULL)
1438 #if DEBUG_TRANSPORT > 1
1439 if (addresses->addr != NULL)
1440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1441 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1442 GNUNET_a2s (addresses->addr,
1443 addresses->addrlen),
1444 GNUNET_i2s (&neighbour->id),
1445 addresses->connected,
1446 addresses->in_transmit,
1447 addresses->validated,
1448 addresses->connect_attempts,
1449 (unsigned long long) addresses->timeout.value,
1450 (unsigned int) addresses->distance);
1452 if ( ( (best_address == NULL) ||
1453 (addresses->connected == GNUNET_YES) ||
1454 (best_address->connected == GNUNET_NO) ) &&
1455 (addresses->in_transmit == GNUNET_NO) &&
1456 ( (best_address == NULL) ||
1457 (addresses->latency.value < best_address->latency.value)) )
1458 best_address = addresses;
1459 /* FIXME: also give lower-latency addresses that are not
1460 connected a chance some times... */
1461 addresses = addresses->next;
1465 if (best_address != NULL)
1468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469 "Best address found has latency of %llu ms.\n",
1470 best_address->latency.value);
1475 GNUNET_STATISTICS_update (stats,
1476 gettext_noop ("# transmission attempts failed (no address)"),
1480 return best_address;
1486 * We should re-try transmitting to the given peer,
1487 * hopefully we've learned something in the meantime.
1490 retry_transmission_task (void *cls,
1491 const struct GNUNET_SCHEDULER_TaskContext *tc)
1493 struct NeighbourList *n = cls;
1495 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1496 try_transmission_to_peer (n);
1501 * Check the ready list for the given neighbour and if a plugin is
1502 * ready for transmission (and if we have a message), do so!
1504 * @param neighbour target peer for which to transmit
1507 try_transmission_to_peer (struct NeighbourList *neighbour)
1509 struct ReadyList *rl;
1510 struct MessageQueue *mq;
1511 struct GNUNET_TIME_Relative timeout;
1515 if (neighbour->messages_head == NULL)
1518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1519 "Transmission queue for `%4s' is empty\n",
1520 GNUNET_i2s (&neighbour->id));
1522 return; /* nothing to do */
1525 mq = neighbour->messages_head;
1526 force_address = GNUNET_YES;
1527 if (mq->specific_address == NULL)
1529 mq->specific_address = find_ready_address(neighbour);
1530 GNUNET_STATISTICS_update (stats,
1531 gettext_noop ("# transport selected peer address freely"),
1534 force_address = GNUNET_NO;
1536 if (mq->specific_address == NULL)
1538 GNUNET_STATISTICS_update (stats,
1539 gettext_noop ("# transport failed to selected peer address"),
1542 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1543 if (timeout.value == 0)
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 "No destination address available to transmit message of size %u to peer `%4s'\n",
1548 mq->message_buf_size,
1549 GNUNET_i2s (&mq->neighbour_id));
1551 GNUNET_STATISTICS_update (stats,
1552 gettext_noop ("# bytes in message queue for other peers"),
1553 - (int64_t) mq->message_buf_size,
1555 GNUNET_STATISTICS_update (stats,
1556 gettext_noop ("# bytes discarded (no destination address available)"),
1557 mq->message_buf_size,
1559 if (mq->client != NULL)
1560 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1561 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1562 neighbour->messages_tail,
1565 return; /* nobody ready */
1567 GNUNET_STATISTICS_update (stats,
1568 gettext_noop ("# message delivery deferred (no address)"),
1571 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1572 GNUNET_SCHEDULER_cancel (sched,
1573 neighbour->retry_task);
1574 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1576 &retry_transmission_task,
1579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1580 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1581 mq->message_buf_size,
1582 GNUNET_i2s (&mq->neighbour_id),
1585 /* FIXME: might want to trigger peerinfo lookup here
1586 (unless that's already pending...) */
1589 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1590 neighbour->messages_tail,
1592 if (mq->specific_address->connected == GNUNET_NO)
1593 mq->specific_address->connect_attempts++;
1594 rl = mq->specific_address->ready_list;
1595 mq->plugin = rl->plugin;
1596 if (!mq->internal_msg)
1597 mq->specific_address->in_transmit = GNUNET_YES;
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1601 mq->message_buf_size,
1602 GNUNET_i2s (&neighbour->id),
1603 (mq->specific_address->addr != NULL)
1604 ? GNUNET_a2s (mq->specific_address->addr,
1605 mq->specific_address->addrlen)
1607 rl->plugin->short_name);
1609 GNUNET_STATISTICS_update (stats,
1610 gettext_noop ("# bytes in message queue for other peers"),
1611 - (int64_t) mq->message_buf_size,
1613 GNUNET_STATISTICS_update (stats,
1614 gettext_noop ("# bytes pending with plugins"),
1615 mq->message_buf_size,
1617 ret = rl->plugin->api->send (rl->plugin->api->cls,
1620 mq->message_buf_size,
1622 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1623 mq->specific_address->session,
1624 mq->specific_address->addr,
1625 mq->specific_address->addrlen,
1627 &transmit_send_continuation, mq);
1630 /* failure, but 'send' would not call continuation in this case,
1631 so we need to do it here! */
1632 transmit_send_continuation (mq,
1640 * Send the specified message to the specified peer.
1642 * @param client source of the transmission request (can be NULL)
1643 * @param peer_address ForeignAddressList where we should send this message
1644 * @param priority how important is the message
1645 * @param timeout how long do we have to transmit?
1646 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1647 * @param message_buf_size total size of all messages in message_buf
1648 * @param is_internal is this an internal message; these are pre-pended and
1649 * also do not count for plugins being "ready" to transmit
1650 * @param neighbour handle to the neighbour for transmission
1653 transmit_to_peer (struct TransportClient *client,
1654 struct ForeignAddressList *peer_address,
1655 unsigned int priority,
1656 struct GNUNET_TIME_Relative timeout,
1657 const char *message_buf,
1658 size_t message_buf_size,
1659 int is_internal, struct NeighbourList *neighbour)
1661 struct MessageQueue *mq;
1666 /* check for duplicate submission */
1667 mq = neighbour->messages_head;
1670 if (mq->client == client)
1672 /* client transmitted to same peer twice
1673 before getting SEND_OK! */
1681 GNUNET_STATISTICS_update (stats,
1682 gettext_noop ("# bytes in message queue for other peers"),
1685 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1686 mq->specific_address = peer_address;
1687 mq->client = client;
1688 memcpy (&mq[1], message_buf, message_buf_size);
1689 mq->message_buf = (const char*) &mq[1];
1690 mq->message_buf_size = message_buf_size;
1691 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1692 mq->internal_msg = is_internal;
1693 mq->priority = priority;
1694 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1696 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1697 neighbour->messages_tail,
1700 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1701 neighbour->messages_tail,
1702 neighbour->messages_tail,
1704 try_transmission_to_peer (neighbour);
1711 struct GeneratorContext
1713 struct TransportPlugin *plug_pos;
1714 struct OwnAddressList *addr_pos;
1715 struct GNUNET_TIME_Absolute expiration;
1723 address_generator (void *cls, size_t max, void *buf)
1725 struct GeneratorContext *gc = cls;
1728 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1730 gc->plug_pos = gc->plug_pos->next;
1731 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1733 if (NULL == gc->plug_pos)
1738 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1741 gc->addr_pos->addrlen, buf, max);
1742 gc->addr_pos = gc->addr_pos->next;
1748 * Construct our HELLO message from all of the addresses of
1749 * all of the transports.
1754 struct GNUNET_HELLO_Message *hello;
1755 struct TransportClient *cpos;
1756 struct NeighbourList *npos;
1757 struct GeneratorContext gc;
1759 gc.plug_pos = plugins;
1760 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1761 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1762 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1765 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1767 GNUNET_STATISTICS_update (stats,
1768 gettext_noop ("# refreshed my HELLO"),
1772 while (cpos != NULL)
1774 transmit_to_client (cpos,
1775 (const struct GNUNET_MessageHeader *) hello,
1780 GNUNET_free_non_null (our_hello);
1782 our_hello_version++;
1783 GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1785 while (npos != NULL)
1788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1789 "Transmitting updated `%s' to neighbour `%4s'\n",
1790 "HELLO", GNUNET_i2s (&npos->id));
1792 GNUNET_STATISTICS_update (stats,
1793 gettext_noop ("# transmitted my HELLO to other peers"),
1796 transmit_to_peer (NULL, NULL, 0,
1797 HELLO_ADDRESS_EXPIRATION,
1798 (const char *) our_hello,
1799 GNUNET_HELLO_size(our_hello),
1807 * Task used to clean up expired addresses for a plugin.
1809 * @param cls closure
1813 expire_address_task (void *cls,
1814 const struct GNUNET_SCHEDULER_TaskContext *tc);
1818 * Update the list of addresses for this plugin,
1819 * expiring those that are past their expiration date.
1821 * @param plugin addresses of which plugin should be recomputed?
1822 * @param fresh set to GNUNET_YES if a new address was added
1823 * and we need to regenerate the HELLO even if nobody
1827 update_addresses (struct TransportPlugin *plugin, int fresh)
1829 static struct GNUNET_TIME_Absolute last_update;
1830 struct GNUNET_TIME_Relative min_remaining;
1831 struct GNUNET_TIME_Relative remaining;
1832 struct GNUNET_TIME_Absolute now;
1833 struct OwnAddressList *pos;
1834 struct OwnAddressList *prev;
1835 struct OwnAddressList *next;
1838 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1839 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1840 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1841 now = GNUNET_TIME_absolute_get ();
1842 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1843 expired = (GNUNET_TIME_absolute_get_duration (last_update).value > (HELLO_ADDRESS_EXPIRATION.value / 4));
1845 pos = plugin->addresses;
1849 if (pos->expires.value < now.value)
1851 expired = GNUNET_YES;
1853 plugin->addresses = pos->next;
1855 prev->next = pos->next;
1860 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1861 if (remaining.value < min_remaining.value)
1862 min_remaining = remaining;
1868 if (expired || fresh)
1873 min_remaining = GNUNET_TIME_relative_min (min_remaining,
1874 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1876 plugin->address_update_task
1877 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1879 &expire_address_task, plugin);
1884 * Task used to clean up expired addresses for a plugin.
1886 * @param cls closure
1890 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1892 struct TransportPlugin *plugin = cls;
1894 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1895 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1896 update_addresses (plugin, GNUNET_NO);
1901 * Iterator over hash map entries that NULLs the session of validation
1902 * entries that match the given session.
1904 * @param cls closure (the 'struct Session*' to match against)
1905 * @param key current key code (peer ID, not used)
1906 * @param value value in the hash map ('struct ValidationEntry*')
1907 * @return GNUNET_YES (we should continue to iterate)
1910 remove_session_validations (void *cls,
1911 const GNUNET_HashCode * key,
1914 struct Session *session = cls;
1915 struct ValidationEntry *ve = value;
1917 if (session == ve->session)
1924 * Function that will be called whenever the plugin internally
1925 * cleans up a session pointer and hence the service needs to
1926 * discard all of those sessions as well. Plugins that do not
1927 * use sessions can simply omit calling this function and always
1928 * use NULL wherever a session pointer is needed.
1930 * @param cls closure
1931 * @param peer which peer was the session for
1932 * @param session which session is being destoyed
1935 plugin_env_session_end (void *cls,
1936 const struct GNUNET_PeerIdentity *peer,
1937 struct Session *session)
1939 struct TransportPlugin *p = cls;
1940 struct NeighbourList *nl;
1941 struct ReadyList *rl;
1942 struct ForeignAddressList *pos;
1943 struct ForeignAddressList *prev;
1945 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
1946 &remove_session_validations,
1948 nl = find_neighbour (peer);
1954 if (rl->plugin == p)
1961 pos = rl->addresses;
1962 while ( (pos != NULL) &&
1963 (pos->session != session) )
1970 pos->session = NULL;
1971 if (pos->addrlen != 0)
1974 rl->addresses = pos->next;
1976 prev->next = pos->next;
1977 if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
1979 GNUNET_SCHEDULER_cancel (sched,
1980 pos->revalidate_task);
1981 pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
1984 if (nl->received_pong == GNUNET_NO)
1985 return; /* nothing to do */
1986 /* check if we have any validated addresses left */
1987 pos = rl->addresses;
1994 /* no valid addresses left, signal disconnect! */
1995 disconnect_neighbour (nl, GNUNET_NO);
2000 * Function that must be called by each plugin to notify the
2001 * transport service about the addresses under which the transport
2002 * provided by the plugin can be reached.
2004 * @param cls closure
2005 * @param name name of the transport that generated the address
2006 * @param addr one of the addresses of the host, NULL for the last address
2007 * the specific address format depends on the transport
2008 * @param addrlen length of the address
2009 * @param expires when should this address automatically expire?
2012 plugin_env_notify_address (void *cls,
2016 struct GNUNET_TIME_Relative expires)
2018 struct TransportPlugin *p = cls;
2019 struct OwnAddressList *al;
2020 struct GNUNET_TIME_Absolute abex;
2022 GNUNET_assert (addr != NULL);
2023 abex = GNUNET_TIME_relative_to_absolute (expires);
2024 GNUNET_assert (p == find_transport (name));
2028 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2030 if (al->expires.value < abex.value)
2037 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2039 al->next = p->addresses;
2042 al->addrlen = addrlen;
2043 memcpy (&al[1], addr, addrlen);
2044 update_addresses (p, GNUNET_YES);
2049 * Notify all of our clients about a peer connecting.
2052 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2053 struct GNUNET_TIME_Relative latency,
2056 struct ConnectInfoMessage cim;
2057 struct TransportClient *cpos;
2060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061 "Notifying clients about connection from `%s'\n",
2064 GNUNET_STATISTICS_update (stats,
2065 gettext_noop ("# peers connected"),
2068 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2069 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2070 cim.distance = htonl (distance);
2071 cim.latency = GNUNET_TIME_relative_hton (latency);
2072 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
2074 while (cpos != NULL)
2076 transmit_to_client (cpos, &cim.header, GNUNET_NO);
2083 * Notify all of our clients about a peer disconnecting.
2086 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2088 struct DisconnectInfoMessage dim;
2089 struct TransportClient *cpos;
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 "Notifying clients about lost connection to `%s'\n",
2096 GNUNET_STATISTICS_update (stats,
2097 gettext_noop ("# peers connected"),
2100 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2101 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2102 dim.reserved = htonl (0);
2103 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2105 while (cpos != NULL)
2107 transmit_to_client (cpos, &dim.header, GNUNET_NO);
2114 * Find a ForeignAddressList entry for the given neighbour
2115 * that matches the given address and transport.
2117 * @param neighbour which peer we care about
2118 * @param tname name of the transport plugin
2119 * @param session session to look for, NULL for 'any'; otherwise
2120 * can be used for the service to "learn" this session ID
2122 * @param addr binary address
2123 * @param addrlen length of addr
2124 * @return NULL if no such entry exists
2126 static struct ForeignAddressList *
2127 find_peer_address(struct NeighbourList *neighbour,
2129 struct Session *session,
2133 struct ReadyList *head;
2134 struct ForeignAddressList *pos;
2136 head = neighbour->plugins;
2137 while (head != NULL)
2139 if (0 == strcmp (tname, head->plugin->short_name))
2145 pos = head->addresses;
2146 while ( (pos != NULL) &&
2147 ( (pos->addrlen != addrlen) ||
2148 (memcmp(pos->addr, addr, addrlen) != 0) ) )
2150 if ( (session != NULL) &&
2151 (pos->session == session) )
2155 if ( (session != NULL) && (pos != NULL) )
2156 pos->session = session; /* learn it! */
2162 * Get the peer address struct for the given neighbour and
2163 * address. If it doesn't yet exist, create it.
2165 * @param neighbour which peer we care about
2166 * @param tname name of the transport plugin
2167 * @param session session of the plugin, or NULL for none
2168 * @param addr binary address
2169 * @param addrlen length of addr
2170 * @return NULL if we do not have a transport plugin for 'tname'
2172 static struct ForeignAddressList *
2173 add_peer_address (struct NeighbourList *neighbour,
2175 struct Session *session,
2179 struct ReadyList *head;
2180 struct ForeignAddressList *ret;
2182 ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2185 head = neighbour->plugins;
2187 while (head != NULL)
2189 if (0 == strcmp (tname, head->plugin->short_name))
2195 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2196 ret->session = session;
2199 ret->addr = (const char*) &ret[1];
2200 memcpy (&ret[1], addr, addrlen);
2206 ret->addrlen = addrlen;
2207 ret->expires = GNUNET_TIME_relative_to_absolute
2208 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2209 ret->latency = GNUNET_TIME_relative_get_forever();
2211 ret->timeout = GNUNET_TIME_relative_to_absolute
2212 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2213 ret->ready_list = head;
2214 ret->next = head->addresses;
2215 head->addresses = ret;
2221 * Closure for 'add_validated_address'.
2223 struct AddValidatedAddressContext
2226 * Entry that has been validated.
2228 const struct ValidationEntry *ve;
2231 * Flag set after we have added the address so
2232 * that we terminate the iteration next time.
2239 * Callback function used to fill a buffer of max bytes with a list of
2240 * addresses in the format used by HELLOs. Should use
2241 * "GNUNET_HELLO_add_address" as a helper function.
2243 * @param cls the 'struct AddValidatedAddressContext' with the validated address
2244 * @param max maximum number of bytes that can be written to buf
2245 * @param buf where to write the address information
2246 * @return number of bytes written, 0 to signal the
2247 * end of the iteration.
2250 add_validated_address (void *cls,
2251 size_t max, void *buf)
2253 struct AddValidatedAddressContext *avac = cls;
2254 const struct ValidationEntry *ve = avac->ve;
2256 if (GNUNET_YES == avac->done)
2258 avac->done = GNUNET_YES;
2259 return GNUNET_HELLO_add_address (ve->transport_name,
2260 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2270 * Closure for 'check_address_exists'.
2272 struct CheckAddressExistsClosure
2275 * Address to check for.
2280 * Name of the transport.
2287 struct Session *session;
2295 * Set to GNUNET_YES if the address exists.
2302 * Iterator over hash map entries. Checks if the given
2303 * validation entry is for the same address as what is given
2306 * @param cls the 'struct CheckAddressExistsClosure*'
2307 * @param key current key code (ignored)
2308 * @param value value in the hash map ('struct ValidationEntry')
2309 * @return GNUNET_YES if we should continue to
2310 * iterate (mismatch), GNUNET_NO if not (entry matched)
2313 check_address_exists (void *cls,
2314 const GNUNET_HashCode * key,
2317 struct CheckAddressExistsClosure *caec = cls;
2318 struct ValidationEntry *ve = value;
2320 if ( (0 == strcmp (caec->tname,
2321 ve->transport_name)) &&
2322 (caec->addrlen == ve->addrlen) &&
2323 (0 == memcmp (caec->addr,
2327 caec->exists = GNUNET_YES;
2330 if ( (ve->session != NULL) &&
2331 (caec->session == ve->session) )
2333 caec->exists = GNUNET_YES;
2341 * HELLO validation cleanup task (validation failed).
2343 * @param cls the 'struct ValidationEntry' that failed
2344 * @param tc scheduler context (unused)
2347 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2349 struct ValidationEntry *va = cls;
2350 struct GNUNET_PeerIdentity pid;
2352 GNUNET_STATISTICS_update (stats,
2353 gettext_noop ("# address validation timeouts"),
2356 GNUNET_CRYPTO_hash (&va->publicKey,
2358 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2360 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2363 GNUNET_free (va->transport_name);
2369 neighbour_timeout_task (void *cls,
2370 const struct GNUNET_SCHEDULER_TaskContext *tc)
2372 struct NeighbourList *n = cls;
2375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2376 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2378 GNUNET_STATISTICS_update (stats,
2379 gettext_noop ("# disconnects due to timeout"),
2382 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2383 disconnect_neighbour (n, GNUNET_NO);
2388 * Schedule the job that will cause us to send a PING to the
2389 * foreign address to evaluate its validity and latency.
2391 * @param fal address to PING
2394 schedule_next_ping (struct ForeignAddressList *fal);
2398 * Add the given address to the list of foreign addresses
2399 * available for the given peer (check for duplicates).
2401 * @param cls the respective 'struct NeighbourList' to update
2402 * @param tname name of the transport
2403 * @param expiration expiration time
2404 * @param addr the address
2405 * @param addrlen length of the address
2406 * @return GNUNET_OK (always)
2409 add_to_foreign_address_list (void *cls,
2411 struct GNUNET_TIME_Absolute expiration,
2412 const void *addr, size_t addrlen)
2414 struct NeighbourList *n = cls;
2415 struct ForeignAddressList *fal;
2418 GNUNET_STATISTICS_update (stats,
2419 gettext_noop ("# valid peer addresses returned by peerinfo"),
2423 fal = find_peer_address (n, tname, NULL, addr, addrlen);
2427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2429 GNUNET_a2s (addr, addrlen),
2431 GNUNET_i2s (&n->id),
2434 fal = add_peer_address (n, tname, NULL, addr, addrlen);
2437 GNUNET_STATISTICS_update (stats,
2438 gettext_noop ("# previously validated addresses lacking transport"),
2444 fal->expires = GNUNET_TIME_absolute_max (expiration,
2446 schedule_next_ping (fal);
2452 fal->expires = GNUNET_TIME_absolute_max (expiration,
2457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458 "Failed to add new address for `%4s'\n",
2459 GNUNET_i2s (&n->id));
2462 if (fal->validated == GNUNET_NO)
2464 fal->validated = GNUNET_YES;
2465 GNUNET_STATISTICS_update (stats,
2466 gettext_noop ("# peer addresses considered valid"),
2470 if (try == GNUNET_YES)
2472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2473 "Have new addresses, will try to trigger transmissions.\n");
2474 try_transmission_to_peer (n);
2481 * Add addresses in validated HELLO "h" to the set of addresses
2482 * we have for this peer.
2484 * @param cls closure ('struct NeighbourList*')
2485 * @param peer id of the peer, NULL for last call
2486 * @param h hello message for the peer (can be NULL)
2487 * @param trust amount of trust we have in the peer (not used)
2490 add_hello_for_peer (void *cls,
2491 const struct GNUNET_PeerIdentity *peer,
2492 const struct GNUNET_HELLO_Message *h,
2495 struct NeighbourList *n = cls;
2503 return; /* no HELLO available */
2505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2506 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2510 if (GNUNET_YES != n->public_key_valid)
2512 GNUNET_HELLO_get_key (h, &n->publicKey);
2513 n->public_key_valid = GNUNET_YES;
2515 GNUNET_HELLO_iterate_addresses (h,
2517 &add_to_foreign_address_list,
2523 * Create a fresh entry in our neighbour list for the given peer.
2524 * Will try to transmit our current HELLO to the new neighbour.
2525 * Do not call this function directly, use 'setup_peer_check_blacklist.
2527 * @param peer the peer for which we create the entry
2528 * @param do_hello should we schedule transmitting a HELLO
2529 * @return the new neighbour list entry
2531 static struct NeighbourList *
2532 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2535 struct NeighbourList *n;
2536 struct TransportPlugin *tp;
2537 struct ReadyList *rl;
2539 GNUNET_assert (our_hello != NULL);
2540 GNUNET_STATISTICS_update (stats,
2541 gettext_noop ("# active neighbours"),
2544 n = GNUNET_malloc (sizeof (struct NeighbourList));
2545 n->next = neighbours;
2549 GNUNET_TIME_relative_to_absolute
2550 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2551 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2552 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2553 MAX_BANDWIDTH_CARRY_S);
2557 if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2559 rl = GNUNET_malloc (sizeof (struct ReadyList));
2561 rl->next = n->plugins;
2564 rl->addresses = NULL;
2568 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2570 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2571 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2572 &neighbour_timeout_task, n);
2575 n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2576 0, GNUNET_TIME_UNIT_FOREVER_REL,
2577 &add_hello_for_peer, n);
2578 transmit_to_peer (NULL, NULL, 0,
2579 HELLO_ADDRESS_EXPIRATION,
2580 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2588 * Function called after we have checked if communicating
2589 * with a given peer is acceptable.
2591 * @param cls closure
2592 * @param n NULL if communication is not acceptable
2594 typedef void (*SetupContinuation)(void *cls,
2595 struct NeighbourList *n);
2599 * Information kept for each client registered to perform
2605 * This is a linked list.
2607 struct Blacklisters *next;
2610 * This is a linked list.
2612 struct Blacklisters *prev;
2615 * Client responsible for this entry.
2617 struct GNUNET_SERVER_Client *client;
2620 * Blacklist check that we're currently performing.
2622 struct BlacklistCheck *bc;
2628 * Head of DLL of blacklisting clients.
2630 static struct Blacklisters *bl_head;
2633 * Tail of DLL of blacklisting clients.
2635 static struct Blacklisters *bl_tail;
2639 * Context we use when performing a blacklist check.
2641 struct BlacklistCheck
2645 * This is a linked list.
2647 struct BlacklistCheck *next;
2650 * This is a linked list.
2652 struct BlacklistCheck *prev;
2655 * Peer being checked.
2657 struct GNUNET_PeerIdentity peer;
2660 * Option for setup neighbour afterwards.
2665 * Continuation to call with the result.
2667 SetupContinuation cont;
2675 * Current transmission request handle for this client, or NULL if no
2676 * request is pending.
2678 struct GNUNET_CONNECTION_TransmitHandle *th;
2681 * Our current position in the blacklisters list.
2683 struct Blacklisters *bl_pos;
2686 * Current task performing the check.
2688 GNUNET_SCHEDULER_TaskIdentifier task;
2693 * Head of DLL of active blacklisting queries.
2695 static struct BlacklistCheck *bc_head;
2698 * Tail of DLL of active blacklisting queries.
2700 static struct BlacklistCheck *bc_tail;
2704 * Perform next action in the blacklist check.
2706 * @param cls the 'struct BlacklistCheck*'
2710 do_blacklist_check (void *cls,
2711 const struct GNUNET_SCHEDULER_TaskContext *tc);
2715 * Transmit blacklist query to the client.
2717 * @param cls the 'struct BlacklistCheck'
2718 * @param size number of bytes allowed
2719 * @param buf where to copy the message
2720 * @return number of bytes copied to buf
2723 transmit_blacklist_message (void *cls,
2727 struct BlacklistCheck *bc = cls;
2728 struct Blacklisters *bl;
2729 struct BlacklistMessage bm;
2734 GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2735 bc->task = GNUNET_SCHEDULER_add_now (sched,
2736 &do_blacklist_check,
2741 bm.header.size = htons (sizeof (struct BlacklistMessage));
2742 bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
2743 bm.is_allowed = htonl (0);
2745 memcpy (buf, &bm, sizeof (bm));
2746 GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
2752 * Perform next action in the blacklist check.
2754 * @param cls the 'struct BlacklistCheck*'
2758 do_blacklist_check (void *cls,
2759 const struct GNUNET_SCHEDULER_TaskContext *tc)
2761 struct BlacklistCheck *bc = cls;
2762 struct Blacklisters *bl;
2764 bc->task = GNUNET_SCHEDULER_NO_TASK;
2768 bc->cont (bc->cont_cls,
2769 setup_new_neighbour (&bc->peer, bc->do_hello));
2776 bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
2777 sizeof (struct BlacklistMessage),
2778 GNUNET_TIME_UNIT_FOREVER_REL,
2779 &transmit_blacklist_message,
2786 * Obtain a 'struct NeighbourList' for the given peer. If such an entry
2787 * does not yet exist, check the blacklist. If the blacklist says creating
2788 * one is acceptable, create one and call the continuation; otherwise
2789 * call the continuation with NULL.
2791 * @param peer peer to setup or look up a struct NeighbourList for
2792 * @param do_hello should we also schedule sending our HELLO to the peer
2793 * if this is a new record
2794 * @param cont function to call with the 'struct NeigbhbourList*'
2795 * @param cont_cls closure for cont
2798 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
2800 SetupContinuation cont,
2803 struct NeighbourList *n;
2804 struct BlacklistCheck *bc;
2806 n = find_neighbour(peer);
2812 if (bl_head == NULL)
2815 setup_new_neighbour (peer, do_hello));
2818 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2819 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2821 bc->do_hello = do_hello;
2823 bc->cont_cls = cont_cls;
2824 bc->bl_pos = bl_head;
2825 bc->task = GNUNET_SCHEDULER_add_now (sched,
2826 &do_blacklist_check,
2832 * Function called with the result of querying a new blacklister about
2833 * it being allowed (or not) to continue to talk to an existing neighbour.
2835 * @param cls the original 'struct NeighbourList'
2836 * @param n NULL if we need to disconnect
2839 confirm_or_drop_neighbour (void *cls,
2840 struct NeighbourList *n)
2842 struct NeighbourList * orig = cls;
2845 disconnect_neighbour (orig, GNUNET_NO);
2850 * Handle a request to start a blacklist.
2852 * @param cls closure (always NULL)
2853 * @param client identification of the client
2854 * @param message the actual message
2857 handle_blacklist_init (void *cls,
2858 struct GNUNET_SERVER_Client *client,
2859 const struct GNUNET_MessageHeader *message)
2861 struct Blacklisters *bl;
2862 struct BlacklistCheck *bc;
2863 struct NeighbourList *n;
2868 if (bl->client == client)
2871 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2876 bl = GNUNET_malloc (sizeof (struct Blacklisters));
2877 bl->client = client;
2878 GNUNET_SERVER_client_keep (client);
2879 GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
2880 /* confirm that all existing connections are OK! */
2884 bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2885 GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2887 bc->do_hello = GNUNET_NO;
2888 bc->cont = &confirm_or_drop_neighbour;
2891 if (n == neighbours) /* all would wait for the same client, no need to
2892 create more than just the first task right now */
2893 bc->task = GNUNET_SCHEDULER_add_now (sched,
2894 &do_blacklist_check,
2902 * Handle a request to blacklist a peer.
2904 * @param cls closure (always NULL)
2905 * @param client identification of the client
2906 * @param message the actual message
2909 handle_blacklist_reply (void *cls,
2910 struct GNUNET_SERVER_Client *client,
2911 const struct GNUNET_MessageHeader *message)
2913 const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
2914 struct Blacklisters *bl;
2915 struct BlacklistCheck *bc;
2918 while ( (bl != NULL) &&
2919 (bl->client != client) )
2923 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2928 if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
2930 bc->cont (bc->cont_cls, NULL);
2931 GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
2936 bc->bl_pos = bc->bl_pos->next;
2937 bc->task = GNUNET_SCHEDULER_add_now (sched,
2938 &do_blacklist_check,
2941 /* check if any other bc's are waiting for this blacklister */
2945 if ( (bc->bl_pos == bl) &&
2946 (GNUNET_SCHEDULER_NO_TASK == bc->task) )
2947 bc->task = GNUNET_SCHEDULER_add_now (sched,
2948 &do_blacklist_check,
2956 * Send periodic PING messages to a give foreign address.
2958 * @param cls our 'struct PeriodicValidationContext*'
2959 * @param tc task context
2962 send_periodic_ping (void *cls,
2963 const struct GNUNET_SCHEDULER_TaskContext *tc)
2965 struct ForeignAddressList *peer_address = cls;
2966 struct TransportPlugin *tp;
2967 struct ValidationEntry *va;
2968 struct NeighbourList *neighbour;
2969 struct TransportPingMessage ping;
2970 struct CheckAddressExistsClosure caec;
2972 uint16_t hello_size;
2975 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2976 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2978 tp = peer_address->ready_list->plugin;
2979 neighbour = peer_address->ready_list->neighbour;
2980 if (GNUNET_YES != neighbour->public_key_valid)
2982 /* no public key yet, try again later */
2983 schedule_next_ping (peer_address);
2986 caec.addr = peer_address->addr;
2987 caec.addrlen = peer_address->addrlen;
2988 caec.tname = tp->short_name;
2989 caec.session = peer_address->session;
2990 caec.exists = GNUNET_NO;
2991 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2992 &check_address_exists,
2994 if (caec.exists == GNUNET_YES)
2996 /* During validation attempts we will likely trigger the other
2997 peer trying to validate our address which in turn will cause
2998 it to send us its HELLO, so we expect to hit this case rather
2999 frequently. Only print something if we are very verbose. */
3000 #if DEBUG_TRANSPORT > 1
3001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3002 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3003 (peer_address->addr != NULL)
3004 ? GNUNET_a2s (peer_address->addr,
3005 peer_address->addrlen)
3008 GNUNET_i2s (&neighbour->id));
3010 schedule_next_ping (peer_address);
3013 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3014 va->transport_name = GNUNET_strdup (tp->short_name);
3015 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3017 va->send_time = GNUNET_TIME_absolute_get();
3018 va->session = peer_address->session;
3019 if (peer_address->addr != NULL)
3021 va->addr = (const void*) &va[1];
3022 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3023 va->addrlen = peer_address->addrlen;
3025 memcpy(&va->publicKey,
3026 &neighbour->publicKey,
3027 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3029 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3030 HELLO_VERIFICATION_TIMEOUT,
3031 &timeout_hello_validation,
3033 GNUNET_CONTAINER_multihashmap_put (validation_map,
3034 &neighbour->id.hashPubKey,
3036 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3037 hello_size = GNUNET_HELLO_size(our_hello);
3038 tsize = sizeof(struct TransportPingMessage) + hello_size;
3039 message_buf = GNUNET_malloc(tsize);
3040 ping.challenge = htonl(va->challenge);
3041 ping.header.size = htons(sizeof(struct TransportPingMessage));
3042 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3043 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3044 memcpy(message_buf, our_hello, hello_size);
3045 memcpy(&message_buf[hello_size],
3047 sizeof(struct TransportPingMessage));
3048 #if DEBUG_TRANSPORT_REVALIDATION
3049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3050 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3051 (peer_address->addr != NULL)
3052 ? GNUNET_a2s (peer_address->addr,
3053 peer_address->addrlen)
3056 GNUNET_i2s (&neighbour->id),
3057 "HELLO", hello_size,
3058 "PING", sizeof (struct TransportPingMessage));
3060 GNUNET_STATISTICS_update (stats,
3061 gettext_noop ("# PING messages sent for re-validation"),
3064 transmit_to_peer (NULL, peer_address,
3065 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3066 HELLO_VERIFICATION_TIMEOUT,
3068 GNUNET_YES, neighbour);
3069 GNUNET_free(message_buf);
3070 schedule_next_ping (peer_address);
3075 * Schedule the job that will cause us to send a PING to the
3076 * foreign address to evaluate its validity and latency.
3078 * @param fal address to PING
3081 schedule_next_ping (struct ForeignAddressList *fal)
3083 struct GNUNET_TIME_Relative delay;
3085 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3087 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3088 delay.value /= 2; /* do before expiration */
3089 delay = GNUNET_TIME_relative_min (delay,
3090 LATENCY_EVALUATION_MAX_DELAY);
3091 if (GNUNET_YES != fal->estimated)
3093 delay = GNUNET_TIME_UNIT_ZERO;
3094 fal->estimated = GNUNET_YES;
3096 if (GNUNET_YES == fal->connected)
3098 delay = GNUNET_TIME_relative_min (delay,
3099 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3101 /* FIXME: also adjust delay based on how close the last
3102 observed latency is to the latency of the best alternative */
3103 /* bound how fast we can go */
3104 delay = GNUNET_TIME_relative_max (delay,
3105 GNUNET_TIME_UNIT_SECONDS);
3106 /* randomize a bit (to avoid doing all at the same time) */
3107 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3108 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
3110 &send_periodic_ping,
3118 * Function that will be called if we receive some payload
3119 * from another peer.
3121 * @param message the payload
3122 * @param n peer who claimed to be the sender
3125 handle_payload_message (const struct GNUNET_MessageHeader *message,
3126 struct NeighbourList *n)
3128 struct InboundMessage *im;
3129 struct TransportClient *cpos;
3132 msize = ntohs (message->size);
3133 if (n->received_pong == GNUNET_NO)
3135 GNUNET_free_non_null (n->pre_connect_message_buffer);
3136 n->pre_connect_message_buffer = GNUNET_malloc (msize);
3137 memcpy (n->pre_connect_message_buffer, message, msize);
3141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3142 "Received message of type %u from `%4s', sending to all clients.\n",
3143 ntohs (message->type),
3144 GNUNET_i2s (&n->id));
3146 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3149 n->quota_violation_count++;
3151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3152 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3153 n->in_tracker.available_bytes_per_s__,
3154 n->quota_violation_count);
3156 /* Discount 32k per violation */
3157 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3162 if (n->quota_violation_count > 0)
3164 /* try to add 32k back */
3165 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3167 n->quota_violation_count--;
3170 GNUNET_STATISTICS_update (stats,
3171 gettext_noop ("# payload received from other peers"),
3174 /* transmit message to all clients */
3175 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3176 im->header.size = htons (sizeof (struct InboundMessage) + msize);
3177 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3178 im->latency = GNUNET_TIME_relative_hton (n->latency);
3180 memcpy (&im[1], message, msize);
3182 while (cpos != NULL)
3184 transmit_to_client (cpos, &im->header, GNUNET_YES);
3192 * Iterator over hash map entries. Checks if the given validation
3193 * entry is for the same challenge as what is given in the PONG.
3195 * @param cls the 'struct TransportPongMessage*'
3196 * @param key peer identity
3197 * @param value value in the hash map ('struct ValidationEntry')
3198 * @return GNUNET_YES if we should continue to
3199 * iterate (mismatch), GNUNET_NO if not (entry matched)
3202 check_pending_validation (void *cls,
3203 const GNUNET_HashCode * key,
3206 const struct TransportPongMessage *pong = cls;
3207 struct ValidationEntry *ve = value;
3208 struct AddValidatedAddressContext avac;
3209 unsigned int challenge = ntohl(pong->challenge);
3210 struct GNUNET_HELLO_Message *hello;
3211 struct GNUNET_PeerIdentity target;
3212 struct NeighbourList *n;
3213 struct ForeignAddressList *fal;
3214 struct GNUNET_MessageHeader *prem;
3216 if (ve->challenge != challenge)
3219 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING,
3224 GNUNET_break_op (0);
3229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3230 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3233 ? GNUNET_a2s ((const struct sockaddr *) ve->addr,
3236 ve->transport_name);
3238 GNUNET_STATISTICS_update (stats,
3239 gettext_noop ("# address validation successes"),
3242 /* create the updated HELLO */
3243 GNUNET_CRYPTO_hash (&ve->publicKey,
3244 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3245 &target.hashPubKey);
3246 if (ve->addr != NULL)
3248 avac.done = GNUNET_NO;
3250 hello = GNUNET_HELLO_create (&ve->publicKey,
3251 &add_validated_address,
3253 GNUNET_PEERINFO_add_peer (peerinfo,
3255 GNUNET_free (hello);
3257 n = find_neighbour (&target);
3260 n->publicKey = ve->publicKey;
3261 n->public_key_valid = GNUNET_YES;
3262 fal = add_peer_address (n,
3267 GNUNET_assert (fal != NULL);
3268 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3269 fal->validated = GNUNET_YES;
3270 mark_address_connected (fal);
3271 GNUNET_STATISTICS_update (stats,
3272 gettext_noop ("# peer addresses considered valid"),
3275 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3276 schedule_next_ping (fal);
3277 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
3278 n->latency = fal->latency;
3280 n->latency.value = (fal->latency.value + n->latency.value) / 2;
3281 n->distance = fal->distance;
3282 if (GNUNET_NO == n->received_pong)
3284 n->received_pong = GNUNET_YES;
3285 notify_clients_connect (&target, n->latency, n->distance);
3286 if (NULL != (prem = n->pre_connect_message_buffer))
3288 n->pre_connect_message_buffer = NULL;
3289 handle_payload_message (prem, n);
3293 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3295 GNUNET_SCHEDULER_cancel (sched,
3297 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3298 try_transmission_to_peer (n);
3302 /* clean up validation entry */
3303 GNUNET_assert (GNUNET_YES ==
3304 GNUNET_CONTAINER_multihashmap_remove (validation_map,
3307 GNUNET_SCHEDULER_cancel (sched,
3309 GNUNET_free (ve->transport_name);
3316 * Function that will be called if we receive a validation
3317 * of an address challenge that we transmitted to another
3318 * peer. Note that the validation should only be considered
3319 * acceptable if the challenge matches AND if the sender
3320 * address is at least a plausible address for this peer
3321 * (otherwise we may be seeing a MiM attack).
3323 * @param cls closure
3324 * @param message the pong message
3325 * @param peer who responded to our challenge
3326 * @param sender_address string describing our sender address (as observed
3327 * by the other peer in binary format)
3328 * @param sender_address_len number of bytes in 'sender_address'
3331 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3332 const struct GNUNET_PeerIdentity *peer,
3333 const char *sender_address,
3334 size_t sender_address_len)
3336 #if DEBUG_TRANSPORT > 1
3337 /* we get tons of these that just get discarded, only log
3338 if we are quite verbose */
3339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340 "Receiving `%s' message from `%4s'.\n", "PONG",
3343 GNUNET_STATISTICS_update (stats,
3344 gettext_noop ("# PONG messages received"),
3347 if (GNUNET_SYSERR !=
3348 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3350 &check_pending_validation,
3353 /* This is *expected* to happen a lot since we send
3354 PONGs to *all* known addresses of the sender of
3355 the PING, so most likely we get multiple PONGs
3356 per PING, and all but the first PONG will end up
3357 here. So really we should not print anything here
3358 unless we want to be very, very verbose... */
3359 #if DEBUG_TRANSPORT > 2
3360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3361 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3370 /* FIXME: add given address to potential pool of our addresses
3372 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
3373 _("Another peer saw us using the address `%s' via `%s'.\n"),
3374 GNUNET_a2s ((const struct sockaddr *) &pong[1],
3375 ntohs(pong->addrlen)),
3376 va->transport_name);
3382 * Try to validate a neighbour's address by sending him our HELLO and a PING.
3384 * @param cls the 'struct ValidationEntry*'
3385 * @param neighbour neighbour to validate, NULL if validation failed
3388 transmit_hello_and_ping (void *cls,
3389 struct NeighbourList *neighbour)
3391 struct ValidationEntry *va = cls;
3392 struct ForeignAddressList *peer_address;
3393 struct TransportPingMessage ping;
3394 uint16_t hello_size;
3398 if (neighbour == NULL)
3400 /* FIXME: stats... */
3401 GNUNET_free (va->transport_name);
3405 neighbour->publicKey = va->publicKey;
3406 neighbour->public_key_valid = GNUNET_YES;
3407 peer_address = add_peer_address (neighbour,
3408 va->transport_name, NULL,
3409 (const void*) &va[1],
3411 if (peer_address == NULL)
3413 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3414 "Failed to add peer `%4s' for plugin `%s'\n",
3415 GNUNET_i2s (&neighbour->id),
3416 va->transport_name);
3417 GNUNET_free (va->transport_name);
3421 hello_size = GNUNET_HELLO_size(our_hello);
3422 tsize = sizeof(struct TransportPingMessage) + hello_size;
3423 message_buf = GNUNET_malloc(tsize);
3424 ping.challenge = htonl(va->challenge);
3425 ping.header.size = htons(sizeof(struct TransportPingMessage));
3426 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3427 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3428 memcpy(message_buf, our_hello, hello_size);
3429 memcpy(&message_buf[hello_size],
3431 sizeof(struct TransportPingMessage));
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3434 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3435 GNUNET_a2s ((const void*) &va[1], va->addrlen),
3437 GNUNET_i2s (&neighbour->id),
3438 "HELLO", hello_size,
3439 "PING", sizeof (struct TransportPingMessage));
3441 GNUNET_STATISTICS_update (stats,
3442 gettext_noop ("# PING messages sent for initial validation"),
3445 transmit_to_peer (NULL, peer_address,
3446 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3447 HELLO_VERIFICATION_TIMEOUT,
3449 GNUNET_YES, neighbour);
3450 GNUNET_free(message_buf);
3455 * Check if the given address is already being validated; if not,
3456 * append the given address to the list of entries that are being be
3457 * validated and initiate validation.
3459 * @param cls closure ('struct CheckHelloValidatedContext *')
3460 * @param tname name of the transport
3461 * @param expiration expiration time
3462 * @param addr the address
3463 * @param addrlen length of the address
3464 * @return GNUNET_OK (always)
3467 run_validation (void *cls,
3469 struct GNUNET_TIME_Absolute expiration,
3470 const void *addr, size_t addrlen)
3472 struct CheckHelloValidatedContext *chvc = cls;
3473 struct GNUNET_PeerIdentity id;
3474 struct TransportPlugin *tp;
3475 struct ValidationEntry *va;
3476 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3477 struct CheckAddressExistsClosure caec;
3479 GNUNET_assert (addr != NULL);
3480 GNUNET_STATISTICS_update (stats,
3481 gettext_noop ("# peer addresses scheduled for validation"),
3484 tp = find_transport (tname);
3487 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3488 GNUNET_ERROR_TYPE_BULK,
3490 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3492 GNUNET_STATISTICS_update (stats,
3493 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
3498 GNUNET_HELLO_get_key (chvc->hello, &pk);
3499 GNUNET_CRYPTO_hash (&pk,
3501 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3504 if (is_blacklisted(&id, tp))
3507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3508 _("Attempted to validate blacklisted peer `%s' using `%s'!\n"), GNUNET_i2s(&id), tname);
3514 caec.addrlen = addrlen;
3515 caec.session = NULL;
3517 caec.exists = GNUNET_NO;
3518 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3519 &check_address_exists,
3521 if (caec.exists == GNUNET_YES)
3523 /* During validation attempts we will likely trigger the other
3524 peer trying to validate our address which in turn will cause
3525 it to send us its HELLO, so we expect to hit this case rather
3526 frequently. Only print something if we are very verbose. */
3527 #if DEBUG_TRANSPORT > 1
3528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3529 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3530 GNUNET_a2s (addr, addrlen),
3534 GNUNET_STATISTICS_update (stats,
3535 gettext_noop ("# peer addresses not validated (in progress)"),
3540 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
3541 va->transport_name = GNUNET_strdup (tname);
3542 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3544 va->send_time = GNUNET_TIME_absolute_get();
3545 va->addr = (const void*) &va[1];
3546 memcpy (&va[1], addr, addrlen);
3547 va->addrlen = addrlen;
3548 GNUNET_HELLO_get_key (chvc->hello,
3550 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3551 HELLO_VERIFICATION_TIMEOUT,
3552 &timeout_hello_validation,
3554 GNUNET_CONTAINER_multihashmap_put (validation_map,
3557 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3558 setup_peer_check_blacklist (&id, GNUNET_NO,
3559 &transmit_hello_and_ping,
3566 * Check if addresses in validated hello "h" overlap with
3567 * those in "chvc->hello" and validate the rest.
3569 * @param cls closure
3570 * @param peer id of the peer, NULL for last call
3571 * @param h hello message for the peer (can be NULL)
3572 * @param trust amount of trust we have in the peer (not used)
3575 check_hello_validated (void *cls,
3576 const struct GNUNET_PeerIdentity *peer,
3577 const struct GNUNET_HELLO_Message *h,
3580 struct CheckHelloValidatedContext *chvc = cls;
3581 struct GNUNET_HELLO_Message *plain_hello;
3582 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3583 struct GNUNET_PeerIdentity target;
3584 struct NeighbourList *n;
3589 GNUNET_CONTAINER_DLL_remove (chvc_head,
3592 if (GNUNET_NO == chvc->hello_known)
3594 /* notify PEERINFO about the peer now, so that we at least
3595 have the public key if some other component needs it */
3596 GNUNET_HELLO_get_key (chvc->hello, &pk);
3597 GNUNET_CRYPTO_hash (&pk,
3598 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3599 &target.hashPubKey);
3600 plain_hello = GNUNET_HELLO_create (&pk,
3603 GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
3604 GNUNET_free (plain_hello);
3606 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3607 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
3609 GNUNET_i2s (&target));
3611 GNUNET_STATISTICS_update (stats,
3612 gettext_noop ("# new HELLOs requiring full validation"),
3615 GNUNET_HELLO_iterate_addresses (chvc->hello,
3622 GNUNET_STATISTICS_update (stats,
3623 gettext_noop ("# duplicate HELLO (peer known)"),
3633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3634 "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
3638 chvc->hello_known = GNUNET_YES;
3639 n = find_neighbour (peer);
3642 GNUNET_HELLO_iterate_addresses (h,
3644 &add_to_foreign_address_list,
3646 try_transmission_to_peer (n);
3650 GNUNET_STATISTICS_update (stats,
3651 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3655 GNUNET_STATISTICS_update (stats,
3656 gettext_noop ("# HELLO validations (update case)"),
3659 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3661 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3668 * Process HELLO-message.
3670 * @param plugin transport involved, may be NULL
3671 * @param message the actual message
3672 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3675 process_hello (struct TransportPlugin *plugin,
3676 const struct GNUNET_MessageHeader *message)
3679 struct GNUNET_PeerIdentity target;
3680 const struct GNUNET_HELLO_Message *hello;
3681 struct CheckHelloValidatedContext *chvc;
3682 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3684 hsize = ntohs (message->size);
3685 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3686 (hsize < sizeof (struct GNUNET_MessageHeader)))
3689 return GNUNET_SYSERR;
3691 GNUNET_STATISTICS_update (stats,
3692 gettext_noop ("# HELLOs received for validation"),
3695 /* first, check if load is too high */
3696 if (GNUNET_SCHEDULER_get_load (sched,
3697 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3699 GNUNET_STATISTICS_update (stats,
3700 gettext_noop ("# HELLOs ignored due to high load"),
3705 hello = (const struct GNUNET_HELLO_Message *) message;
3706 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3708 GNUNET_break_op (0);
3709 return GNUNET_SYSERR;
3711 GNUNET_CRYPTO_hash (&publicKey,
3712 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3713 &target.hashPubKey);
3714 if (0 == memcmp (&my_identity,
3716 sizeof (struct GNUNET_PeerIdentity)))
3718 GNUNET_STATISTICS_update (stats,
3719 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3724 #if DEBUG_TRANSPORT > 1
3725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3726 "Processing `%s' message for `%4s' of size %u\n",
3728 GNUNET_i2s (&target),
3729 GNUNET_HELLO_size(hello));
3731 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3732 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3733 memcpy (&chvc[1], hello, hsize);
3734 GNUNET_CONTAINER_DLL_insert (chvc_head,
3737 /* finally, check if HELLO was previously validated
3738 (continuation will then schedule actual validation) */
3739 chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
3742 HELLO_VERIFICATION_TIMEOUT,
3743 &check_hello_validated, chvc);
3749 * The peer specified by the given neighbour has timed-out or a plugin
3750 * has disconnected. We may either need to do nothing (other plugins
3751 * still up), or trigger a full disconnect and clean up. This
3752 * function updates our state and does the necessary notifications.
3753 * Also notifies our clients that the neighbour is now officially
3756 * @param n the neighbour list entry for the peer
3757 * @param check should we just check if all plugins
3758 * disconnected or must we ask all plugins to
3762 disconnect_neighbour (struct NeighbourList *n, int check)
3764 struct ReadyList *rpos;
3765 struct NeighbourList *npos;
3766 struct NeighbourList *nprev;
3767 struct MessageQueue *mq;
3768 struct ForeignAddressList *peer_addresses;
3769 struct ForeignAddressList *peer_pos;
3771 if (GNUNET_YES == check)
3774 while (NULL != rpos)
3776 peer_addresses = rpos->addresses;
3777 while (peer_addresses != NULL)
3779 if (GNUNET_YES == peer_addresses->connected)
3780 return; /* still connected */
3781 peer_addresses = peer_addresses->next;
3787 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3788 "Disconnecting from `%4s'\n",
3789 GNUNET_i2s (&n->id));
3791 /* remove n from neighbours list */
3794 while ((npos != NULL) && (npos != n))
3799 GNUNET_assert (npos != NULL);
3801 neighbours = n->next;
3803 nprev->next = n->next;
3805 /* notify all clients about disconnect */
3806 if (GNUNET_YES == n->received_pong)
3807 notify_clients_disconnect (&n->id);
3809 /* clean up all plugins, cancel connections and pending transmissions */
3810 while (NULL != (rpos = n->plugins))
3812 n->plugins = rpos->next;
3813 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3814 while (rpos->addresses != NULL)
3816 peer_pos = rpos->addresses;
3817 rpos->addresses = peer_pos->next;
3818 if (peer_pos->connected == GNUNET_YES)
3819 GNUNET_STATISTICS_update (stats,
3820 gettext_noop ("# connected addresses"),
3823 if (GNUNET_YES == peer_pos->validated)
3824 GNUNET_STATISTICS_update (stats,
3825 gettext_noop ("# peer addresses considered valid"),
3828 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3830 GNUNET_SCHEDULER_cancel (sched,
3831 peer_pos->revalidate_task);
3832 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3834 GNUNET_free(peer_pos);
3839 /* free all messages on the queue */
3840 while (NULL != (mq = n->messages_head))
3842 GNUNET_STATISTICS_update (stats,
3843 gettext_noop ("# bytes in message queue for other peers"),
3844 - (int64_t) mq->message_buf_size,
3846 GNUNET_STATISTICS_update (stats,
3847 gettext_noop ("# bytes discarded due to disconnect"),
3848 mq->message_buf_size,
3850 GNUNET_CONTAINER_DLL_remove (n->messages_head,
3853 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
3855 sizeof(struct GNUNET_PeerIdentity)));
3858 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
3860 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
3861 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3863 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3865 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
3866 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3868 if (n->piter != NULL)
3870 GNUNET_PEERINFO_iterate_cancel (n->piter);
3873 /* finally, free n itself */
3874 GNUNET_STATISTICS_update (stats,
3875 gettext_noop ("# active neighbours"),
3878 GNUNET_free_non_null (n->pre_connect_message_buffer);
3884 * We have received a PING message from someone. Need to send a PONG message
3885 * in response to the peer by any means necessary.
3888 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
3889 const struct GNUNET_PeerIdentity *peer,
3890 const char *sender_address,
3891 size_t sender_address_len)
3893 struct TransportPlugin *plugin = cls;
3894 struct TransportPingMessage *ping;
3895 struct TransportPongMessage *pong;
3896 struct NeighbourList *n;
3897 struct ReadyList *rl;
3898 struct ForeignAddressList *fal;
3900 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
3902 GNUNET_break_op (0);
3903 return GNUNET_SYSERR;
3906 ping = (struct TransportPingMessage *) message;
3907 if (0 != memcmp (&ping->target,
3908 plugin->env.my_identity,
3909 sizeof (struct GNUNET_PeerIdentity)))
3911 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3912 _("Received `%s' message not destined for me!\n"),
3914 return GNUNET_SYSERR;
3917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3918 "Processing `%s' from `%s'\n",
3920 (sender_address != NULL)
3921 ? GNUNET_a2s ((const struct sockaddr *)sender_address,
3925 GNUNET_STATISTICS_update (stats,
3926 gettext_noop ("# PING messages received"),
3929 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
3930 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
3931 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
3932 pong->purpose.size =
3933 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3935 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
3936 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
3937 pong->challenge = ping->challenge;
3938 pong->addrlen = htons(sender_address_len);
3939 memcpy(&pong->signer,
3941 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3942 if (sender_address != NULL)
3943 memcpy (&pong[1], sender_address, sender_address_len);
3944 GNUNET_assert (GNUNET_OK ==
3945 GNUNET_CRYPTO_rsa_sign (my_private_key,
3946 &pong->purpose, &pong->signature));
3947 n = find_neighbour(peer);
3948 GNUNET_assert (n != NULL);
3949 /* first try reliable response transmission */
3953 fal = rl->addresses;
3956 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3959 ntohs (pong->header.size),
3960 TRANSPORT_PONG_PRIORITY,
3961 HELLO_VERIFICATION_TIMEOUT,
3969 GNUNET_STATISTICS_update (stats,
3970 gettext_noop ("# PONGs unicast via reliable transport"),
3980 /* no reliable method found, do multicast */
3981 GNUNET_STATISTICS_update (stats,
3982 gettext_noop ("# PONGs multicast to all available addresses"),
3988 fal = rl->addresses;
3991 transmit_to_peer(NULL, fal,
3992 TRANSPORT_PONG_PRIORITY,
3993 HELLO_VERIFICATION_TIMEOUT,
3995 ntohs(pong->header.size),
4008 * Function called by the plugin for each received message.
4009 * Update data volumes, possibly notify plugins about
4010 * reducing the rate at which they read from the socket
4011 * and generally forward to our receive callback.
4013 * @param cls the "struct TransportPlugin *" we gave to the plugin
4014 * @param peer (claimed) identity of the other peer
4015 * @param message the message, NULL if we only care about
4016 * learning about the delay until we should receive again
4017 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
4018 * @param session identifier used for this session (can be NULL)
4019 * @param sender_address binary address of the sender (if observed)
4020 * @param sender_address_len number of bytes in sender_address
4021 * @return how long the plugin should wait until receiving more data
4022 * (plugins that do not support this, can ignore the return value)
4024 static struct GNUNET_TIME_Relative
4025 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4026 const struct GNUNET_MessageHeader *message,
4027 unsigned int distance,
4028 struct Session *session,
4029 const char *sender_address,
4030 size_t sender_address_len)
4032 struct TransportPlugin *plugin = cls;
4033 struct ReadyList *service_context;
4034 struct ForeignAddressList *peer_address;
4036 struct NeighbourList *n;
4037 struct GNUNET_TIME_Relative ret;
4039 if (is_blacklisted (peer, plugin))
4040 return GNUNET_TIME_UNIT_FOREVER_REL;
4042 n = find_neighbour (peer);
4044 n = setup_new_neighbour (peer, GNUNET_YES);
4045 service_context = n->plugins;
4046 while ((service_context != NULL) && (plugin != service_context->plugin))
4047 service_context = service_context->next;
4048 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4049 peer_address = NULL;
4050 if (message != NULL)
4052 if ( (session != NULL) ||
4053 (sender_address != NULL) )
4054 peer_address = add_peer_address (n,
4058 sender_address_len);
4059 if (peer_address != NULL)
4061 peer_address->distance = distance;
4062 if (GNUNET_YES == peer_address->validated)
4063 mark_address_connected (peer_address);
4064 peer_address->timeout
4066 GNUNET_TIME_relative_to_absolute
4067 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4068 schedule_next_ping (peer_address);
4070 /* update traffic received amount ... */
4071 msize = ntohs (message->size);
4072 GNUNET_STATISTICS_update (stats,
4073 gettext_noop ("# bytes received from other peers"),
4076 n->distance = distance;
4078 GNUNET_TIME_relative_to_absolute
4079 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4080 GNUNET_SCHEDULER_cancel (sched,
4083 GNUNET_SCHEDULER_add_delayed (sched,
4084 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4085 &neighbour_timeout_task, n);
4086 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4088 /* dropping message due to frequent inbound volume violations! */
4089 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4090 GNUNET_ERROR_TYPE_BULK,
4092 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4093 n->in_tracker.available_bytes_per_s__,
4094 n->quota_violation_count);
4095 GNUNET_STATISTICS_update (stats,
4096 gettext_noop ("# bandwidth quota violations by other peers"),
4099 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4102 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4103 "Received message of type %u from `%4s', sending to all clients.\n",
4104 ntohs (message->type), GNUNET_i2s (peer));
4106 switch (ntohs (message->type))
4108 case GNUNET_MESSAGE_TYPE_HELLO:
4109 GNUNET_STATISTICS_update (stats,
4110 gettext_noop ("# HELLO messages received from other peers"),
4113 process_hello (plugin, message);
4115 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4116 handle_ping (plugin, message, peer, sender_address, sender_address_len);
4118 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4119 handle_pong (plugin, message, peer, sender_address, sender_address_len);
4122 handle_payload_message (message, n);
4126 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4129 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4130 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4131 (unsigned long long) n->in_tracker.consumption_since_last_update__,
4132 (unsigned int) n->in_tracker.available_bytes_per_s__,
4133 (unsigned long long) ret.value);
4134 GNUNET_STATISTICS_update (stats,
4135 gettext_noop ("# ms throttling suggested"),
4136 (int64_t) ret.value,
4143 * Handle START-message. This is the first message sent to us
4144 * by any client which causes us to add it to our list.
4146 * @param cls closure (always NULL)
4147 * @param client identification of the client
4148 * @param message the actual message
4151 handle_start (void *cls,
4152 struct GNUNET_SERVER_Client *client,
4153 const struct GNUNET_MessageHeader *message)
4155 struct TransportClient *c;
4156 struct ConnectInfoMessage cim;
4157 struct NeighbourList *n;
4160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4161 "Received `%s' request from client\n", "START");
4166 if (c->client == client)
4168 /* client already on our list! */
4170 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4175 c = GNUNET_malloc (sizeof (struct TransportClient));
4179 if (our_hello != NULL)
4182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4183 "Sending our own `%s' to new client\n", "HELLO");
4185 transmit_to_client (c,
4186 (const struct GNUNET_MessageHeader *) our_hello,
4188 /* tell new client about all existing connections */
4189 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
4190 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4194 if (GNUNET_YES == n->received_pong)
4197 cim.latency = GNUNET_TIME_relative_hton (n->latency);
4198 cim.distance = htonl (n->distance);
4199 transmit_to_client (c, &cim.header, GNUNET_NO);
4204 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4209 * Handle HELLO-message.
4211 * @param cls closure (always NULL)
4212 * @param client identification of the client
4213 * @param message the actual message
4216 handle_hello (void *cls,
4217 struct GNUNET_SERVER_Client *client,
4218 const struct GNUNET_MessageHeader *message)
4222 GNUNET_STATISTICS_update (stats,
4223 gettext_noop ("# HELLOs received from clients"),
4226 ret = process_hello (NULL, message);
4227 GNUNET_SERVER_receive_done (client, ret);
4232 * Closure for 'transmit_client_message'; followed by
4233 * 'msize' bytes of the actual message.
4235 struct TransmitClientMessageContext
4238 * Client on whom's behalf we are sending.
4240 struct GNUNET_SERVER_Client *client;
4243 * Timeout for the transmission.
4245 struct GNUNET_TIME_Absolute timeout;
4253 * Size of the message in bytes.
4260 * Schedule transmission of a message we got from a client to a peer.
4262 * @param cls the 'struct TransmitClientMessageContext*'
4263 * @param n destination, or NULL on error (in that case, drop the message)
4266 transmit_client_message (void *cls,
4267 struct NeighbourList *n)
4269 struct TransmitClientMessageContext *tcmc = cls;
4270 struct TransportClient *tc;
4273 while ((tc != NULL) && (tc->client != tcmc->client))
4278 transmit_to_peer (tc, NULL, tcmc->priority,
4279 GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
4281 tcmc->msize, GNUNET_NO, n);
4283 GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
4284 GNUNET_SERVER_client_drop (tcmc->client);
4290 * Handle SEND-message.
4292 * @param cls closure (always NULL)
4293 * @param client identification of the client
4294 * @param message the actual message
4297 handle_send (void *cls,
4298 struct GNUNET_SERVER_Client *client,
4299 const struct GNUNET_MessageHeader *message)
4301 const struct OutboundMessage *obm;
4302 const struct GNUNET_MessageHeader *obmm;
4303 struct TransmitClientMessageContext *tcmc;
4307 size = ntohs (message->size);
4309 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
4312 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4315 GNUNET_STATISTICS_update (stats,
4316 gettext_noop ("# payload received for other peers"),
4319 obm = (const struct OutboundMessage *) message;
4320 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
4321 msize = ntohs (obmm->size);
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4324 "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
4325 "SEND", GNUNET_i2s (&obm->peer),
4329 if (size != msize + sizeof (struct OutboundMessage))
4332 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4335 tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
4336 tcmc->client = client;
4337 tcmc->priority = ntohl (obm->priority);
4338 tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
4339 tcmc->msize = msize;
4340 memcpy (&tcmc[1], obmm, msize);
4341 GNUNET_SERVER_client_keep (client);
4342 setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
4343 &transmit_client_message,
4349 * Handle SET_QUOTA-message.
4351 * @param cls closure (always NULL)
4352 * @param client identification of the client
4353 * @param message the actual message
4356 handle_set_quota (void *cls,
4357 struct GNUNET_SERVER_Client *client,
4358 const struct GNUNET_MessageHeader *message)
4360 const struct QuotaSetMessage *qsm =
4361 (const struct QuotaSetMessage *) message;
4362 struct NeighbourList *n;
4364 GNUNET_STATISTICS_update (stats,
4365 gettext_noop ("# SET QUOTA messages received"),
4368 n = find_neighbour (&qsm->peer);
4371 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4372 GNUNET_STATISTICS_update (stats,
4373 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
4379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4380 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
4382 (unsigned int) ntohl (qsm->quota.value__),
4383 (unsigned int) n->in_tracker.available_bytes_per_s__,
4384 GNUNET_i2s (&qsm->peer));
4386 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
4388 if (0 == ntohl (qsm->quota.value__))
4389 disconnect_neighbour (n, GNUNET_NO);
4390 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4395 * Take the given address and append it to the set of results send back to
4398 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
4399 * @param address the resolved name, NULL to indicate the last response
4402 transmit_address_to_client (void *cls, const char *address)
4404 struct GNUNET_SERVER_TransmitContext *tc = cls;
4407 if (NULL == address)
4410 slen = strlen (address) + 1;
4411 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
4412 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4413 if (NULL == address)
4414 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
4419 * Handle AddressLookup-message.
4421 * @param cls closure (always NULL)
4422 * @param client identification of the client
4423 * @param message the actual message
4426 handle_address_lookup (void *cls,
4427 struct GNUNET_SERVER_Client *client,
4428 const struct GNUNET_MessageHeader *message)
4430 const struct AddressLookupMessage *alum;
4431 struct TransportPlugin *lsPlugin;
4432 const char *nameTransport;
4433 const char *address;
4435 struct GNUNET_SERVER_TransmitContext *tc;
4436 struct GNUNET_TIME_Absolute timeout;
4437 struct GNUNET_TIME_Relative rtimeout;
4440 size = ntohs (message->size);
4441 if (size < sizeof (struct AddressLookupMessage))
4443 GNUNET_break_op (0);
4444 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4447 alum = (const struct AddressLookupMessage *) message;
4448 uint32_t addressLen = ntohl (alum->addrlen);
4449 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
4451 GNUNET_break_op (0);
4452 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4455 address = (const char *) &alum[1];
4456 nameTransport = (const char *) &address[addressLen];
4458 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
4460 GNUNET_break_op (0);
4461 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4464 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
4465 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
4466 numeric = ntohl (alum->numeric_only);
4467 lsPlugin = find_transport (nameTransport);
4468 if (NULL == lsPlugin)
4470 tc = GNUNET_SERVER_transmit_context_create (client);
4471 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
4472 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4473 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
4476 tc = GNUNET_SERVER_transmit_context_create (client);
4477 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
4479 address, addressLen,
4482 &transmit_address_to_client, tc);
4486 * List of handlers for the messages understood by this
4489 static struct GNUNET_SERVER_MessageHandler handlers[] = {
4490 {&handle_start, NULL,
4491 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
4492 {&handle_hello, NULL,
4493 GNUNET_MESSAGE_TYPE_HELLO, 0},
4494 {&handle_send, NULL,
4495 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
4496 {&handle_set_quota, NULL,
4497 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
4498 {&handle_address_lookup, NULL,
4499 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
4501 {&handle_blacklist_init, NULL,
4502 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
4503 {&handle_blacklist_reply, NULL,
4504 GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
4510 * Setup the environment for this plugin.
4513 create_environment (struct TransportPlugin *plug)
4515 plug->env.cfg = cfg;
4516 plug->env.sched = sched;
4517 plug->env.my_identity = &my_identity;
4518 plug->env.cls = plug;
4519 plug->env.receive = &plugin_env_receive;
4520 plug->env.notify_address = &plugin_env_notify_address;
4521 plug->env.session_end = &plugin_env_session_end;
4522 plug->env.max_connections = max_connect_per_transport;
4523 plug->env.stats = stats;
4528 * Start the specified transport (load the plugin).
4531 start_transport (struct GNUNET_SERVER_Handle *server,
4534 struct TransportPlugin *plug;
4537 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4538 _("Loading `%s' transport plugin\n"), name);
4539 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
4540 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
4541 create_environment (plug);
4542 plug->short_name = GNUNET_strdup (name);
4543 plug->lib_name = libname;
4544 plug->next = plugins;
4546 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
4547 if (plug->api == NULL)
4549 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4550 _("Failed to load transport plugin for `%s'\n"), name);
4551 GNUNET_free (plug->short_name);
4552 plugins = plug->next;
4553 GNUNET_free (libname);
4560 * Called whenever a client is disconnected. Frees our
4561 * resources associated with that client.
4563 * @param cls closure
4564 * @param client identification of the client
4567 client_disconnect_notification (void *cls,
4568 struct GNUNET_SERVER_Client *client)
4570 struct TransportClient *pos;
4571 struct TransportClient *prev;
4572 struct ClientMessageQueueEntry *mqe;
4573 struct Blacklisters *bl;
4574 struct BlacklistCheck *bc;
4579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4580 "Client disconnected, cleaning up.\n");
4582 /* clean up blacklister */
4586 if (bl->client == client)
4591 if (bc->bl_pos == bl)
4593 bc->bl_pos = bl->next;
4596 GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
4599 if (bc->task == GNUNET_SCHEDULER_NO_TASK)
4600 bc->task = GNUNET_SCHEDULER_add_now (sched,
4601 &do_blacklist_check,
4607 GNUNET_CONTAINER_DLL_remove (bl_head,
4610 GNUNET_SERVER_client_drop (bl->client);
4616 /* clean up 'normal' clients */
4619 while ((pos != NULL) && (pos->client != client))
4626 while (NULL != (mqe = pos->message_queue_head))
4628 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
4629 pos->message_queue_tail,
4631 pos->message_count--;
4635 clients = pos->next;
4637 prev->next = pos->next;
4638 if (GNUNET_YES == pos->tcs_pending)
4643 if (pos->th != NULL)
4645 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
4648 GNUNET_break (0 == pos->message_count);
4654 * Iterator to free entries in the validation_map.
4656 * @param cls closure (unused)
4657 * @param key current key code
4658 * @param value value in the hash map (validation to abort)
4659 * @return GNUNET_YES (always)
4662 abort_validation (void *cls,
4663 const GNUNET_HashCode * key,
4666 struct ValidationEntry *va = value;
4668 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
4669 GNUNET_free (va->transport_name);
4676 * Function called when the service shuts down. Unloads our plugins
4677 * and cancels pending validations.
4679 * @param cls closure, unused
4680 * @param tc task context (unused)
4683 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4685 struct TransportPlugin *plug;
4686 struct OwnAddressList *al;
4687 struct CheckHelloValidatedContext *chvc;
4689 while (neighbours != NULL)
4690 disconnect_neighbour (neighbours, GNUNET_NO);
4692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4693 "Transport service is unloading plugins...\n");
4695 while (NULL != (plug = plugins))
4697 plugins = plug->next;
4698 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
4700 GNUNET_SCHEDULER_cancel (plug->env.sched,
4701 plug->address_update_task);
4702 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
4704 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
4705 GNUNET_free (plug->lib_name);
4706 GNUNET_free (plug->short_name);
4707 while (NULL != (al = plug->addresses))
4709 plug->addresses = al->next;
4714 if (my_private_key != NULL)
4715 GNUNET_CRYPTO_rsa_key_free (my_private_key);
4716 GNUNET_free_non_null (our_hello);
4718 /* free 'chvc' data structure */
4719 while (NULL != (chvc = chvc_head))
4721 chvc_head = chvc->next;
4722 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
4727 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4730 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4731 validation_map = NULL;
4734 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4738 /* Can we assume those are gone by now, or do we need to clean up
4740 GNUNET_break (bl_head == NULL);
4741 GNUNET_break (bc_head == NULL);
4746 * Initiate transport service.
4748 * @param cls closure
4749 * @param s scheduler to use
4750 * @param serv the initialized server
4751 * @param c configuration to use
4755 struct GNUNET_SCHEDULER_Handle *s,
4756 struct GNUNET_SERVER_Handle *serv,
4757 const struct GNUNET_CONFIGURATION_Handle *c)
4762 unsigned long long tneigh;
4767 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4768 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4769 /* parse configuration */
4771 GNUNET_CONFIGURATION_get_value_number (c,
4776 GNUNET_CONFIGURATION_get_value_filename (c,
4778 "HOSTKEY", &keyfile)))
4780 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4782 ("Transport service is lacking key configuration settings. Exiting.\n"));
4783 GNUNET_SCHEDULER_shutdown (s);
4786 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4789 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4790 validation_map = NULL;
4793 max_connect_per_transport = (uint32_t) tneigh;
4794 peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
4795 if (peerinfo == NULL)
4797 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4798 _("Could not access PEERINFO service. Exiting.\n"));
4799 GNUNET_SCHEDULER_shutdown (s);
4802 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4805 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4806 validation_map = NULL;
4807 GNUNET_free (keyfile);
4810 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4811 GNUNET_free (keyfile);
4812 if (my_private_key == NULL)
4814 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4816 ("Transport service could not access hostkey. Exiting.\n"));
4817 GNUNET_SCHEDULER_shutdown (s);
4820 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4823 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4824 validation_map = NULL;
4827 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4828 GNUNET_CRYPTO_hash (&my_public_key,
4829 sizeof (my_public_key), &my_identity.hashPubKey);
4830 /* setup notification */
4832 GNUNET_SERVER_disconnect_notify (server,
4833 &client_disconnect_notification, NULL);
4834 /* load plugins... */
4837 GNUNET_CONFIGURATION_get_value_string (c,
4838 "TRANSPORT", "PLUGINS", &plugs))
4840 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4841 _("Starting transport plugins `%s'\n"), plugs);
4842 pos = strtok (plugs, " ");
4845 start_transport (server, pos);
4847 pos = strtok (NULL, " ");
4849 GNUNET_free (plugs);
4851 GNUNET_SCHEDULER_add_delayed (sched,
4852 GNUNET_TIME_UNIT_FOREVER_REL,
4853 &shutdown_task, NULL);
4858 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
4860 /* If we have a blacklist file, read from it */
4861 read_blacklist_file(cfg);
4862 /* process client requests */
4863 GNUNET_SERVER_add_handlers (server, handlers);
4868 * The main function for the transport service.
4870 * @param argc number of arguments from the command line
4871 * @param argv command line arguments
4872 * @return 0 ok, 1 on error
4875 main (int argc, char *const *argv)
4877 return (GNUNET_OK ==
4878 GNUNET_SERVICE_run (argc,
4881 GNUNET_SERVICE_OPTION_NONE,
4882 &run, NULL)) ? 0 : 1;
4885 /* end of gnunet-service-transport.c */