2 This file is part of GNUnet.
3 (C) 2009 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!
33 #include "gnunet_client_lib.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_os_lib.h"
39 #include "gnunet_peerinfo_service.h"
40 #include "gnunet_plugin_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_signatures.h"
44 #include "plugin_transport.h"
45 #include "transport.h"
48 * Should we do some additional checks (to validate behavior
51 #define EXTRA_CHECKS GNUNET_YES
54 * How many messages can we have pending for a given client process
55 * before we start to drop incoming messages? We typically should
56 * have only one client and so this would be the primary buffer for
57 * messages, so the number should be chosen rather generously.
59 * The expectation here is that most of the time the queue is large
60 * enough so that a drop is virtually never required.
62 #define MAX_PENDING 128
65 * How often should we try to reconnect to a peer using a particular
66 * transport plugin before giving up? Note that the plugin may be
67 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
69 #define MAX_CONNECT_RETRY 3
72 * Limit on the number of ready-to-run tasks when validating
73 * HELLOs. If more tasks are ready to run, we will drop
74 * HELLOs instead of validating them.
76 #define MAX_HELLO_LOAD 4
79 * How often must a peer violate bandwidth quotas before we start
80 * to simply drop its messages?
82 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
85 * How long until a HELLO verification attempt should time out?
86 * Must be rather small, otherwise a partially successful HELLO
87 * validation (some addresses working) might not be available
88 * before a client's request for a connection fails for good.
89 * Besides, if a single request to an address takes a long time,
90 * then the peer is unlikely worthwhile anyway.
92 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
95 * Priority to use for PONG messages.
97 #define TRANSPORT_PONG_PRIORITY 4
100 * How often do we re-add (cheaper) plugins to our list of plugins
101 * to try for a given connected peer?
103 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
106 * After how long do we expire an address in a HELLO that we just
107 * validated? This value is also used for our own addresses when we
110 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
114 * How long before an existing address expires should we again try to
115 * validate it? Must be (significantly) smaller than
116 * HELLO_ADDRESS_EXPIRATION.
118 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
121 * Maximum frequency for re-evaluating latencies for all transport addresses.
123 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
126 * Maximum frequency for re-evaluating latencies for connected addresses.
128 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
132 * List of addresses of other peers
134 struct ForeignAddressList
137 * This is a linked list.
139 struct ForeignAddressList *next;
142 * Which ready list does this entry belong to.
144 struct ReadyList *ready_list;
147 * How long until we auto-expire this address (unless it is
148 * re-confirmed by the transport)?
150 struct GNUNET_TIME_Absolute expires;
153 * Task used to re-validate addresses, updates latencies and
156 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
169 * What was the last latency observed for this address, plugin and peer?
171 struct GNUNET_TIME_Relative latency;
174 * If we did not successfully transmit a message to the given peer
175 * via this connection during the specified time, we should consider
176 * the connection to be dead. This is used in the case that a TCP
177 * transport simply stalls writing to the stream but does not
178 * formerly get a signal that the other peer died.
180 struct GNUNET_TIME_Absolute timeout;
183 * How often have we tried to connect using this plugin? Used to
184 * discriminate against addresses that do not work well.
185 * FIXME: not yet used, but should be!
187 unsigned int connect_attempts;
190 * DV distance to this peer (1 if no DV is used).
191 * FIXME: need to set this from transport plugins!
196 * Have we ever estimated the latency of this address? Used to
197 * ensure that the first time we add an address, we immediately
203 * Are we currently connected via this address? The first time we
204 * successfully transmit or receive data to a peer via a particular
205 * address, we set this to GNUNET_YES. If we later get an error
206 * (disconnect notification, transmission failure, timeout), we set
207 * it back to GNUNET_NO.
212 * Is this plugin currently busy transmitting to the specific target?
213 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
214 * messages do not count as 'in transmit'.
219 * Has this address been validated yet?
227 * Entry in linked list of network addresses for ourselves.
229 struct OwnAddressList
232 * This is a linked list.
234 struct OwnAddressList *next;
237 * The address, actually a pointer to the end
238 * of this struct. Do not free!
243 * How long until we auto-expire this address (unless it is
244 * re-confirmed by the transport)?
246 struct GNUNET_TIME_Absolute expires;
257 * Entry in linked list of all of our plugins.
259 struct TransportPlugin
263 * This is a linked list.
265 struct TransportPlugin *next;
268 * API of the transport as returned by the plugin's
269 * initialization function.
271 struct GNUNET_TRANSPORT_PluginFunctions *api;
274 * Short name for the plugin (i.e. "tcp").
279 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
284 * List of our known addresses for this transport.
286 struct OwnAddressList *addresses;
289 * Environment this transport service is using
292 struct GNUNET_TRANSPORT_PluginEnvironment env;
295 * ID of task that is used to clean up expired addresses.
297 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
300 * Set to GNUNET_YES if we need to scrap the existing list of
301 * "addresses" and start fresh when we receive the next address
302 * update from a transport. Set to GNUNET_NO if we should just add
303 * the new address to the list and wait for the commit call.
309 struct NeighbourList;
312 * For each neighbour we keep a list of messages
313 * that we still want to transmit to the neighbour.
319 * This is a doubly linked list.
321 struct MessageQueue *next;
324 * This is a doubly linked list.
326 struct MessageQueue *prev;
329 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
330 * stuck together in memory. Allocated at the end of this struct.
332 const char *message_buf;
335 * Size of the message buf
337 size_t message_buf_size;
340 * Client responsible for queueing the message;
341 * used to check that a client has no two messages
342 * pending for the same target. Can be NULL.
344 struct TransportClient *client;
347 * Using which specific address should we send this message?
349 struct ForeignAddressList *specific_address;
352 * Peer ID of the Neighbour this entry belongs to.
354 struct GNUNET_PeerIdentity neighbour_id;
357 * Plugin that we used for the transmission.
358 * NULL until we scheduled a transmission.
360 struct TransportPlugin *plugin;
363 * At what time should we fail?
365 struct GNUNET_TIME_Absolute timeout;
368 * Internal message of the transport system that should not be
369 * included in the usual SEND-SEND_OK transmission confirmation
370 * traffic management scheme. Typically, "internal_msg" will
371 * be set whenever "client" is NULL (but it is not strictly
377 * How important is the message?
379 unsigned int priority;
385 * For a given Neighbour, which plugins are available
386 * to talk to this peer and what are their costs?
391 * This is a linked list.
393 struct ReadyList *next;
396 * Which of our transport plugins does this entry
399 struct TransportPlugin *plugin;
402 * Transport addresses, latency, and readiness for
403 * this particular plugin.
405 struct ForeignAddressList *addresses;
408 * To which neighbour does this ready list belong to?
410 struct NeighbourList *neighbour;
416 * Entry in linked list of all of our current neighbours.
422 * This is a linked list.
424 struct NeighbourList *next;
427 * Which of our transports is connected to this peer
428 * and what is their status?
430 struct ReadyList *plugins;
433 * Head of list of messages we would like to send to this peer;
434 * must contain at most one message per client.
436 struct MessageQueue *messages_head;
439 * Tail of list of messages we would like to send to this peer; must
440 * contain at most one message per client.
442 struct MessageQueue *messages_tail;
445 * Context for peerinfo iteration.
446 * NULL after we are done processing peerinfo's information.
448 struct GNUNET_PEERINFO_IteratorContext *piter;
451 * Public key for this peer. Valid only if the respective flag is set below.
453 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
456 * Identity of this neighbour.
458 struct GNUNET_PeerIdentity id;
461 * ID of task scheduled to run when this peer is about to
462 * time out (will free resources associated with the peer).
464 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
467 * ID of task scheduled to run when we should retry transmitting
468 * the head of the message queue. Actually triggered when the
469 * transmission is timing out (we trigger instantly when we have
470 * a chance of success).
472 GNUNET_SCHEDULER_TaskIdentifier retry_task;
475 * How long until we should consider this peer dead
476 * (if we don't receive another message in the
479 struct GNUNET_TIME_Absolute peer_timeout;
482 * Tracker for inbound bandwidth.
484 struct GNUNET_BANDWIDTH_Tracker in_tracker;
487 * The latency we have seen for this particular address for
488 * this particular peer. This latency may have been calculated
489 * over multiple transports. This value reflects how long it took
490 * us to receive a response when SENDING via this particular
491 * transport/neighbour/address combination!
493 * FIXME: we need to periodically send PINGs to update this
494 * latency (at least more often than the current "huge" (11h?)
497 struct GNUNET_TIME_Relative latency;
500 * How often has the other peer (recently) violated the
501 * inbound traffic limit? Incremented by 10 per violation,
502 * decremented by 1 per non-violation (for each
505 unsigned int quota_violation_count;
508 * DV distance to this peer (1 if no DV is used).
513 * Have we seen an PONG from this neighbour in the past (and
514 * not had a disconnect since)?
519 * Do we have a valid public key for this neighbour?
521 int public_key_valid;
526 * Message used to ask a peer to validate receipt (to check an address
529 struct TransportPingMessage
533 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
535 struct GNUNET_MessageHeader header;
538 * Random challenge number (in network byte order).
540 uint32_t challenge GNUNET_PACKED;
543 * Who is the intended recipient?
545 struct GNUNET_PeerIdentity target;
551 * Message used to validate a HELLO. The challenge is included in the
552 * confirmation to make matching of replies to requests possible. The
553 * signature signs the original challenge number, our public key, the
554 * sender's address (so that the sender can check that the address we
555 * saw is plausible for him and possibly detect a MiM attack) and a
556 * timestamp (to limit replay).<p>
558 * This message is followed by the address of the
559 * client that we are observing (which is part of what
562 struct TransportPongMessage
566 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
568 struct GNUNET_MessageHeader header;
571 * For padding, always zero.
573 uint32_t reserved GNUNET_PACKED;
578 struct GNUNET_CRYPTO_RsaSignature signature;
581 * What are we signing and why?
583 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
586 * Random challenge number (in network byte order).
588 uint32_t challenge GNUNET_PACKED;
591 * Who signed this message?
593 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
596 * Size of address appended to this message
604 * Linked list of messages to be transmitted to the client. Each
605 * entry is followed by the actual message.
607 struct ClientMessageQueueEntry
610 * This is a doubly-linked list.
612 struct ClientMessageQueueEntry *next;
615 * This is a doubly-linked list.
617 struct ClientMessageQueueEntry *prev;
622 * Client connected to the transport service.
624 struct TransportClient
628 * This is a linked list.
630 struct TransportClient *next;
633 * Handle to the client.
635 struct GNUNET_SERVER_Client *client;
638 * Linked list of messages yet to be transmitted to
641 struct ClientMessageQueueEntry *message_queue_head;
644 * Tail of linked list of messages yet to be transmitted to the
647 struct ClientMessageQueueEntry *message_queue_tail;
650 * Current transmit request handle.
652 struct GNUNET_CONNECTION_TransmitHandle *th;
655 * Is a call to "transmit_send_continuation" pending? If so, we
656 * must not free this struct (even if the corresponding client
657 * disconnects) and instead only remove it from the linked list and
658 * set the "client" field to NULL.
663 * Length of the list of messages pending for this client.
665 unsigned int message_count;
671 * Entry in map of all HELLOs awaiting validation.
673 struct ValidationEntry
677 * The address, actually a pointer to the end
678 * of this struct. Do not free!
683 * Name of the transport.
685 char *transport_name;
688 * The public key of the peer.
690 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
693 * ID of task that will clean up this entry if we don't succeed
694 * with the validation first.
696 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
699 * At what time did we send this validation?
701 struct GNUNET_TIME_Absolute send_time;
709 * Challenge number we used.
717 * Context of currently active requests to peerinfo
718 * for validation of HELLOs.
720 struct CheckHelloValidatedContext
724 * This is a doubly-linked list.
726 struct CheckHelloValidatedContext *next;
729 * This is a doubly-linked list.
731 struct CheckHelloValidatedContext *prev;
734 * Hello that we are validating.
736 const struct GNUNET_HELLO_Message *hello;
739 * Context for peerinfo iteration.
740 * NULL after we are done processing peerinfo's information.
742 struct GNUNET_PEERINFO_IteratorContext *piter;
745 * Was a HELLO known for this peer to peerinfo?
755 static struct GNUNET_HELLO_Message *our_hello;
758 * "version" of "our_hello". Used to see if a given neighbour has
759 * already been sent the latest version of our HELLO message.
761 static unsigned int our_hello_version;
766 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
771 static struct GNUNET_PeerIdentity my_identity;
776 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
781 struct GNUNET_SCHEDULER_Handle *sched;
786 const struct GNUNET_CONFIGURATION_Handle *cfg;
789 * Linked list of all clients to this service.
791 static struct TransportClient *clients;
794 * All loaded plugins.
796 static struct TransportPlugin *plugins;
801 static struct GNUNET_SERVER_Handle *server;
804 * All known neighbours and their HELLOs.
806 static struct NeighbourList *neighbours;
809 * Number of neighbours we'd like to have.
811 static uint32_t max_connect_per_transport;
814 * Head of linked list.
816 static struct CheckHelloValidatedContext *chvc_head;
819 * Tail of linked list.
821 static struct CheckHelloValidatedContext *chvc_tail;
824 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
825 * of the given peer that we are currently validating).
827 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
830 * Handle for reporting statistics.
832 static struct GNUNET_STATISTICS_Handle *stats;
836 * The peer specified by the given neighbour has timed-out or a plugin
837 * has disconnected. We may either need to do nothing (other plugins
838 * still up), or trigger a full disconnect and clean up. This
839 * function updates our state and do the necessary notifications.
840 * Also notifies our clients that the neighbour is now officially
843 * @param n the neighbour list entry for the peer
844 * @param check should we just check if all plugins
845 * disconnected or must we ask all plugins to
848 static void disconnect_neighbour (struct NeighbourList *n, int check);
851 * Check the ready list for the given neighbour and if a plugin is
852 * ready for transmission (and if we have a message), do so!
854 * @param neighbour target peer for which to transmit
856 static void try_transmission_to_peer (struct NeighbourList *neighbour);
860 * Find an entry in the neighbour list for a particular peer.
862 * @return NULL if not found.
864 static struct NeighbourList *
865 find_neighbour (const struct GNUNET_PeerIdentity *key)
867 struct NeighbourList *head = neighbours;
869 while ((head != NULL) &&
870 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
877 * Find an entry in the transport list for a particular transport.
879 * @return NULL if not found.
881 static struct TransportPlugin *
882 find_transport (const char *short_name)
884 struct TransportPlugin *head = plugins;
885 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
892 * Function called to notify a client about the socket being ready to
893 * queue more data. "buf" will be NULL and "size" zero if the socket
894 * was closed for writing in the meantime.
897 * @param size number of bytes available in buf
898 * @param buf where the callee should write the message
899 * @return number of bytes written to buf
902 transmit_to_client_callback (void *cls, size_t size, void *buf)
904 struct TransportClient *client = cls;
905 struct ClientMessageQueueEntry *q;
908 const struct GNUNET_MessageHeader *msg;
914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915 "Transmission to client failed, closing connection.\n");
916 /* fatal error with client, free message queue! */
917 while (NULL != (q = client->message_queue_head))
919 GNUNET_STATISTICS_update (stats,
920 gettext_noop ("# bytes discarded (could not transmit to client)"),
921 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
923 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
924 client->message_queue_tail,
928 client->message_count = 0;
933 while (NULL != (q = client->message_queue_head))
935 msg = (const struct GNUNET_MessageHeader *) &q[1];
936 msize = ntohs (msg->size);
937 if (msize + tsize > size)
940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941 "Transmitting message of type %u to client.\n",
944 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
945 client->message_queue_tail,
947 memcpy (&cbuf[tsize], msg, msize);
950 client->message_count--;
954 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
955 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
957 GNUNET_TIME_UNIT_FOREVER_REL,
958 &transmit_to_client_callback,
960 GNUNET_assert (client->th != NULL);
967 * Send the specified message to the specified client. Since multiple
968 * messages may be pending for the same client at a time, this code
969 * makes sure that no message is lost.
971 * @param client client to transmit the message to
972 * @param msg the message to send
973 * @param may_drop can this message be dropped if the
974 * message queue for this client is getting far too large?
977 transmit_to_client (struct TransportClient *client,
978 const struct GNUNET_MessageHeader *msg, int may_drop)
980 struct ClientMessageQueueEntry *q;
983 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
985 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
987 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
988 client->message_count, MAX_PENDING);
989 /* TODO: call to statistics... */
992 msize = ntohs (msg->size);
993 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
994 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
995 memcpy (&q[1], msg, msize);
996 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
997 client->message_queue_tail,
998 client->message_queue_tail,
1000 client->message_count++;
1001 if (client->th == NULL)
1003 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1005 GNUNET_TIME_UNIT_FOREVER_REL,
1006 &transmit_to_client_callback,
1008 GNUNET_assert (client->th != NULL);
1014 * Transmit a 'SEND_OK' notification to the given client for the
1017 * @param client who to notify
1018 * @param n neighbour to notify about
1019 * @param result status code for the transmission request
1022 transmit_send_ok (struct TransportClient *client,
1023 struct NeighbourList *n,
1026 struct SendOkMessage send_ok_msg;
1028 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1029 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1030 send_ok_msg.success = htonl (result);
1031 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1032 send_ok_msg.peer = n->id;
1033 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1038 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1039 * upon "completion" of a send request. This tells the API
1040 * that it is now legal to send another message to the given
1043 * @param cls closure, identifies the entry on the
1044 * message queue that was transmitted and the
1045 * client responsible for queueing the message
1046 * @param target the peer receiving the message
1047 * @param result GNUNET_OK on success, if the transmission
1048 * failed, we should not tell the client to transmit
1052 transmit_send_continuation (void *cls,
1053 const struct GNUNET_PeerIdentity *target,
1056 struct MessageQueue *mq = cls;
1057 struct NeighbourList *n;
1059 GNUNET_STATISTICS_update (stats,
1060 gettext_noop ("# bytes pending with plugins"),
1061 - (int64_t) mq->message_buf_size,
1063 if (result == GNUNET_OK)
1065 GNUNET_STATISTICS_update (stats,
1066 gettext_noop ("# bytes successfully transmitted by plugins"),
1067 mq->message_buf_size,
1072 GNUNET_STATISTICS_update (stats,
1073 gettext_noop ("# bytes with transmission failure by plugins"),
1074 mq->message_buf_size,
1077 n = find_neighbour(&mq->neighbour_id);
1078 GNUNET_assert (n != NULL);
1079 if (mq->specific_address != NULL)
1081 if (result == GNUNET_OK)
1083 mq->specific_address->timeout =
1084 GNUNET_TIME_relative_to_absolute
1085 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1086 if (mq->specific_address->connected != GNUNET_YES)
1088 GNUNET_STATISTICS_update (stats,
1089 gettext_noop ("# connected addresses"),
1092 mq->specific_address->connected = GNUNET_YES;
1097 if (mq->specific_address->connected != GNUNET_NO)
1099 GNUNET_STATISTICS_update (stats,
1100 gettext_noop ("# connected addresses"),
1103 mq->specific_address->connected = GNUNET_NO;
1106 if (! mq->internal_msg)
1107 mq->specific_address->in_transmit = GNUNET_NO;
1109 if (mq->client != NULL)
1110 transmit_send_ok (mq->client, n, result);
1112 try_transmission_to_peer (n);
1117 * Find an address in any of the available transports for
1118 * the given neighbour that would be good for message
1119 * transmission. This is essentially the transport selection
1122 * @param neighbour for whom to select an address
1123 * @return selected address, NULL if we have none
1125 struct ForeignAddressList *
1126 find_ready_address(struct NeighbourList *neighbour)
1128 struct ReadyList *head = neighbour->plugins;
1129 struct ForeignAddressList *addresses;
1130 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1131 struct ForeignAddressList *best_address;
1133 best_address = NULL;
1134 while (head != NULL)
1136 addresses = head->addresses;
1137 while (addresses != NULL)
1139 if ( (addresses->timeout.value < now.value) &&
1140 (addresses->connected == GNUNET_YES) )
1143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144 "Marking long-time inactive connection to `%4s' as down.\n",
1145 GNUNET_i2s (&neighbour->id));
1147 GNUNET_STATISTICS_update (stats,
1148 gettext_noop ("# connected addresses"),
1151 addresses->connected = GNUNET_NO;
1153 addresses = addresses->next;
1156 addresses = head->addresses;
1157 while (addresses != NULL)
1159 #if DEBUG_TRANSPORT > 1
1160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1161 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1162 GNUNET_a2s (addresses->addr,
1163 addresses->addrlen),
1164 GNUNET_i2s (&neighbour->id),
1165 addresses->connected,
1166 addresses->in_transmit,
1167 addresses->validated,
1168 addresses->connect_attempts,
1169 (unsigned long long) addresses->timeout.value,
1170 (unsigned int) addresses->distance);
1172 if ( ( (best_address == NULL) ||
1173 (addresses->connected == GNUNET_YES) ||
1174 (best_address->connected == GNUNET_NO) ) &&
1175 (addresses->in_transmit == GNUNET_NO) &&
1176 ( (best_address == NULL) ||
1177 (addresses->latency.value < best_address->latency.value)) )
1178 best_address = addresses;
1179 /* FIXME: also give lower-latency addresses that are not
1180 connected a chance some times... */
1181 addresses = addresses->next;
1185 if (best_address != NULL)
1188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189 "Best address found has latency of %llu ms.\n",
1190 best_address->latency.value);
1195 GNUNET_STATISTICS_update (stats,
1196 gettext_noop ("# transmission attempts failed (no address)"),
1200 return best_address;
1206 * We should re-try transmitting to the given peer,
1207 * hopefully we've learned something in the meantime.
1210 retry_transmission_task (void *cls,
1211 const struct GNUNET_SCHEDULER_TaskContext *tc)
1213 struct NeighbourList *n = cls;
1215 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1216 try_transmission_to_peer (n);
1221 * Check the ready list for the given neighbour and if a plugin is
1222 * ready for transmission (and if we have a message), do so!
1224 * @param neighbour target peer for which to transmit
1227 try_transmission_to_peer (struct NeighbourList *neighbour)
1229 struct ReadyList *rl;
1230 struct MessageQueue *mq;
1231 struct GNUNET_TIME_Relative timeout;
1235 if (neighbour->messages_head == NULL)
1238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1239 "Transmission queue for `%4s' is empty\n",
1240 GNUNET_i2s (&neighbour->id));
1242 return; /* nothing to do */
1245 mq = neighbour->messages_head;
1246 force_address = GNUNET_YES;
1247 if (mq->specific_address == NULL)
1249 mq->specific_address = find_ready_address(neighbour);
1250 GNUNET_STATISTICS_update (stats,
1251 gettext_noop ("# transport selected peer address freely"),
1254 force_address = GNUNET_NO;
1256 if (mq->specific_address == NULL)
1258 GNUNET_STATISTICS_update (stats,
1259 gettext_noop ("# transport failed to selected peer address"),
1262 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1263 if (timeout.value == 0)
1266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1267 "No destination address available to transmit message of size %u to peer `%4s'\n",
1268 mq->message_buf_size,
1269 GNUNET_i2s (&mq->neighbour_id));
1271 GNUNET_STATISTICS_update (stats,
1272 gettext_noop ("# bytes in message queue for other peers"),
1273 - (int64_t) mq->message_buf_size,
1275 GNUNET_STATISTICS_update (stats,
1276 gettext_noop ("# bytes discarded (no destination address available)"),
1277 mq->message_buf_size,
1279 if (mq->client != NULL)
1280 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1281 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1282 neighbour->messages_tail,
1285 return; /* nobody ready */
1287 GNUNET_STATISTICS_update (stats,
1288 gettext_noop ("# message delivery deferred (no address)"),
1291 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1292 GNUNET_SCHEDULER_cancel (sched,
1293 neighbour->retry_task);
1294 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1296 &retry_transmission_task,
1299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1300 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1301 mq->message_buf_size,
1302 GNUNET_i2s (&mq->neighbour_id),
1305 /* FIXME: might want to trigger peerinfo lookup here
1306 (unless that's already pending...) */
1309 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1310 neighbour->messages_tail,
1312 if (mq->specific_address->connected == GNUNET_NO)
1313 mq->specific_address->connect_attempts++;
1314 rl = mq->specific_address->ready_list;
1315 mq->plugin = rl->plugin;
1316 if (!mq->internal_msg)
1317 mq->specific_address->in_transmit = GNUNET_YES;
1319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1320 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1321 mq->message_buf_size,
1322 GNUNET_i2s (&neighbour->id),
1323 GNUNET_a2s (mq->specific_address->addr,
1324 mq->specific_address->addrlen),
1325 rl->plugin->short_name);
1327 GNUNET_STATISTICS_update (stats,
1328 gettext_noop ("# bytes in message queue for other peers"),
1329 - (int64_t) mq->message_buf_size,
1331 GNUNET_STATISTICS_update (stats,
1332 gettext_noop ("# bytes pending with plugins"),
1333 mq->message_buf_size,
1335 ret = rl->plugin->api->send (rl->plugin->api->cls,
1338 mq->message_buf_size,
1340 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1341 mq->specific_address->addr,
1342 mq->specific_address->addrlen,
1344 &transmit_send_continuation, mq);
1347 /* failure, but 'send' would not call continuation in this case,
1348 so we need to do it here! */
1349 transmit_send_continuation (mq,
1357 * Send the specified message to the specified peer.
1359 * @param client source of the transmission request (can be NULL)
1360 * @param peer_address ForeignAddressList where we should send this message
1361 * @param priority how important is the message
1362 * @param timeout how long do we have to transmit?
1363 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1364 * @param message_buf_size total size of all messages in message_buf
1365 * @param is_internal is this an internal message; these are pre-pended and
1366 * also do not count for plugins being "ready" to transmit
1367 * @param neighbour handle to the neighbour for transmission
1370 transmit_to_peer (struct TransportClient *client,
1371 struct ForeignAddressList *peer_address,
1372 unsigned int priority,
1373 struct GNUNET_TIME_Relative timeout,
1374 const char *message_buf,
1375 size_t message_buf_size,
1376 int is_internal, struct NeighbourList *neighbour)
1378 struct MessageQueue *mq;
1383 /* check for duplicate submission */
1384 mq = neighbour->messages_head;
1387 if (mq->client == client)
1389 /* client transmitted to same peer twice
1390 before getting SEND_OK! */
1398 GNUNET_STATISTICS_update (stats,
1399 gettext_noop ("# bytes in message queue for other peers"),
1402 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1403 mq->specific_address = peer_address;
1404 mq->client = client;
1405 memcpy (&mq[1], message_buf, message_buf_size);
1406 mq->message_buf = (const char*) &mq[1];
1407 mq->message_buf_size = message_buf_size;
1408 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1409 mq->internal_msg = is_internal;
1410 mq->priority = priority;
1411 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1413 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1414 neighbour->messages_tail,
1417 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1418 neighbour->messages_tail,
1419 neighbour->messages_tail,
1421 try_transmission_to_peer (neighbour);
1428 struct GeneratorContext
1430 struct TransportPlugin *plug_pos;
1431 struct OwnAddressList *addr_pos;
1432 struct GNUNET_TIME_Absolute expiration;
1440 address_generator (void *cls, size_t max, void *buf)
1442 struct GeneratorContext *gc = cls;
1445 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1447 gc->plug_pos = gc->plug_pos->next;
1448 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1450 if (NULL == gc->plug_pos)
1455 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1458 gc->addr_pos->addrlen, buf, max);
1459 gc->addr_pos = gc->addr_pos->next;
1465 * Construct our HELLO message from all of the addresses of
1466 * all of the transports.
1471 struct GNUNET_HELLO_Message *hello;
1472 struct TransportClient *cpos;
1473 struct NeighbourList *npos;
1474 struct GeneratorContext gc;
1476 gc.plug_pos = plugins;
1477 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1478 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1479 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1482 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1484 GNUNET_STATISTICS_update (stats,
1485 gettext_noop ("# refreshed my HELLO"),
1489 while (cpos != NULL)
1491 transmit_to_client (cpos,
1492 (const struct GNUNET_MessageHeader *) hello,
1497 GNUNET_free_non_null (our_hello);
1499 our_hello_version++;
1500 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1502 while (npos != NULL)
1505 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1506 "Transmitting updated `%s' to neighbour `%4s'\n",
1507 "HELLO", GNUNET_i2s (&npos->id));
1509 GNUNET_STATISTICS_update (stats,
1510 gettext_noop ("# transmitted my HELLO to other peers"),
1513 transmit_to_peer (NULL, NULL, 0,
1514 HELLO_ADDRESS_EXPIRATION,
1515 (const char *) our_hello,
1516 GNUNET_HELLO_size(our_hello),
1524 * Task used to clean up expired addresses for a plugin.
1526 * @param cls closure
1530 expire_address_task (void *cls,
1531 const struct GNUNET_SCHEDULER_TaskContext *tc);
1535 * Update the list of addresses for this plugin,
1536 * expiring those that are past their expiration date.
1538 * @param plugin addresses of which plugin should be recomputed?
1539 * @param fresh set to GNUNET_YES if a new address was added
1540 * and we need to regenerate the HELLO even if nobody
1544 update_addresses (struct TransportPlugin *plugin, int fresh)
1546 static struct GNUNET_TIME_Absolute last_update;
1547 struct GNUNET_TIME_Relative min_remaining;
1548 struct GNUNET_TIME_Relative remaining;
1549 struct GNUNET_TIME_Absolute now;
1550 struct OwnAddressList *pos;
1551 struct OwnAddressList *prev;
1552 struct OwnAddressList *next;
1555 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1556 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1557 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1558 now = GNUNET_TIME_absolute_get ();
1559 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1560 expired = (GNUNET_TIME_absolute_get_duration (last_update).value > (HELLO_ADDRESS_EXPIRATION.value / 4));
1562 pos = plugin->addresses;
1566 if (pos->expires.value < now.value)
1568 expired = GNUNET_YES;
1570 plugin->addresses = pos->next;
1572 prev->next = pos->next;
1577 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1578 if (remaining.value < min_remaining.value)
1579 min_remaining = remaining;
1585 if (expired || fresh)
1590 min_remaining = GNUNET_TIME_relative_min (min_remaining,
1591 GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1593 plugin->address_update_task
1594 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1596 &expire_address_task, plugin);
1601 * Task used to clean up expired addresses for a plugin.
1603 * @param cls closure
1607 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1609 struct TransportPlugin *plugin = cls;
1611 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1612 if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1613 update_addresses (plugin, GNUNET_NO);
1618 * Function that must be called by each plugin to notify the
1619 * transport service about the addresses under which the transport
1620 * provided by the plugin can be reached.
1622 * @param cls closure
1623 * @param name name of the transport that generated the address
1624 * @param addr one of the addresses of the host, NULL for the last address
1625 * the specific address format depends on the transport
1626 * @param addrlen length of the address
1627 * @param expires when should this address automatically expire?
1630 plugin_env_notify_address (void *cls,
1634 struct GNUNET_TIME_Relative expires)
1636 struct TransportPlugin *p = cls;
1637 struct OwnAddressList *al;
1638 struct GNUNET_TIME_Absolute abex;
1640 abex = GNUNET_TIME_relative_to_absolute (expires);
1641 GNUNET_assert (p == find_transport (name));
1646 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1648 if (al->expires.value < abex.value)
1655 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1657 al->next = p->addresses;
1660 al->addrlen = addrlen;
1661 memcpy (&al[1], addr, addrlen);
1662 update_addresses (p, GNUNET_YES);
1667 * Notify all of our clients about a peer connecting.
1670 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1671 struct GNUNET_TIME_Relative latency,
1674 struct ConnectInfoMessage cim;
1675 struct TransportClient *cpos;
1678 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1679 "Notifying clients about connection from `%s'\n",
1682 GNUNET_STATISTICS_update (stats,
1683 gettext_noop ("# peers connected"),
1686 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1687 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1688 cim.distance = htonl (distance);
1689 cim.latency = GNUNET_TIME_relative_hton (latency);
1690 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1692 while (cpos != NULL)
1694 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1701 * Notify all of our clients about a peer disconnecting.
1704 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1706 struct DisconnectInfoMessage dim;
1707 struct TransportClient *cpos;
1710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1711 "Notifying clients about lost connection to `%s'\n",
1714 GNUNET_STATISTICS_update (stats,
1715 gettext_noop ("# peers connected"),
1718 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1719 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1720 dim.reserved = htonl (0);
1721 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1723 while (cpos != NULL)
1725 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1732 * Find a ForeignAddressList entry for the given neighbour
1733 * that matches the given address and transport.
1735 * @param neighbour which peer we care about
1736 * @param tname name of the transport plugin
1737 * @param addr binary address
1738 * @param addrlen length of addr
1739 * @return NULL if no such entry exists
1741 static struct ForeignAddressList *
1742 find_peer_address(struct NeighbourList *neighbour,
1747 struct ReadyList *head;
1748 struct ForeignAddressList *address_head;
1750 head = neighbour->plugins;
1751 while (head != NULL)
1753 if (0 == strcmp (tname, head->plugin->short_name))
1760 address_head = head->addresses;
1761 while ( (address_head != NULL) &&
1762 ( (address_head->addrlen != addrlen) ||
1763 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1764 address_head = address_head->next;
1765 return address_head;
1770 * Get the peer address struct for the given neighbour and
1771 * address. If it doesn't yet exist, create it.
1773 * @param neighbour which peer we care about
1774 * @param tname name of the transport plugin
1775 * @param addr binary address
1776 * @param addrlen length of addr
1777 * @return NULL if we do not have a transport plugin for 'tname'
1779 static struct ForeignAddressList *
1780 add_peer_address (struct NeighbourList *neighbour,
1785 struct ReadyList *head;
1786 struct ForeignAddressList *ret;
1788 ret = find_peer_address (neighbour, tname, addr, addrlen);
1791 head = neighbour->plugins;
1792 while (head != NULL)
1794 if (0 == strcmp (tname, head->plugin->short_name))
1800 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1801 ret->addr = (const char*) &ret[1];
1802 memcpy (&ret[1], addr, addrlen);
1803 ret->addrlen = addrlen;
1804 ret->expires = GNUNET_TIME_relative_to_absolute
1805 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1806 ret->latency = GNUNET_TIME_relative_get_forever();
1808 ret->timeout = GNUNET_TIME_relative_to_absolute
1809 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1810 ret->ready_list = head;
1811 ret->next = head->addresses;
1812 head->addresses = ret;
1818 * Closure for 'add_validated_address'.
1820 struct AddValidatedAddressContext
1823 * Entry that has been validated.
1825 const struct ValidationEntry *ve;
1828 * Flag set after we have added the address so
1829 * that we terminate the iteration next time.
1836 * Callback function used to fill a buffer of max bytes with a list of
1837 * addresses in the format used by HELLOs. Should use
1838 * "GNUNET_HELLO_add_address" as a helper function.
1840 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1841 * @param max maximum number of bytes that can be written to buf
1842 * @param buf where to write the address information
1843 * @return number of bytes written, 0 to signal the
1844 * end of the iteration.
1847 add_validated_address (void *cls,
1848 size_t max, void *buf)
1850 struct AddValidatedAddressContext *avac = cls;
1851 const struct ValidationEntry *ve = avac->ve;
1853 if (GNUNET_YES == avac->done)
1855 avac->done = GNUNET_YES;
1856 return GNUNET_HELLO_add_address (ve->transport_name,
1857 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1867 * Closure for 'check_address_exists'.
1869 struct CheckAddressExistsClosure
1872 * Address to check for.
1877 * Name of the transport.
1887 * Set to GNUNET_YES if the address exists.
1894 * Iterator over hash map entries. Checks if the given
1895 * validation entry is for the same address as what is given
1898 * @param cls the 'struct CheckAddressExistsClosure*'
1899 * @param key current key code (ignored)
1900 * @param value value in the hash map ('struct ValidationEntry')
1901 * @return GNUNET_YES if we should continue to
1902 * iterate (mismatch), GNUNET_NO if not (entry matched)
1905 check_address_exists (void *cls,
1906 const GNUNET_HashCode * key,
1909 struct CheckAddressExistsClosure *caec = cls;
1910 struct ValidationEntry *ve = value;
1911 if ( (0 == strcmp (caec->tname,
1912 ve->transport_name)) &&
1913 (caec->addrlen == ve->addrlen) &&
1914 (0 == memcmp (caec->addr,
1918 caec->exists = GNUNET_YES;
1926 * HELLO validation cleanup task (validation failed).
1928 * @param cls the 'struct ValidationEntry' that failed
1929 * @param tc scheduler context (unused)
1932 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1934 struct ValidationEntry *va = cls;
1935 struct GNUNET_PeerIdentity pid;
1937 GNUNET_STATISTICS_update (stats,
1938 gettext_noop ("# address validation timeouts"),
1941 GNUNET_CRYPTO_hash (&va->publicKey,
1943 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1945 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1948 GNUNET_free (va->transport_name);
1954 neighbour_timeout_task (void *cls,
1955 const struct GNUNET_SCHEDULER_TaskContext *tc)
1957 struct NeighbourList *n = cls;
1960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1961 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1963 GNUNET_STATISTICS_update (stats,
1964 gettext_noop ("# disconnects due to timeout"),
1967 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1968 disconnect_neighbour (n, GNUNET_NO);
1973 * Schedule the job that will cause us to send a PING to the
1974 * foreign address to evaluate its validity and latency.
1976 * @param fal address to PING
1979 schedule_next_ping (struct ForeignAddressList *fal);
1983 * Add the given address to the list of foreign addresses
1984 * available for the given peer (check for duplicates).
1986 * @param cls the respective 'struct NeighbourList' to update
1987 * @param tname name of the transport
1988 * @param expiration expiration time
1989 * @param addr the address
1990 * @param addrlen length of the address
1991 * @return GNUNET_OK (always)
1994 add_to_foreign_address_list (void *cls,
1996 struct GNUNET_TIME_Absolute expiration,
1997 const void *addr, size_t addrlen)
1999 struct NeighbourList *n = cls;
2000 struct ForeignAddressList *fal;
2003 GNUNET_STATISTICS_update (stats,
2004 gettext_noop ("# valid peer addresses returned by peerinfo"),
2008 fal = find_peer_address (n, tname, addr, addrlen);
2012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2013 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2014 GNUNET_a2s (addr, addrlen),
2016 GNUNET_i2s (&n->id),
2019 fal = add_peer_address (n, tname, addr, addrlen);
2022 GNUNET_STATISTICS_update (stats,
2023 gettext_noop ("# previously validated addresses lacking transport"),
2029 fal->expires = GNUNET_TIME_absolute_max (expiration,
2031 schedule_next_ping (fal);
2037 fal->expires = GNUNET_TIME_absolute_max (expiration,
2042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2043 "Failed to add new address for `%4s'\n",
2044 GNUNET_i2s (&n->id));
2047 if (fal->validated == GNUNET_NO)
2049 fal->validated = GNUNET_YES;
2050 GNUNET_STATISTICS_update (stats,
2051 gettext_noop ("# peer addresses considered valid"),
2055 if (try == GNUNET_YES)
2057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2058 "Have new addresses, will try to trigger transmissions.\n");
2059 try_transmission_to_peer (n);
2066 * Add addresses in validated HELLO "h" to the set of addresses
2067 * we have for this peer.
2069 * @param cls closure ('struct NeighbourList*')
2070 * @param peer id of the peer, NULL for last call
2071 * @param h hello message for the peer (can be NULL)
2072 * @param trust amount of trust we have in the peer (not used)
2075 add_hello_for_peer (void *cls,
2076 const struct GNUNET_PeerIdentity *peer,
2077 const struct GNUNET_HELLO_Message *h,
2080 struct NeighbourList *n = cls;
2088 return; /* no HELLO available */
2090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2095 if (GNUNET_YES != n->public_key_valid)
2097 GNUNET_HELLO_get_key (h, &n->publicKey);
2098 n->public_key_valid = GNUNET_YES;
2100 GNUNET_HELLO_iterate_addresses (h,
2102 &add_to_foreign_address_list,
2108 * Create a fresh entry in our neighbour list for the given peer.
2109 * Will try to transmit our current HELLO to the new neighbour.
2111 * @param peer the peer for which we create the entry
2112 * @return the new neighbour list entry
2114 static struct NeighbourList *
2115 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2117 struct NeighbourList *n;
2118 struct TransportPlugin *tp;
2119 struct ReadyList *rl;
2121 GNUNET_assert (our_hello != NULL);
2122 GNUNET_STATISTICS_update (stats,
2123 gettext_noop ("# active neighbours"),
2126 n = GNUNET_malloc (sizeof (struct NeighbourList));
2127 n->next = neighbours;
2131 GNUNET_TIME_relative_to_absolute
2132 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2133 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2134 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2135 MAX_BANDWIDTH_CARRY_S);
2139 if (tp->api->send != NULL)
2141 rl = GNUNET_malloc (sizeof (struct ReadyList));
2143 rl->next = n->plugins;
2146 rl->addresses = NULL;
2150 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2152 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2153 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2154 &neighbour_timeout_task, n);
2155 n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2156 0, GNUNET_TIME_UNIT_FOREVER_REL,
2157 &add_hello_for_peer, n);
2158 transmit_to_peer (NULL, NULL, 0,
2159 HELLO_ADDRESS_EXPIRATION,
2160 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2167 * Send periodic PING messages to a give foreign address.
2169 * @param cls our 'struct PeriodicValidationContext*'
2170 * @param tc task context
2173 send_periodic_ping (void *cls,
2174 const struct GNUNET_SCHEDULER_TaskContext *tc)
2176 struct ForeignAddressList *peer_address = cls;
2177 struct TransportPlugin *tp;
2178 struct ValidationEntry *va;
2179 struct NeighbourList *neighbour;
2180 struct TransportPingMessage ping;
2181 struct CheckAddressExistsClosure caec;
2183 uint16_t hello_size;
2186 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2187 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2189 tp = peer_address->ready_list->plugin;
2190 neighbour = peer_address->ready_list->neighbour;
2191 if (GNUNET_YES != neighbour->public_key_valid)
2193 /* no public key yet, try again later */
2194 schedule_next_ping (peer_address);
2197 caec.addr = peer_address->addr;
2198 caec.addrlen = peer_address->addrlen;
2199 caec.tname = tp->short_name;
2200 caec.exists = GNUNET_NO;
2201 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2202 &check_address_exists,
2204 if (caec.exists == GNUNET_YES)
2206 /* During validation attempts we will likely trigger the other
2207 peer trying to validate our address which in turn will cause
2208 it to send us its HELLO, so we expect to hit this case rather
2209 frequently. Only print something if we are very verbose. */
2210 #if DEBUG_TRANSPORT > 1
2211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2213 GNUNET_a2s (peer_address->addr,
2214 peer_address->addrlen),
2216 GNUNET_i2s (&neighbour->id));
2218 schedule_next_ping (peer_address);
2221 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2222 va->transport_name = GNUNET_strdup (tp->short_name);
2223 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2225 va->send_time = GNUNET_TIME_absolute_get();
2226 va->addr = (const void*) &va[1];
2227 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2228 va->addrlen = peer_address->addrlen;
2230 memcpy(&va->publicKey,
2231 &neighbour->publicKey,
2232 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2234 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2235 HELLO_VERIFICATION_TIMEOUT,
2236 &timeout_hello_validation,
2238 GNUNET_CONTAINER_multihashmap_put (validation_map,
2239 &neighbour->id.hashPubKey,
2241 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2242 hello_size = GNUNET_HELLO_size(our_hello);
2243 tsize = sizeof(struct TransportPingMessage) + hello_size;
2244 message_buf = GNUNET_malloc(tsize);
2245 ping.challenge = htonl(va->challenge);
2246 ping.header.size = htons(sizeof(struct TransportPingMessage));
2247 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2248 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2249 memcpy(message_buf, our_hello, hello_size);
2250 memcpy(&message_buf[hello_size],
2252 sizeof(struct TransportPingMessage));
2253 #if DEBUG_TRANSPORT_REVALIDATION
2254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2256 GNUNET_a2s (peer_address->addr,
2257 peer_address->addrlen),
2259 GNUNET_i2s (&neighbour->id),
2260 "HELLO", hello_size,
2261 "PING", sizeof (struct TransportPingMessage));
2263 GNUNET_STATISTICS_update (stats,
2264 gettext_noop ("# PING messages sent for re-validation"),
2267 transmit_to_peer (NULL, peer_address,
2268 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2269 HELLO_VERIFICATION_TIMEOUT,
2271 GNUNET_YES, neighbour);
2272 GNUNET_free(message_buf);
2273 schedule_next_ping (peer_address);
2278 * Schedule the job that will cause us to send a PING to the
2279 * foreign address to evaluate its validity and latency.
2281 * @param fal address to PING
2284 schedule_next_ping (struct ForeignAddressList *fal)
2286 struct GNUNET_TIME_Relative delay;
2288 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2290 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2291 delay.value /= 2; /* do before expiration */
2292 delay = GNUNET_TIME_relative_min (delay,
2293 LATENCY_EVALUATION_MAX_DELAY);
2294 if (GNUNET_YES != fal->estimated)
2296 delay = GNUNET_TIME_UNIT_ZERO;
2297 fal->estimated = GNUNET_YES;
2299 if (GNUNET_YES == fal->connected)
2301 delay = GNUNET_TIME_relative_min (delay,
2302 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2304 /* FIXME: also adjust delay based on how close the last
2305 observed latency is to the latency of the best alternative */
2306 /* bound how fast we can go */
2307 delay = GNUNET_TIME_relative_max (delay,
2308 GNUNET_TIME_UNIT_SECONDS);
2309 /* randomize a bit (to avoid doing all at the same time) */
2310 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2311 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
2313 &send_periodic_ping,
2319 * Iterator over hash map entries. Checks if the given validation
2320 * entry is for the same challenge as what is given in the PONG.
2322 * @param cls the 'struct TransportPongMessage*'
2323 * @param key peer identity
2324 * @param value value in the hash map ('struct ValidationEntry')
2325 * @return GNUNET_YES if we should continue to
2326 * iterate (mismatch), GNUNET_NO if not (entry matched)
2329 check_pending_validation (void *cls,
2330 const GNUNET_HashCode * key,
2333 const struct TransportPongMessage *pong = cls;
2334 struct ValidationEntry *ve = value;
2335 struct AddValidatedAddressContext avac;
2336 unsigned int challenge = ntohl(pong->challenge);
2337 struct GNUNET_HELLO_Message *hello;
2338 struct GNUNET_PeerIdentity target;
2339 struct NeighbourList *n;
2340 struct ForeignAddressList *fal;
2342 if (ve->challenge != challenge)
2346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2349 GNUNET_a2s ((const struct sockaddr *) ve->addr,
2351 ve->transport_name);
2353 GNUNET_STATISTICS_update (stats,
2354 gettext_noop ("# address validation successes"),
2357 /* create the updated HELLO */
2358 GNUNET_CRYPTO_hash (&ve->publicKey,
2359 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2360 &target.hashPubKey);
2361 avac.done = GNUNET_NO;
2363 hello = GNUNET_HELLO_create (&ve->publicKey,
2364 &add_validated_address,
2366 GNUNET_PEERINFO_add_peer (cfg, sched,
2369 GNUNET_free (hello);
2370 n = find_neighbour (&target);
2373 n->publicKey = ve->publicKey;
2374 n->public_key_valid = GNUNET_YES;
2375 fal = add_peer_address (n,
2379 GNUNET_assert (fal != NULL);
2380 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2381 fal->validated = GNUNET_YES;
2382 GNUNET_STATISTICS_update (stats,
2383 gettext_noop ("# peer addresses considered valid"),
2386 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2387 schedule_next_ping (fal);
2388 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2389 n->latency = fal->latency;
2391 n->latency.value = (fal->latency.value + n->latency.value) / 2;
2392 n->distance = fal->distance;
2393 if (GNUNET_NO == n->received_pong)
2395 notify_clients_connect (&target, n->latency, n->distance);
2396 n->received_pong = GNUNET_YES;
2398 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2400 GNUNET_SCHEDULER_cancel (sched,
2402 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2403 try_transmission_to_peer (n);
2407 /* clean up validation entry */
2408 GNUNET_assert (GNUNET_YES ==
2409 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2412 GNUNET_SCHEDULER_cancel (sched,
2414 GNUNET_free (ve->transport_name);
2421 * Function that will be called if we receive a validation
2422 * of an address challenge that we transmitted to another
2423 * peer. Note that the validation should only be considered
2424 * acceptable if the challenge matches AND if the sender
2425 * address is at least a plausible address for this peer
2426 * (otherwise we may be seeing a MiM attack).
2428 * @param cls closure
2429 * @param message the pong message
2430 * @param peer who responded to our challenge
2431 * @param sender_address string describing our sender address (as observed
2432 * by the other peer in binary format)
2433 * @param sender_address_len number of bytes in 'sender_address'
2436 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2437 const struct GNUNET_PeerIdentity *peer,
2438 const char *sender_address,
2439 size_t sender_address_len)
2441 #if DEBUG_TRANSPORT > 1
2442 /* we get tons of these that just get discarded, only log
2443 if we are quite verbose */
2444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445 "Receiving `%s' message from `%4s'.\n", "PONG",
2448 GNUNET_STATISTICS_update (stats,
2449 gettext_noop ("# PONG messages received"),
2452 if (GNUNET_SYSERR !=
2453 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2455 &check_pending_validation,
2458 /* This is *expected* to happen a lot since we send
2459 PONGs to *all* known addresses of the sender of
2460 the PING, so most likely we get multiple PONGs
2461 per PING, and all but the first PONG will end up
2462 here. So really we should not print anything here
2463 unless we want to be very, very verbose... */
2464 #if DEBUG_TRANSPORT > 2
2465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2475 /* FIXME: add given address to potential pool of our addresses
2477 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2478 _("Another peer saw us using the address `%s' via `%s'.\n"),
2479 GNUNET_a2s ((const struct sockaddr *) &pong[1],
2480 ntohs(pong->addrlen)),
2481 va->transport_name);
2487 * Check if the given address is already being validated; if not,
2488 * append the given address to the list of entries that are being be
2489 * validated and initiate validation.
2491 * @param cls closure ('struct CheckHelloValidatedContext *')
2492 * @param tname name of the transport
2493 * @param expiration expiration time
2494 * @param addr the address
2495 * @param addrlen length of the address
2496 * @return GNUNET_OK (always)
2499 run_validation (void *cls,
2501 struct GNUNET_TIME_Absolute expiration,
2502 const void *addr, size_t addrlen)
2504 struct CheckHelloValidatedContext *chvc = cls;
2505 struct GNUNET_PeerIdentity id;
2506 struct TransportPlugin *tp;
2507 struct ValidationEntry *va;
2508 struct NeighbourList *neighbour;
2509 struct ForeignAddressList *peer_address;
2510 struct TransportPingMessage ping;
2511 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2512 struct CheckAddressExistsClosure caec;
2514 uint16_t hello_size;
2517 GNUNET_STATISTICS_update (stats,
2518 gettext_noop ("# peer addresses scheduled for validation"),
2521 tp = find_transport (tname);
2524 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2525 GNUNET_ERROR_TYPE_BULK,
2527 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2529 GNUNET_STATISTICS_update (stats,
2530 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2535 GNUNET_HELLO_get_key (chvc->hello, &pk);
2536 GNUNET_CRYPTO_hash (&pk,
2538 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2541 caec.addrlen = addrlen;
2543 caec.exists = GNUNET_NO;
2544 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2545 &check_address_exists,
2547 if (caec.exists == GNUNET_YES)
2549 /* During validation attempts we will likely trigger the other
2550 peer trying to validate our address which in turn will cause
2551 it to send us its HELLO, so we expect to hit this case rather
2552 frequently. Only print something if we are very verbose. */
2553 #if DEBUG_TRANSPORT > 1
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2556 GNUNET_a2s (addr, addrlen),
2560 GNUNET_STATISTICS_update (stats,
2561 gettext_noop ("# peer addresses not validated (in progress)"),
2566 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2567 va->transport_name = GNUNET_strdup (tname);
2568 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2570 va->send_time = GNUNET_TIME_absolute_get();
2571 va->addr = (const void*) &va[1];
2572 memcpy (&va[1], addr, addrlen);
2573 va->addrlen = addrlen;
2574 GNUNET_HELLO_get_key (chvc->hello,
2576 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2577 HELLO_VERIFICATION_TIMEOUT,
2578 &timeout_hello_validation,
2580 GNUNET_CONTAINER_multihashmap_put (validation_map,
2583 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2584 neighbour = find_neighbour(&id);
2585 if (neighbour == NULL)
2586 neighbour = setup_new_neighbour(&id);
2587 neighbour->publicKey = va->publicKey;
2588 neighbour->public_key_valid = GNUNET_YES;
2589 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2590 GNUNET_assert(peer_address != NULL);
2591 hello_size = GNUNET_HELLO_size(our_hello);
2592 tsize = sizeof(struct TransportPingMessage) + hello_size;
2593 message_buf = GNUNET_malloc(tsize);
2594 ping.challenge = htonl(va->challenge);
2595 ping.header.size = htons(sizeof(struct TransportPingMessage));
2596 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2597 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2598 memcpy(message_buf, our_hello, hello_size);
2599 memcpy(&message_buf[hello_size],
2601 sizeof(struct TransportPingMessage));
2603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2604 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2605 GNUNET_a2s (addr, addrlen),
2608 "HELLO", hello_size,
2609 "PING", sizeof (struct TransportPingMessage));
2611 GNUNET_STATISTICS_update (stats,
2612 gettext_noop ("# PING messages sent for initial validation"),
2615 transmit_to_peer (NULL, peer_address,
2616 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2617 HELLO_VERIFICATION_TIMEOUT,
2619 GNUNET_YES, neighbour);
2620 GNUNET_free(message_buf);
2626 * Check if addresses in validated hello "h" overlap with
2627 * those in "chvc->hello" and validate the rest.
2629 * @param cls closure
2630 * @param peer id of the peer, NULL for last call
2631 * @param h hello message for the peer (can be NULL)
2632 * @param trust amount of trust we have in the peer (not used)
2635 check_hello_validated (void *cls,
2636 const struct GNUNET_PeerIdentity *peer,
2637 const struct GNUNET_HELLO_Message *h,
2640 struct CheckHelloValidatedContext *chvc = cls;
2641 struct GNUNET_HELLO_Message *plain_hello;
2642 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2643 struct GNUNET_PeerIdentity target;
2644 struct NeighbourList *n;
2649 GNUNET_CONTAINER_DLL_remove (chvc_head,
2652 if (GNUNET_NO == chvc->hello_known)
2654 /* notify PEERINFO about the peer now, so that we at least
2655 have the public key if some other component needs it */
2656 GNUNET_HELLO_get_key (chvc->hello, &pk);
2657 GNUNET_CRYPTO_hash (&pk,
2658 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2659 &target.hashPubKey);
2660 plain_hello = GNUNET_HELLO_create (&pk,
2663 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2664 GNUNET_free (plain_hello);
2666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2669 GNUNET_i2s (&target));
2671 GNUNET_STATISTICS_update (stats,
2672 gettext_noop ("# new HELLOs requiring full validation"),
2675 GNUNET_HELLO_iterate_addresses (chvc->hello,
2682 GNUNET_STATISTICS_update (stats,
2683 gettext_noop ("# duplicate HELLO (peer known)"),
2693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2694 "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2698 chvc->hello_known = GNUNET_YES;
2699 n = find_neighbour (peer);
2702 GNUNET_HELLO_iterate_addresses (h,
2704 &add_to_foreign_address_list,
2706 try_transmission_to_peer (n);
2710 GNUNET_STATISTICS_update (stats,
2711 gettext_noop ("# no existing neighbour record (validating HELLO)"),
2715 GNUNET_STATISTICS_update (stats,
2716 gettext_noop ("# HELLO validations (update case)"),
2719 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2721 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2727 * Process HELLO-message.
2729 * @param plugin transport involved, may be NULL
2730 * @param message the actual message
2731 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2734 process_hello (struct TransportPlugin *plugin,
2735 const struct GNUNET_MessageHeader *message)
2738 struct GNUNET_PeerIdentity target;
2739 const struct GNUNET_HELLO_Message *hello;
2740 struct CheckHelloValidatedContext *chvc;
2741 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2743 hsize = ntohs (message->size);
2744 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2745 (hsize < sizeof (struct GNUNET_MessageHeader)))
2748 return GNUNET_SYSERR;
2750 GNUNET_STATISTICS_update (stats,
2751 gettext_noop ("# HELLOs received for validation"),
2754 /* first, check if load is too high */
2755 if (GNUNET_SCHEDULER_get_load (sched,
2756 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2758 GNUNET_STATISTICS_update (stats,
2759 gettext_noop ("# HELLOs ignored due to high load"),
2764 hello = (const struct GNUNET_HELLO_Message *) message;
2765 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2767 GNUNET_break_op (0);
2768 return GNUNET_SYSERR;
2770 GNUNET_CRYPTO_hash (&publicKey,
2771 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2772 &target.hashPubKey);
2773 if (0 == memcmp (&my_identity,
2775 sizeof (struct GNUNET_PeerIdentity)))
2777 GNUNET_STATISTICS_update (stats,
2778 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
2783 #if DEBUG_TRANSPORT > 1
2784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2785 "Processing `%s' message for `%4s' of size %u\n",
2787 GNUNET_i2s (&target),
2788 GNUNET_HELLO_size(hello));
2790 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2791 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2792 memcpy (&chvc[1], hello, hsize);
2793 GNUNET_CONTAINER_DLL_insert (chvc_head,
2796 /* finally, check if HELLO was previously validated
2797 (continuation will then schedule actual validation) */
2798 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2802 HELLO_VERIFICATION_TIMEOUT,
2803 &check_hello_validated, chvc);
2809 * The peer specified by the given neighbour has timed-out or a plugin
2810 * has disconnected. We may either need to do nothing (other plugins
2811 * still up), or trigger a full disconnect and clean up. This
2812 * function updates our state and does the necessary notifications.
2813 * Also notifies our clients that the neighbour is now officially
2816 * @param n the neighbour list entry for the peer
2817 * @param check should we just check if all plugins
2818 * disconnected or must we ask all plugins to
2822 disconnect_neighbour (struct NeighbourList *n, int check)
2824 struct ReadyList *rpos;
2825 struct NeighbourList *npos;
2826 struct NeighbourList *nprev;
2827 struct MessageQueue *mq;
2828 struct ForeignAddressList *peer_addresses;
2829 struct ForeignAddressList *peer_pos;
2831 if (GNUNET_YES == check)
2834 while (NULL != rpos)
2836 peer_addresses = rpos->addresses;
2837 while (peer_addresses != NULL)
2839 if (GNUNET_YES == peer_addresses->connected)
2840 return; /* still connected */
2841 peer_addresses = peer_addresses->next;
2847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2848 "Disconnecting from `%4s'\n",
2849 GNUNET_i2s (&n->id));
2851 /* remove n from neighbours list */
2854 while ((npos != NULL) && (npos != n))
2859 GNUNET_assert (npos != NULL);
2861 neighbours = n->next;
2863 nprev->next = n->next;
2865 /* notify all clients about disconnect */
2866 if (GNUNET_YES == n->received_pong)
2867 notify_clients_disconnect (&n->id);
2869 /* clean up all plugins, cancel connections and pending transmissions */
2870 while (NULL != (rpos = n->plugins))
2872 n->plugins = rpos->next;
2873 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2874 while (rpos->addresses != NULL)
2876 peer_pos = rpos->addresses;
2877 rpos->addresses = peer_pos->next;
2878 if (peer_pos->connected == GNUNET_YES)
2879 GNUNET_STATISTICS_update (stats,
2880 gettext_noop ("# connected addresses"),
2883 if (GNUNET_YES == peer_pos->validated)
2884 GNUNET_STATISTICS_update (stats,
2885 gettext_noop ("# peer addresses considered valid"),
2888 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
2890 GNUNET_SCHEDULER_cancel (sched,
2891 peer_pos->revalidate_task);
2892 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2894 GNUNET_free(peer_pos);
2899 /* free all messages on the queue */
2900 while (NULL != (mq = n->messages_head))
2902 GNUNET_STATISTICS_update (stats,
2903 gettext_noop ("# bytes in message queue for other peers"),
2904 - (int64_t) mq->message_buf_size,
2906 GNUNET_STATISTICS_update (stats,
2907 gettext_noop ("# bytes discarded due to disconnect"),
2908 mq->message_buf_size,
2910 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2913 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2915 sizeof(struct GNUNET_PeerIdentity)));
2918 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2920 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2921 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2923 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2925 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2926 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2928 if (n->piter != NULL)
2930 GNUNET_PEERINFO_iterate_cancel (n->piter);
2933 /* finally, free n itself */
2934 GNUNET_STATISTICS_update (stats,
2935 gettext_noop ("# active neighbours"),
2943 * We have received a PING message from someone. Need to send a PONG message
2944 * in response to the peer by any means necessary.
2947 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2948 const struct GNUNET_PeerIdentity *peer,
2949 const char *sender_address,
2950 size_t sender_address_len)
2952 struct TransportPlugin *plugin = cls;
2953 struct TransportPingMessage *ping;
2954 struct TransportPongMessage *pong;
2955 struct NeighbourList *n;
2956 struct ReadyList *rl;
2957 struct ForeignAddressList *fal;
2959 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2961 GNUNET_break_op (0);
2962 return GNUNET_SYSERR;
2964 ping = (struct TransportPingMessage *) message;
2965 if (0 != memcmp (&ping->target,
2966 plugin->env.my_identity,
2967 sizeof (struct GNUNET_PeerIdentity)))
2969 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2970 _("Received `%s' message not destined for me!\n"),
2972 return GNUNET_SYSERR;
2975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2976 "Processing `%s' from `%s'\n",
2978 GNUNET_a2s ((const struct sockaddr *)sender_address,
2979 sender_address_len));
2981 GNUNET_STATISTICS_update (stats,
2982 gettext_noop ("# PING messages received"),
2985 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2986 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2987 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2988 pong->purpose.size =
2989 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2991 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2992 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2993 pong->challenge = ping->challenge;
2994 pong->addrlen = htons(sender_address_len);
2995 memcpy(&pong->signer,
2997 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2998 memcpy (&pong[1], sender_address, sender_address_len);
2999 GNUNET_assert (GNUNET_OK ==
3000 GNUNET_CRYPTO_rsa_sign (my_private_key,
3001 &pong->purpose, &pong->signature));
3002 n = find_neighbour(peer);
3004 n = setup_new_neighbour(peer);
3005 /* first try reliable response transmission */
3009 fal = rl->addresses;
3012 if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3015 ntohs (pong->header.size),
3016 TRANSPORT_PONG_PRIORITY,
3017 HELLO_VERIFICATION_TIMEOUT,
3024 GNUNET_STATISTICS_update (stats,
3025 gettext_noop ("# PONGs unicast via reliable transport"),
3035 /* no reliable method found, do multicast */
3036 GNUNET_STATISTICS_update (stats,
3037 gettext_noop ("# PONGs multicast to all available addresses"),
3043 fal = rl->addresses;
3046 transmit_to_peer(NULL, fal,
3047 TRANSPORT_PONG_PRIORITY,
3048 HELLO_VERIFICATION_TIMEOUT,
3050 ntohs(pong->header.size),
3063 * Function called by the plugin for each received message.
3064 * Update data volumes, possibly notify plugins about
3065 * reducing the rate at which they read from the socket
3066 * and generally forward to our receive callback.
3068 * @param cls the "struct TransportPlugin *" we gave to the plugin
3069 * @param peer (claimed) identity of the other peer
3070 * @param message the message, NULL if we only care about
3071 * learning about the delay until we should receive again
3072 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3073 * @param sender_address binary address of the sender (if observed)
3074 * @param sender_address_len number of bytes in sender_address
3075 * @return how long the plugin should wait until receiving more data
3076 * (plugins that do not support this, can ignore the return value)
3078 static struct GNUNET_TIME_Relative
3079 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3080 const struct GNUNET_MessageHeader *message,
3081 unsigned int distance, const char *sender_address,
3082 size_t sender_address_len)
3084 struct ReadyList *service_context;
3085 struct TransportPlugin *plugin = cls;
3086 struct TransportClient *cpos;
3087 struct InboundMessage *im;
3088 struct ForeignAddressList *peer_address;
3090 struct NeighbourList *n;
3091 struct GNUNET_TIME_Relative ret;
3093 n = find_neighbour (peer);
3095 n = setup_new_neighbour (peer);
3096 service_context = n->plugins;
3097 while ((service_context != NULL) && (plugin != service_context->plugin))
3098 service_context = service_context->next;
3099 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3100 if (message != NULL)
3102 peer_address = add_peer_address(n,
3105 sender_address_len);
3106 if (peer_address != NULL)
3108 peer_address->distance = distance;
3109 if (peer_address->connected == GNUNET_NO)
3111 /* FIXME: be careful here to not mark
3112 MULTIPLE addresses as connected! */
3113 peer_address->connected = GNUNET_YES;
3114 GNUNET_STATISTICS_update (stats,
3115 gettext_noop ("# connected addresses"),
3119 peer_address->timeout
3121 GNUNET_TIME_relative_to_absolute
3122 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3123 schedule_next_ping (peer_address);
3125 /* update traffic received amount ... */
3126 msize = ntohs (message->size);
3127 GNUNET_STATISTICS_update (stats,
3128 gettext_noop ("# bytes received from other peers"),
3131 n->distance = distance;
3133 GNUNET_TIME_relative_to_absolute
3134 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3135 GNUNET_SCHEDULER_cancel (sched,
3138 GNUNET_SCHEDULER_add_delayed (sched,
3139 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3140 &neighbour_timeout_task, n);
3141 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3143 /* dropping message due to frequent inbound volume violations! */
3144 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3145 GNUNET_ERROR_TYPE_BULK,
3147 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
3148 n->in_tracker.available_bytes_per_s__,
3149 n->quota_violation_count);
3150 GNUNET_STATISTICS_update (stats,
3151 gettext_noop ("# bandwidth quota violations by other peers"),
3154 return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
3156 switch (ntohs (message->type))
3158 case GNUNET_MESSAGE_TYPE_HELLO:
3159 GNUNET_STATISTICS_update (stats,
3160 gettext_noop ("# HELLO messages received from other peers"),
3163 process_hello (plugin, message);
3165 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3166 handle_ping(plugin, message, peer, sender_address, sender_address_len);
3168 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3169 handle_pong(plugin, message, peer, sender_address, sender_address_len);
3173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3174 "Received message of type %u from `%4s', sending to all clients.\n",
3175 ntohs (message->type), GNUNET_i2s (peer));
3177 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3180 n->quota_violation_count++;
3182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3183 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3184 n->in_tracker.available_bytes_per_s__,
3185 n->quota_violation_count);
3187 /* Discount 32k per violation */
3188 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3193 if (n->quota_violation_count > 0)
3195 /* try to add 32k back */
3196 GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3198 n->quota_violation_count--;
3201 GNUNET_STATISTICS_update (stats,
3202 gettext_noop ("# payload received from other peers"),
3205 /* transmit message to all clients */
3206 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3207 im->header.size = htons (sizeof (struct InboundMessage) + msize);
3208 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3209 im->latency = GNUNET_TIME_relative_hton (n->latency);
3211 memcpy (&im[1], message, msize);
3213 while (cpos != NULL)
3215 transmit_to_client (cpos, &im->header, GNUNET_YES);
3221 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3224 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3225 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3226 (unsigned long long) n->in_tracker.consumption_since_last_update__,
3227 (unsigned int) n->in_tracker.available_bytes_per_s__,
3228 (unsigned long long) ret.value);
3229 GNUNET_STATISTICS_update (stats,
3230 gettext_noop ("# ms throttling suggested"),
3231 (int64_t) ret.value,
3239 * Handle START-message. This is the first message sent to us
3240 * by any client which causes us to add it to our list.
3242 * @param cls closure (always NULL)
3243 * @param client identification of the client
3244 * @param message the actual message
3247 handle_start (void *cls,
3248 struct GNUNET_SERVER_Client *client,
3249 const struct GNUNET_MessageHeader *message)
3251 struct TransportClient *c;
3252 struct ConnectInfoMessage cim;
3253 struct NeighbourList *n;
3256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3257 "Received `%s' request from client\n", "START");
3262 if (c->client == client)
3264 /* client already on our list! */
3266 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3271 c = GNUNET_malloc (sizeof (struct TransportClient));
3275 if (our_hello != NULL)
3278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3279 "Sending our own `%s' to new client\n", "HELLO");
3281 transmit_to_client (c,
3282 (const struct GNUNET_MessageHeader *) our_hello,
3284 /* tell new client about all existing connections */
3285 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3286 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3290 if (GNUNET_YES == n->received_pong)
3293 cim.latency = GNUNET_TIME_relative_hton (n->latency);
3294 cim.distance = htonl (n->distance);
3295 transmit_to_client (c, &cim.header, GNUNET_NO);
3300 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3305 * Handle HELLO-message.
3307 * @param cls closure (always NULL)
3308 * @param client identification of the client
3309 * @param message the actual message
3312 handle_hello (void *cls,
3313 struct GNUNET_SERVER_Client *client,
3314 const struct GNUNET_MessageHeader *message)
3318 GNUNET_STATISTICS_update (stats,
3319 gettext_noop ("# HELLOs received from clients"),
3322 ret = process_hello (NULL, message);
3323 GNUNET_SERVER_receive_done (client, ret);
3328 * Handle SEND-message.
3330 * @param cls closure (always NULL)
3331 * @param client identification of the client
3332 * @param message the actual message
3335 handle_send (void *cls,
3336 struct GNUNET_SERVER_Client *client,
3337 const struct GNUNET_MessageHeader *message)
3339 struct TransportClient *tc;
3340 struct NeighbourList *n;
3341 const struct OutboundMessage *obm;
3342 const struct GNUNET_MessageHeader *obmm;
3346 size = ntohs (message->size);
3348 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3351 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3354 GNUNET_STATISTICS_update (stats,
3355 gettext_noop ("# payload received for other peers"),
3358 obm = (const struct OutboundMessage *) message;
3360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3361 "Received `%s' request from client with target `%4s'\n",
3362 "SEND", GNUNET_i2s (&obm->peer));
3364 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3365 msize = ntohs (obmm->size);
3366 if (size != msize + sizeof (struct OutboundMessage))
3369 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3372 n = find_neighbour (&obm->peer);
3374 n = setup_new_neighbour (&obm->peer);
3376 while ((tc != NULL) && (tc->client != client))
3380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3381 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3383 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3385 transmit_to_peer (tc, NULL, ntohl (obm->priority),
3386 GNUNET_TIME_relative_ntoh (obm->timeout),
3388 ntohs (obmm->size), GNUNET_NO, n);
3389 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3394 * Handle SET_QUOTA-message.
3396 * @param cls closure (always NULL)
3397 * @param client identification of the client
3398 * @param message the actual message
3401 handle_set_quota (void *cls,
3402 struct GNUNET_SERVER_Client *client,
3403 const struct GNUNET_MessageHeader *message)
3405 const struct QuotaSetMessage *qsm =
3406 (const struct QuotaSetMessage *) message;
3407 struct NeighbourList *n;
3409 GNUNET_STATISTICS_update (stats,
3410 gettext_noop ("# SET QUOTA messages received"),
3413 n = find_neighbour (&qsm->peer);
3416 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3417 GNUNET_STATISTICS_update (stats,
3418 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3425 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3427 (unsigned int) ntohl (qsm->quota.value__),
3428 (unsigned int) n->in_tracker.available_bytes_per_s__,
3429 GNUNET_i2s (&qsm->peer));
3431 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3433 if (0 == ntohl (qsm->quota.value__))
3434 disconnect_neighbour (n, GNUNET_NO);
3435 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3440 * Take the given address and append it to the set of results send back to
3443 * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3444 * @param address the resolved name, NULL to indicate the last response
3447 transmit_address_to_client (void *cls, const char *address)
3449 struct GNUNET_SERVER_TransmitContext *tc = cls;
3452 if (NULL == address)
3455 slen = strlen (address) + 1;
3456 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3457 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3458 if (NULL == address)
3459 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3464 * Handle AddressLookup-message.
3466 * @param cls closure (always NULL)
3467 * @param client identification of the client
3468 * @param message the actual message
3471 handle_address_lookup (void *cls,
3472 struct GNUNET_SERVER_Client *client,
3473 const struct GNUNET_MessageHeader *message)
3475 const struct AddressLookupMessage *alum;
3476 struct TransportPlugin *lsPlugin;
3477 const char *nameTransport;
3478 const char *address;
3480 struct GNUNET_SERVER_TransmitContext *tc;
3481 struct GNUNET_TIME_Absolute timeout;
3482 struct GNUNET_TIME_Relative rtimeout;
3485 size = ntohs (message->size);
3486 if (size < sizeof (struct AddressLookupMessage))
3488 GNUNET_break_op (0);
3489 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3492 alum = (const struct AddressLookupMessage *) message;
3493 uint32_t addressLen = ntohl (alum->addrlen);
3494 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3496 GNUNET_break_op (0);
3497 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3500 address = (const char *) &alum[1];
3501 nameTransport = (const char *) &address[addressLen];
3503 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3505 GNUNET_break_op (0);
3506 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3509 timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3510 rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3511 numeric = ntohl (alum->numeric_only);
3512 lsPlugin = find_transport (nameTransport);
3513 if (NULL == lsPlugin)
3515 tc = GNUNET_SERVER_transmit_context_create (client);
3516 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3517 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3518 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3521 tc = GNUNET_SERVER_transmit_context_create (client);
3522 lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
3524 address, addressLen,
3527 &transmit_address_to_client, tc);
3531 * List of handlers for the messages understood by this
3534 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3535 {&handle_start, NULL,
3536 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3537 {&handle_hello, NULL,
3538 GNUNET_MESSAGE_TYPE_HELLO, 0},
3539 {&handle_send, NULL,
3540 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3541 {&handle_set_quota, NULL,
3542 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3543 {&handle_address_lookup, NULL,
3544 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3551 * Setup the environment for this plugin.
3554 create_environment (struct TransportPlugin *plug)
3556 plug->env.cfg = cfg;
3557 plug->env.sched = sched;
3558 plug->env.my_identity = &my_identity;
3559 plug->env.cls = plug;
3560 plug->env.receive = &plugin_env_receive;
3561 plug->env.notify_address = &plugin_env_notify_address;
3562 plug->env.max_connections = max_connect_per_transport;
3563 plug->env.stats = stats;
3568 * Start the specified transport (load the plugin).
3571 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3573 struct TransportPlugin *plug;
3576 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3577 _("Loading `%s' transport plugin\n"), name);
3578 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3579 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3580 create_environment (plug);
3581 plug->short_name = GNUNET_strdup (name);
3582 plug->lib_name = libname;
3583 plug->next = plugins;
3585 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3586 if (plug->api == NULL)
3588 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3589 _("Failed to load transport plugin for `%s'\n"), name);
3590 GNUNET_free (plug->short_name);
3591 plugins = plug->next;
3592 GNUNET_free (libname);
3599 * Called whenever a client is disconnected. Frees our
3600 * resources associated with that client.
3602 * @param cls closure
3603 * @param client identification of the client
3606 client_disconnect_notification (void *cls,
3607 struct GNUNET_SERVER_Client *client)
3609 struct TransportClient *pos;
3610 struct TransportClient *prev;
3611 struct ClientMessageQueueEntry *mqe;
3616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3617 "Client disconnected, cleaning up.\n");
3621 while ((pos != NULL) && (pos->client != client))
3628 while (NULL != (mqe = pos->message_queue_head))
3630 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3631 pos->message_queue_tail,
3633 pos->message_count--;
3637 clients = pos->next;
3639 prev->next = pos->next;
3640 if (GNUNET_YES == pos->tcs_pending)
3645 if (pos->th != NULL)
3647 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3650 GNUNET_break (0 == pos->message_count);
3656 * Iterator to free entries in the validation_map.
3658 * @param cls closure (unused)
3659 * @param key current key code
3660 * @param value value in the hash map (validation to abort)
3661 * @return GNUNET_YES (always)
3664 abort_validation (void *cls,
3665 const GNUNET_HashCode * key,
3668 struct ValidationEntry *va = value;
3670 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3671 GNUNET_free (va->transport_name);
3678 * Function called when the service shuts down. Unloads our plugins
3679 * and cancels pending validations.
3681 * @param cls closure, unused
3682 * @param tc task context (unused)
3685 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3687 struct TransportPlugin *plug;
3688 struct OwnAddressList *al;
3689 struct CheckHelloValidatedContext *chvc;
3691 while (neighbours != NULL)
3692 disconnect_neighbour (neighbours, GNUNET_NO);
3694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3695 "Transport service is unloading plugins...\n");
3697 while (NULL != (plug = plugins))
3699 plugins = plug->next;
3700 if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
3702 GNUNET_SCHEDULER_cancel (plug->env.sched,
3703 plug->address_update_task);
3704 plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
3706 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3707 GNUNET_free (plug->lib_name);
3708 GNUNET_free (plug->short_name);
3709 while (NULL != (al = plug->addresses))
3711 plug->addresses = al->next;
3716 if (my_private_key != NULL)
3717 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3718 GNUNET_free_non_null (our_hello);
3720 /* free 'chvc' data structure */
3721 while (NULL != (chvc = chvc_head))
3723 chvc_head = chvc->next;
3724 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3729 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3732 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3733 validation_map = NULL;
3736 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3743 * Initiate transport service.
3745 * @param cls closure
3746 * @param s scheduler to use
3747 * @param serv the initialized server
3748 * @param c configuration to use
3752 struct GNUNET_SCHEDULER_Handle *s,
3753 struct GNUNET_SERVER_Handle *serv,
3754 const struct GNUNET_CONFIGURATION_Handle *c)
3759 unsigned long long tneigh;
3764 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3765 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3766 /* parse configuration */
3768 GNUNET_CONFIGURATION_get_value_number (c,
3773 GNUNET_CONFIGURATION_get_value_filename (c,
3775 "HOSTKEY", &keyfile)))
3777 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3779 ("Transport service is lacking key configuration settings. Exiting.\n"));
3780 GNUNET_SCHEDULER_shutdown (s);
3783 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3786 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3787 validation_map = NULL;
3790 max_connect_per_transport = (uint32_t) tneigh;
3791 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3792 GNUNET_free (keyfile);
3793 if (my_private_key == NULL)
3795 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3797 ("Transport service could not access hostkey. Exiting.\n"));
3798 GNUNET_SCHEDULER_shutdown (s);
3801 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3804 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3805 validation_map = NULL;
3808 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3809 GNUNET_CRYPTO_hash (&my_public_key,
3810 sizeof (my_public_key), &my_identity.hashPubKey);
3811 /* setup notification */
3813 GNUNET_SERVER_disconnect_notify (server,
3814 &client_disconnect_notification, NULL);
3815 /* load plugins... */
3818 GNUNET_CONFIGURATION_get_value_string (c,
3819 "TRANSPORT", "PLUGINS", &plugs))
3821 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3822 _("Starting transport plugins `%s'\n"), plugs);
3823 pos = strtok (plugs, " ");
3826 start_transport (server, pos);
3828 pos = strtok (NULL, " ");
3830 GNUNET_free (plugs);
3832 GNUNET_SCHEDULER_add_delayed (sched,
3833 GNUNET_TIME_UNIT_FOREVER_REL,
3834 &shutdown_task, NULL);
3839 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3841 /* process client requests */
3842 GNUNET_SERVER_add_handlers (server, handlers);
3847 * The main function for the transport service.
3849 * @param argc number of arguments from the command line
3850 * @param argv command line arguments
3851 * @return 0 ok, 1 on error
3854 main (int argc, char *const *argv)
3856 return (GNUNET_OK ==
3857 GNUNET_SERVICE_run (argc,
3860 GNUNET_SERVICE_OPTION_NONE,
3861 &run, NULL)) ? 0 : 1;
3864 /* end of gnunet-service-transport.c */