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 * - bi-directional nature of TCP is not exploited
30 * - This code uses 'GNUNET_a2s' for debug printing in many places,
31 * which is technically wrong since it assumes we have IP+Port
32 * (v4/v6) addresses. Once we add transports like http or smtp
33 * this will have to be changed!
36 #include "gnunet_client_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "gnunet_constants.h"
39 #include "gnunet_getopt_lib.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_os_lib.h"
42 #include "gnunet_peerinfo_service.h"
43 #include "gnunet_plugin_lib.h"
44 #include "gnunet_protocols.h"
45 #include "gnunet_service_lib.h"
46 #include "gnunet_signatures.h"
47 #include "plugin_transport.h"
48 #include "transport.h"
51 * Should we do some additional checks (to validate behavior
54 #define EXTRA_CHECKS GNUNET_YES
57 * How many messages can we have pending for a given client process
58 * before we start to drop incoming messages? We typically should
59 * have only one client and so this would be the primary buffer for
60 * messages, so the number should be chosen rather generously.
62 * The expectation here is that most of the time the queue is large
63 * enough so that a drop is virtually never required.
65 #define MAX_PENDING 128
68 * How often should we try to reconnect to a peer using a particular
69 * transport plugin before giving up? Note that the plugin may be
70 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
72 #define MAX_CONNECT_RETRY 3
75 * Limit on the number of ready-to-run tasks when validating
76 * HELLOs. If more tasks are ready to run, we will drop
77 * HELLOs instead of validating them.
79 #define MAX_HELLO_LOAD 4
82 * How often must a peer violate bandwidth quotas before we start
83 * to simply drop its messages?
85 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
88 * How long until a HELLO verification attempt should time out?
89 * Must be rather small, otherwise a partially successful HELLO
90 * validation (some addresses working) might not be available
91 * before a client's request for a connection fails for good.
92 * Besides, if a single request to an address takes a long time,
93 * then the peer is unlikely worthwhile anyway.
95 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
98 * How long will we allow sending of a ping to be delayed?
100 #define TRANSPORT_DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
103 * Priority to use for PONG messages.
105 #define TRANSPORT_PONG_PRIORITY 4
108 * How often do we re-add (cheaper) plugins to our list of plugins
109 * to try for a given connected peer?
111 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
114 * After how long do we expire an address in a HELLO that we just
115 * validated? This value is also used for our own addresses when we
118 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
122 * How long before an existing address expires should we again try to
123 * validate it? Must be (significantly) smaller than
124 * HELLO_ADDRESS_EXPIRATION.
126 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
129 * Maximum frequency for re-evaluating latencies for all transport addresses.
131 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
134 * Maximum frequency for re-evaluating latencies for connected addresses.
136 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
140 * List of addresses of other peers
142 struct ForeignAddressList
145 * This is a linked list.
147 struct ForeignAddressList *next;
150 * Which ready list does this entry belong to.
152 struct ReadyList *ready_list;
155 * How long until we auto-expire this address (unless it is
156 * re-confirmed by the transport)?
158 struct GNUNET_TIME_Absolute expires;
161 * Task used to re-validate addresses, updates latencies and
164 GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
177 * What was the last latency observed for this address, plugin and peer?
179 struct GNUNET_TIME_Relative latency;
182 * If we did not successfully transmit a message to the given peer
183 * via this connection during the specified time, we should consider
184 * the connection to be dead. This is used in the case that a TCP
185 * transport simply stalls writing to the stream but does not
186 * formerly get a signal that the other peer died.
188 struct GNUNET_TIME_Absolute timeout;
191 * How often have we tried to connect using this plugin? Used to
192 * discriminate against addresses that do not work well.
193 * FIXME: not yet used, but should be!
195 unsigned int connect_attempts;
198 * DV distance to this peer (1 if no DV is used).
199 * FIXME: need to set this from transport plugins!
204 * Have we ever estimated the latency of this address? Used to
205 * ensure that the first time we add an address, we immediately
211 * Are we currently connected via this address? The first time we
212 * successfully transmit or receive data to a peer via a particular
213 * address, we set this to GNUNET_YES. If we later get an error
214 * (disconnect notification, transmission failure, timeout), we set
215 * it back to GNUNET_NO.
220 * Is this plugin currently busy transmitting to the specific target?
221 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
222 * messages do not count as 'in transmit'.
227 * Has this address been validated yet?
235 * Entry in linked list of network addresses for ourselves.
237 struct OwnAddressList
240 * This is a linked list.
242 struct OwnAddressList *next;
245 * The address, actually a pointer to the end
246 * of this struct. Do not free!
251 * How long until we auto-expire this address (unless it is
252 * re-confirmed by the transport)?
254 struct GNUNET_TIME_Absolute expires;
265 * Entry in linked list of all of our plugins.
267 struct TransportPlugin
271 * This is a linked list.
273 struct TransportPlugin *next;
276 * API of the transport as returned by the plugin's
277 * initialization function.
279 struct GNUNET_TRANSPORT_PluginFunctions *api;
282 * Short name for the plugin (i.e. "tcp").
287 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
292 * List of our known addresses for this transport.
294 struct OwnAddressList *addresses;
297 * Environment this transport service is using
300 struct GNUNET_TRANSPORT_PluginEnvironment env;
303 * ID of task that is used to clean up expired addresses.
305 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
308 * Set to GNUNET_YES if we need to scrap the existing
309 * list of "addresses" and start fresh when we receive
310 * the next address update from a transport. Set to
311 * GNUNET_NO if we should just add the new address
312 * to the list and wait for the commit call.
318 struct NeighbourList;
321 * For each neighbour we keep a list of messages
322 * that we still want to transmit to the neighbour.
328 * This is a doubly linked list.
330 struct MessageQueue *next;
333 * This is a doubly linked list.
335 struct MessageQueue *prev;
338 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
339 * stuck together in memory. Allocated at the end of this struct.
341 const char *message_buf;
344 * Size of the message buf
346 size_t message_buf_size;
349 * Client responsible for queueing the message;
350 * used to check that a client has no two messages
351 * pending for the same target. Can be NULL.
353 struct TransportClient *client;
356 * Using which specific address should we send this message?
358 struct ForeignAddressList *specific_address;
361 * Peer ID of the Neighbour this entry belongs to.
363 struct GNUNET_PeerIdentity neighbour_id;
366 * Plugin that we used for the transmission.
367 * NULL until we scheduled a transmission.
369 struct TransportPlugin *plugin;
372 * At what time should we fail?
374 struct GNUNET_TIME_Absolute timeout;
377 * Internal message of the transport system that should not be
378 * included in the usual SEND-SEND_OK transmission confirmation
379 * traffic management scheme. Typically, "internal_msg" will
380 * be set whenever "client" is NULL (but it is not strictly
386 * How important is the message?
388 unsigned int priority;
394 * For a given Neighbour, which plugins are available
395 * to talk to this peer and what are their costs?
400 * This is a linked list.
402 struct ReadyList *next;
405 * Which of our transport plugins does this entry
408 struct TransportPlugin *plugin;
411 * Transport addresses, latency, and readiness for
412 * this particular plugin.
414 struct ForeignAddressList *addresses;
417 * To which neighbour does this ready list belong to?
419 struct NeighbourList *neighbour;
425 * Entry in linked list of all of our current neighbours.
431 * This is a linked list.
433 struct NeighbourList *next;
436 * Which of our transports is connected to this peer
437 * and what is their status?
439 struct ReadyList *plugins;
442 * Head of list of messages we would like to send to this peer;
443 * must contain at most one message per client.
445 struct MessageQueue *messages_head;
448 * Tail of list of messages we would like to send to this peer; must
449 * contain at most one message per client.
451 struct MessageQueue *messages_tail;
454 * Context for peerinfo iteration.
455 * NULL after we are done processing peerinfo's information.
457 struct GNUNET_PEERINFO_IteratorContext *piter;
460 * Public key for this peer. Valid only if the respective flag is set below.
462 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
465 * Identity of this neighbour.
467 struct GNUNET_PeerIdentity id;
470 * ID of task scheduled to run when this peer is about to
471 * time out (will free resources associated with the peer).
473 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
476 * ID of task scheduled to run when we should retry transmitting
477 * the head of the message queue. Actually triggered when the
478 * transmission is timing out (we trigger instantly when we have
479 * a chance of success).
481 GNUNET_SCHEDULER_TaskIdentifier retry_task;
484 * How long until we should consider this peer dead
485 * (if we don't receive another message in the
488 struct GNUNET_TIME_Absolute peer_timeout;
491 * Tracker for inbound bandwidth.
493 struct GNUNET_BANDWIDTH_Tracker in_tracker;
496 * The latency we have seen for this particular address for
497 * this particular peer. This latency may have been calculated
498 * over multiple transports. This value reflects how long it took
499 * us to receive a response when SENDING via this particular
500 * transport/neighbour/address combination!
502 * FIXME: we need to periodically send PINGs to update this
503 * latency (at least more often than the current "huge" (11h?)
506 struct GNUNET_TIME_Relative latency;
509 * How often has the other peer (recently) violated the
510 * inbound traffic limit? Incremented by 10 per violation,
511 * decremented by 1 per non-violation (for each
514 unsigned int quota_violation_count;
517 * DV distance to this peer (1 if no DV is used).
522 * Have we seen an PONG from this neighbour in the past (and
523 * not had a disconnect since)?
528 * Do we have a valid public key for this neighbour?
530 int public_key_valid;
535 * Message used to ask a peer to validate receipt (to check an address
538 struct TransportPingMessage
542 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
544 struct GNUNET_MessageHeader header;
547 * Random challenge number (in network byte order).
549 uint32_t challenge GNUNET_PACKED;
552 * Who is the intended recipient?
554 struct GNUNET_PeerIdentity target;
560 * Message used to validate a HELLO. The challenge is included in the
561 * confirmation to make matching of replies to requests possible. The
562 * signature signs the original challenge number, our public key, the
563 * sender's address (so that the sender can check that the address we
564 * saw is plausible for him and possibly detect a MiM attack) and a
565 * timestamp (to limit replay).<p>
567 * This message is followed by the address of the
568 * client that we are observing (which is part of what
571 struct TransportPongMessage
575 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
577 struct GNUNET_MessageHeader header;
580 * For padding, always zero.
582 uint32_t reserved GNUNET_PACKED;
587 struct GNUNET_CRYPTO_RsaSignature signature;
590 * What are we signing and why?
592 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
595 * Random challenge number (in network byte order).
597 uint32_t challenge GNUNET_PACKED;
600 * Who signed this message?
602 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
605 * Size of address appended to this message
613 * Linked list of messages to be transmitted to the client. Each
614 * entry is followed by the actual message.
616 struct ClientMessageQueueEntry
619 * This is a doubly-linked list.
621 struct ClientMessageQueueEntry *next;
624 * This is a doubly-linked list.
626 struct ClientMessageQueueEntry *prev;
631 * Client connected to the transport service.
633 struct TransportClient
637 * This is a linked list.
639 struct TransportClient *next;
642 * Handle to the client.
644 struct GNUNET_SERVER_Client *client;
647 * Linked list of messages yet to be transmitted to
650 struct ClientMessageQueueEntry *message_queue_head;
653 * Tail of linked list of messages yet to be transmitted to the
656 struct ClientMessageQueueEntry *message_queue_tail;
659 * Current transmit request handle.
661 struct GNUNET_CONNECTION_TransmitHandle *th;
664 * Is a call to "transmit_send_continuation" pending? If so, we
665 * must not free this struct (even if the corresponding client
666 * disconnects) and instead only remove it from the linked list and
667 * set the "client" field to NULL.
672 * Length of the list of messages pending for this client.
674 unsigned int message_count;
680 * Entry in map of all HELLOs awaiting validation.
682 struct ValidationEntry
686 * The address, actually a pointer to the end
687 * of this struct. Do not free!
692 * Name of the transport.
694 char *transport_name;
697 * The public key of the peer.
699 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
702 * ID of task that will clean up this entry if we don't succeed
703 * with the validation first.
705 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
708 * At what time did we send this validation?
710 struct GNUNET_TIME_Absolute send_time;
718 * Challenge number we used.
726 * Context of currently active requests to peerinfo
727 * for validation of HELLOs.
729 struct CheckHelloValidatedContext
733 * This is a doubly-linked list.
735 struct CheckHelloValidatedContext *next;
738 * This is a doubly-linked list.
740 struct CheckHelloValidatedContext *prev;
743 * Hello that we are validating.
745 const struct GNUNET_HELLO_Message *hello;
748 * Context for peerinfo iteration.
749 * NULL after we are done processing peerinfo's information.
751 struct GNUNET_PEERINFO_IteratorContext *piter;
754 * Was a HELLO known for this peer to peerinfo?
764 static struct GNUNET_HELLO_Message *our_hello;
767 * "version" of "our_hello". Used to see if a given neighbour has
768 * already been sent the latest version of our HELLO message.
770 static unsigned int our_hello_version;
775 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
780 static struct GNUNET_PeerIdentity my_identity;
785 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
790 struct GNUNET_SCHEDULER_Handle *sched;
795 const struct GNUNET_CONFIGURATION_Handle *cfg;
798 * Linked list of all clients to this service.
800 static struct TransportClient *clients;
803 * All loaded plugins.
805 static struct TransportPlugin *plugins;
810 static struct GNUNET_SERVER_Handle *server;
813 * All known neighbours and their HELLOs.
815 static struct NeighbourList *neighbours;
818 * Number of neighbours we'd like to have.
820 static uint32_t max_connect_per_transport;
823 * Head of linked list.
825 static struct CheckHelloValidatedContext *chvc_head;
828 * Tail of linked list.
830 static struct CheckHelloValidatedContext *chvc_tail;
833 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
834 * of the given peer that we are currently validating).
836 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
839 * Handle for reporting statistics.
841 static struct GNUNET_STATISTICS_Handle *stats;
845 * The peer specified by the given neighbour has timed-out or a plugin
846 * has disconnected. We may either need to do nothing (other plugins
847 * still up), or trigger a full disconnect and clean up. This
848 * function updates our state and do the necessary notifications.
849 * Also notifies our clients that the neighbour is now officially
852 * @param n the neighbour list entry for the peer
853 * @param check should we just check if all plugins
854 * disconnected or must we ask all plugins to
857 static void disconnect_neighbour (struct NeighbourList *n, int check);
860 * Check the ready list for the given neighbour and if a plugin is
861 * ready for transmission (and if we have a message), do so!
863 * @param neighbour target peer for which to transmit
865 static void try_transmission_to_peer (struct NeighbourList *neighbour);
869 * Find an entry in the neighbour list for a particular peer.
870 * if sender_address is not specified (NULL) then return the
871 * first matching entry. If sender_address is specified, then
872 * make sure that the address and address_len also matches.
874 * FIXME: This description does not fit the function.
876 * @return NULL if not found.
878 static struct NeighbourList *
879 find_neighbour (const struct GNUNET_PeerIdentity *key)
881 struct NeighbourList *head = neighbours;
883 while ((head != NULL) &&
884 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
891 * Find an entry in the transport list for a particular transport.
893 * @return NULL if not found.
895 static struct TransportPlugin *
896 find_transport (const char *short_name)
898 struct TransportPlugin *head = plugins;
899 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
906 * Function called to notify a client about the socket being ready to
907 * queue more data. "buf" will be NULL and "size" zero if the socket
908 * was closed for writing in the meantime.
911 * @param size number of bytes available in buf
912 * @param buf where the callee should write the message
913 * @return number of bytes written to buf
916 transmit_to_client_callback (void *cls, size_t size, void *buf)
918 struct TransportClient *client = cls;
919 struct ClientMessageQueueEntry *q;
922 const struct GNUNET_MessageHeader *msg;
928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
929 "Transmission to client failed, closing connection.\n");
930 /* fatal error with client, free message queue! */
931 while (NULL != (q = client->message_queue_head))
933 GNUNET_STATISTICS_update (stats,
934 gettext_noop ("# bytes discarded (could not transmit to client)"),
935 ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
937 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
938 client->message_queue_tail,
942 client->message_count = 0;
947 while (NULL != (q = client->message_queue_head))
949 msg = (const struct GNUNET_MessageHeader *) &q[1];
950 msize = ntohs (msg->size);
951 if (msize + tsize > size)
954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955 "Transmitting message of type %u to client.\n",
958 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
959 client->message_queue_tail,
961 memcpy (&cbuf[tsize], msg, msize);
964 client->message_count--;
968 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
969 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
971 GNUNET_TIME_UNIT_FOREVER_REL,
972 &transmit_to_client_callback,
974 GNUNET_assert (client->th != NULL);
981 * Send the specified message to the specified client. Since multiple
982 * messages may be pending for the same client at a time, this code
983 * makes sure that no message is lost.
985 * @param client client to transmit the message to
986 * @param msg the message to send
987 * @param may_drop can this message be dropped if the
988 * message queue for this client is getting far too large?
991 transmit_to_client (struct TransportClient *client,
992 const struct GNUNET_MessageHeader *msg, int may_drop)
994 struct ClientMessageQueueEntry *q;
997 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
999 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1001 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1002 client->message_count, MAX_PENDING);
1003 /* TODO: call to statistics... */
1006 msize = ntohs (msg->size);
1007 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1008 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1009 memcpy (&q[1], msg, msize);
1010 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1011 client->message_queue_tail,
1012 client->message_queue_tail,
1014 client->message_count++;
1015 if (client->th == NULL)
1017 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1019 GNUNET_TIME_UNIT_FOREVER_REL,
1020 &transmit_to_client_callback,
1022 GNUNET_assert (client->th != NULL);
1028 * Transmit a 'SEND_OK' notification to the given client for the
1031 * @param client who to notify
1032 * @param n neighbour to notify about
1033 * @param result status code for the transmission request
1036 transmit_send_ok (struct TransportClient *client,
1037 struct NeighbourList *n,
1040 struct SendOkMessage send_ok_msg;
1042 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1043 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1044 send_ok_msg.success = htonl (result);
1045 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1046 send_ok_msg.peer = n->id;
1047 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1052 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1053 * upon "completion" of a send request. This tells the API
1054 * that it is now legal to send another message to the given
1057 * @param cls closure, identifies the entry on the
1058 * message queue that was transmitted and the
1059 * client responsible for queueing the message
1060 * @param target the peer receiving the message
1061 * @param result GNUNET_OK on success, if the transmission
1062 * failed, we should not tell the client to transmit
1066 transmit_send_continuation (void *cls,
1067 const struct GNUNET_PeerIdentity *target,
1070 struct MessageQueue *mq = cls;
1071 struct NeighbourList *n;
1073 GNUNET_STATISTICS_update (stats,
1074 gettext_noop ("# bytes pending with plugins"),
1075 -mq->message_buf_size,
1077 if (result == GNUNET_OK)
1079 GNUNET_STATISTICS_update (stats,
1080 gettext_noop ("# bytes successfully transmitted by plugins"),
1081 mq->message_buf_size,
1086 GNUNET_STATISTICS_update (stats,
1087 gettext_noop ("# bytes with transmission failure by plugins"),
1088 mq->message_buf_size,
1091 n = find_neighbour(&mq->neighbour_id);
1092 GNUNET_assert (n != NULL);
1093 if (mq->specific_address != NULL)
1095 if (result == GNUNET_OK)
1097 mq->specific_address->timeout =
1098 GNUNET_TIME_relative_to_absolute
1099 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1100 if (mq->specific_address->connected != GNUNET_YES)
1102 GNUNET_STATISTICS_update (stats,
1103 gettext_noop ("# connected addresses"),
1106 mq->specific_address->connected = GNUNET_YES;
1111 if (mq->specific_address->connected != GNUNET_NO)
1113 GNUNET_STATISTICS_update (stats,
1114 gettext_noop ("# connected addresses"),
1117 mq->specific_address->connected = GNUNET_NO;
1120 if (! mq->internal_msg)
1121 mq->specific_address->in_transmit = GNUNET_NO;
1123 if (mq->client != NULL)
1124 transmit_send_ok (mq->client, n, result);
1126 try_transmission_to_peer (n);
1131 * Find an address in any of the available transports for
1132 * the given neighbour that would be good for message
1133 * transmission. This is essentially the transport selection
1136 * @param neighbour for whom to select an address
1137 * @return selected address, NULL if we have none
1139 struct ForeignAddressList *
1140 find_ready_address(struct NeighbourList *neighbour)
1142 struct ReadyList *head = neighbour->plugins;
1143 struct ForeignAddressList *addresses;
1144 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1145 struct ForeignAddressList *best_address;
1147 best_address = NULL;
1148 while (head != NULL)
1150 addresses = head->addresses;
1151 while (addresses != NULL)
1153 if ( (addresses->timeout.value < now.value) &&
1154 (addresses->connected == GNUNET_YES) )
1157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1158 "Marking long-time inactive connection to `%4s' as down.\n",
1159 GNUNET_i2s (&neighbour->id));
1161 GNUNET_STATISTICS_update (stats,
1162 gettext_noop ("# connected addresses"),
1165 addresses->connected = GNUNET_NO;
1167 addresses = addresses->next;
1170 addresses = head->addresses;
1171 while (addresses != NULL)
1173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1174 "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1175 GNUNET_a2s (addresses->addr,
1176 addresses->addrlen),
1177 GNUNET_i2s (&neighbour->id),
1178 addresses->connected,
1179 addresses->in_transmit,
1180 addresses->validated,
1181 addresses->connect_attempts,
1182 (unsigned long long) addresses->timeout.value,
1183 (unsigned int) addresses->distance);
1184 if ( ( (best_address == NULL) ||
1185 (addresses->connected == GNUNET_YES) ||
1186 (best_address->connected == GNUNET_NO) ) &&
1187 (addresses->in_transmit == GNUNET_NO) &&
1188 ( (best_address == NULL) ||
1189 (addresses->latency.value < best_address->latency.value)) )
1190 best_address = addresses;
1191 /* FIXME: also give lower-latency addresses that are not
1192 connected a chance some times... */
1193 addresses = addresses->next;
1197 if (best_address != NULL)
1200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1201 "Best address found has latency of %llu ms.\n",
1202 best_address->latency.value);
1207 GNUNET_STATISTICS_update (stats,
1208 gettext_noop ("# transmission attempts failed (no address)"),
1212 return best_address;
1218 * We should re-try transmitting to the given peer,
1219 * hopefully we've learned something in the meantime.
1222 retry_transmission_task (void *cls,
1223 const struct GNUNET_SCHEDULER_TaskContext *tc)
1225 struct NeighbourList *n = cls;
1227 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1228 try_transmission_to_peer (n);
1233 * Check the ready list for the given neighbour and if a plugin is
1234 * ready for transmission (and if we have a message), do so!
1236 * @param neighbour target peer for which to transmit
1239 try_transmission_to_peer (struct NeighbourList *neighbour)
1241 struct ReadyList *rl;
1242 struct MessageQueue *mq;
1243 struct GNUNET_TIME_Relative timeout;
1245 if (neighbour->messages_head == NULL)
1247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248 "Transmission queue for `%4s' is empty\n",
1249 GNUNET_i2s (&neighbour->id));
1250 return; /* nothing to do */
1253 mq = neighbour->messages_head;
1254 /* FIXME: support bi-directional use of TCP */
1255 if (mq->specific_address == NULL)
1257 mq->specific_address = find_ready_address(neighbour);
1258 GNUNET_STATISTICS_update (stats,
1259 gettext_noop ("# transport selected peer address freely"),
1263 if (mq->specific_address == NULL)
1265 GNUNET_STATISTICS_update (stats,
1266 gettext_noop ("# transport failed to selected peer address"),
1269 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1270 if (timeout.value == 0)
1273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1274 "No destination address available to transmit message of size %u to peer `%4s'\n",
1275 mq->message_buf_size,
1276 GNUNET_i2s (&mq->neighbour_id));
1278 GNUNET_STATISTICS_update (stats,
1279 gettext_noop ("# bytes in message queue for other peers"),
1280 -mq->message_buf_size,
1282 GNUNET_STATISTICS_update (stats,
1283 gettext_noop ("# bytes discarded (no destination address available)"),
1284 mq->message_buf_size,
1286 if (mq->client != NULL)
1287 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1288 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1289 neighbour->messages_tail,
1292 return; /* nobody ready */
1294 GNUNET_STATISTICS_update (stats,
1295 gettext_noop ("# message delivery deferred (no address)"),
1298 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1299 GNUNET_SCHEDULER_cancel (sched,
1300 neighbour->retry_task);
1301 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1303 &retry_transmission_task,
1306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1307 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1308 mq->message_buf_size,
1309 GNUNET_i2s (&mq->neighbour_id),
1312 /* FIXME: might want to trigger peerinfo lookup here
1313 (unless that's already pending...) */
1316 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1317 neighbour->messages_tail,
1319 if (mq->specific_address->connected == GNUNET_NO)
1320 mq->specific_address->connect_attempts++;
1321 rl = mq->specific_address->ready_list;
1322 mq->plugin = rl->plugin;
1323 if (!mq->internal_msg)
1324 mq->specific_address->in_transmit = GNUNET_YES;
1326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1327 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1328 mq->message_buf_size,
1329 GNUNET_i2s (&neighbour->id),
1330 GNUNET_a2s (mq->specific_address->addr,
1331 mq->specific_address->addrlen),
1332 rl->plugin->short_name);
1334 GNUNET_STATISTICS_update (stats,
1335 gettext_noop ("# bytes in message queue for other peers"),
1336 -mq->message_buf_size,
1338 GNUNET_STATISTICS_update (stats,
1339 gettext_noop ("# bytes pending with plugins"),
1340 mq->message_buf_size,
1342 rl->plugin->api->send (rl->plugin->api->cls,
1345 mq->message_buf_size,
1347 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1348 mq->specific_address->addr,
1349 mq->specific_address->addrlen,
1350 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1351 &transmit_send_continuation, mq);
1356 * Send the specified message to the specified peer.
1358 * @param client source of the transmission request (can be NULL)
1359 * @param peer_address ForeignAddressList where we should send this message
1360 * @param priority how important is the message
1361 * @param timeout how long do we have to transmit?
1362 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1363 * @param message_buf_size total size of all messages in message_buf
1364 * @param is_internal is this an internal message; these are pre-pended and
1365 * also do not count for plugins being "ready" to transmit
1366 * @param neighbour handle to the neighbour for transmission
1369 transmit_to_peer (struct TransportClient *client,
1370 struct ForeignAddressList *peer_address,
1371 unsigned int priority,
1372 struct GNUNET_TIME_Relative timeout,
1373 const char *message_buf,
1374 size_t message_buf_size,
1375 int is_internal, struct NeighbourList *neighbour)
1377 struct MessageQueue *mq;
1382 /* check for duplicate submission */
1383 mq = neighbour->messages_head;
1386 if (mq->client == client)
1388 /* client transmitted to same peer twice
1389 before getting SEND_OK! */
1397 GNUNET_STATISTICS_update (stats,
1398 gettext_noop ("# bytes in message queue for other peers"),
1401 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1402 mq->specific_address = peer_address;
1403 mq->client = client;
1404 memcpy (&mq[1], message_buf, message_buf_size);
1405 mq->message_buf = (const char*) &mq[1];
1406 mq->message_buf_size = message_buf_size;
1407 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1408 mq->internal_msg = is_internal;
1409 mq->priority = priority;
1410 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1412 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1413 neighbour->messages_tail,
1416 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1417 neighbour->messages_tail,
1418 neighbour->messages_tail,
1420 try_transmission_to_peer (neighbour);
1427 struct GeneratorContext
1429 struct TransportPlugin *plug_pos;
1430 struct OwnAddressList *addr_pos;
1431 struct GNUNET_TIME_Absolute expiration;
1439 address_generator (void *cls, size_t max, void *buf)
1441 struct GeneratorContext *gc = cls;
1444 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1446 gc->plug_pos = gc->plug_pos->next;
1447 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1449 if (NULL == gc->plug_pos)
1454 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1457 gc->addr_pos->addrlen, buf, max);
1458 gc->addr_pos = gc->addr_pos->next;
1464 * Construct our HELLO message from all of the addresses of
1465 * all of the transports.
1470 struct GNUNET_HELLO_Message *hello;
1471 struct TransportClient *cpos;
1472 struct NeighbourList *npos;
1473 struct GeneratorContext gc;
1475 gc.plug_pos = plugins;
1476 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1477 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1478 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1480 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1481 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1483 GNUNET_STATISTICS_update (stats,
1484 gettext_noop ("# refreshed my HELLO"),
1488 while (cpos != NULL)
1490 transmit_to_client (cpos,
1491 (const struct GNUNET_MessageHeader *) hello,
1496 GNUNET_free_non_null (our_hello);
1498 our_hello_version++;
1499 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1501 while (npos != NULL)
1504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1505 "Transmitting updated `%s' to neighbour `%4s'\n",
1506 "HELLO", GNUNET_i2s (&npos->id));
1508 GNUNET_STATISTICS_update (stats,
1509 gettext_noop ("# transmitted my HELLO to other peers"),
1512 transmit_to_peer (NULL, NULL, 0,
1513 HELLO_ADDRESS_EXPIRATION,
1514 (const char *) our_hello,
1515 GNUNET_HELLO_size(our_hello),
1523 * Task used to clean up expired addresses for a plugin.
1525 * @param cls closure
1529 expire_address_task (void *cls,
1530 const struct GNUNET_SCHEDULER_TaskContext *tc);
1534 * Update the list of addresses for this plugin,
1535 * expiring those that are past their expiration date.
1537 * @param plugin addresses of which plugin should be recomputed?
1538 * @param fresh set to GNUNET_YES if a new address was added
1539 * and we need to regenerate the HELLO even if nobody
1543 update_addresses (struct TransportPlugin *plugin, int fresh)
1545 struct GNUNET_TIME_Relative min_remaining;
1546 struct GNUNET_TIME_Relative remaining;
1547 struct GNUNET_TIME_Absolute now;
1548 struct OwnAddressList *pos;
1549 struct OwnAddressList *prev;
1550 struct OwnAddressList *next;
1553 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1554 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1555 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1556 now = GNUNET_TIME_absolute_get ();
1557 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1558 expired = GNUNET_NO;
1560 pos = plugin->addresses;
1564 if (pos->expires.value < now.value)
1566 expired = GNUNET_YES;
1568 plugin->addresses = pos->next;
1570 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)
1587 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1588 plugin->address_update_task
1589 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1591 &expire_address_task, plugin);
1597 * Task used to clean up expired addresses for a plugin.
1599 * @param cls closure
1603 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1605 struct TransportPlugin *plugin = cls;
1606 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1607 update_addresses (plugin, GNUNET_NO);
1612 * Function that must be called by each plugin to notify the
1613 * transport service about the addresses under which the transport
1614 * provided by the plugin can be reached.
1616 * @param cls closure
1617 * @param name name of the transport that generated the address
1618 * @param addr one of the addresses of the host, NULL for the last address
1619 * the specific address format depends on the transport
1620 * @param addrlen length of the address
1621 * @param expires when should this address automatically expire?
1624 plugin_env_notify_address (void *cls,
1628 struct GNUNET_TIME_Relative expires)
1630 struct TransportPlugin *p = cls;
1631 struct OwnAddressList *al;
1632 struct GNUNET_TIME_Absolute abex;
1634 abex = GNUNET_TIME_relative_to_absolute (expires);
1635 GNUNET_assert (p == find_transport (name));
1640 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1642 if (al->expires.value < abex.value)
1649 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1651 al->next = p->addresses;
1654 al->addrlen = addrlen;
1655 memcpy (&al[1], addr, addrlen);
1656 update_addresses (p, GNUNET_YES);
1661 * Notify all of our clients about a peer connecting.
1664 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1665 struct GNUNET_TIME_Relative latency,
1668 struct ConnectInfoMessage cim;
1669 struct TransportClient *cpos;
1672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673 "Notifying clients about connection from `%s'\n",
1676 GNUNET_STATISTICS_update (stats,
1677 gettext_noop ("# peers connected"),
1680 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1681 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1682 cim.distance = htonl (distance);
1683 cim.latency = GNUNET_TIME_relative_hton (latency);
1684 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1686 while (cpos != NULL)
1688 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1695 * Notify all of our clients about a peer disconnecting.
1698 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1700 struct DisconnectInfoMessage dim;
1701 struct TransportClient *cpos;
1704 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1705 "Notifying clients about lost connection to `%s'\n",
1708 GNUNET_STATISTICS_update (stats,
1709 gettext_noop ("# peers connected"),
1712 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1713 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1714 dim.reserved = htonl (0);
1715 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1717 while (cpos != NULL)
1719 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1726 * Find a ForeignAddressList entry for the given neighbour
1727 * that matches the given address and transport.
1729 * @param neighbour which peer we care about
1730 * @param tname name of the transport plugin
1731 * @param addr binary address
1732 * @param addrlen length of addr
1733 * @return NULL if no such entry exists
1735 static struct ForeignAddressList *
1736 find_peer_address(struct NeighbourList *neighbour,
1741 struct ReadyList *head;
1742 struct ForeignAddressList *address_head;
1744 head = neighbour->plugins;
1745 while (head != NULL)
1747 if (0 == strcmp (tname, head->plugin->short_name))
1754 address_head = head->addresses;
1755 while ( (address_head != NULL) &&
1756 ( (address_head->addrlen != addrlen) ||
1757 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1758 address_head = address_head->next;
1759 return address_head;
1764 * Get the peer address struct for the given neighbour and
1765 * address. If it doesn't yet exist, create it.
1767 * @param neighbour which peer we care about
1768 * @param tname name of the transport plugin
1769 * @param addr binary address
1770 * @param addrlen length of addr
1771 * @return NULL if we do not have a transport plugin for 'tname'
1773 static struct ForeignAddressList *
1774 add_peer_address (struct NeighbourList *neighbour,
1779 struct ReadyList *head;
1780 struct ForeignAddressList *ret;
1782 ret = find_peer_address (neighbour, tname, addr, addrlen);
1785 head = neighbour->plugins;
1786 while (head != NULL)
1788 if (0 == strcmp (tname, head->plugin->short_name))
1794 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1795 ret->addr = (const char*) &ret[1];
1796 memcpy (&ret[1], addr, addrlen);
1797 ret->addrlen = addrlen;
1798 ret->expires = GNUNET_TIME_relative_to_absolute
1799 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1800 ret->latency = GNUNET_TIME_relative_get_forever();
1802 ret->timeout = GNUNET_TIME_relative_to_absolute
1803 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1804 ret->ready_list = head;
1805 ret->next = head->addresses;
1806 head->addresses = ret;
1812 * Closure for 'add_validated_address'.
1814 struct AddValidatedAddressContext
1817 * Entry that has been validated.
1819 const struct ValidationEntry *ve;
1822 * Flag set after we have added the address so
1823 * that we terminate the iteration next time.
1830 * Callback function used to fill a buffer of max bytes with a list of
1831 * addresses in the format used by HELLOs. Should use
1832 * "GNUNET_HELLO_add_address" as a helper function.
1834 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1835 * @param max maximum number of bytes that can be written to buf
1836 * @param buf where to write the address information
1837 * @return number of bytes written, 0 to signal the
1838 * end of the iteration.
1841 add_validated_address (void *cls,
1842 size_t max, void *buf)
1844 struct AddValidatedAddressContext *avac = cls;
1845 const struct ValidationEntry *ve = avac->ve;
1847 if (GNUNET_YES == avac->done)
1849 avac->done = GNUNET_YES;
1850 return GNUNET_HELLO_add_address (ve->transport_name,
1851 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1861 * Closure for 'check_address_exists'.
1863 struct CheckAddressExistsClosure
1866 * Address to check for.
1871 * Name of the transport.
1881 * Set to GNUNET_YES if the address exists.
1888 * Iterator over hash map entries. Checks if the given
1889 * validation entry is for the same address as what is given
1892 * @param cls the 'struct CheckAddressExistsClosure*'
1893 * @param key current key code (ignored)
1894 * @param value value in the hash map ('struct ValidationEntry')
1895 * @return GNUNET_YES if we should continue to
1896 * iterate (mismatch), GNUNET_NO if not (entry matched)
1899 check_address_exists (void *cls,
1900 const GNUNET_HashCode * key,
1903 struct CheckAddressExistsClosure *caec = cls;
1904 struct ValidationEntry *ve = value;
1905 if ( (0 == strcmp (caec->tname,
1906 ve->transport_name)) &&
1907 (caec->addrlen == ve->addrlen) &&
1908 (0 == memcmp (caec->addr,
1912 caec->exists = GNUNET_YES;
1920 * HELLO validation cleanup task (validation failed).
1922 * @param cls the 'struct ValidationEntry' that failed
1923 * @param tc scheduler context (unused)
1926 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1928 struct ValidationEntry *va = cls;
1929 struct GNUNET_PeerIdentity pid;
1931 GNUNET_STATISTICS_update (stats,
1932 gettext_noop ("# address validation timeouts"),
1935 GNUNET_CRYPTO_hash (&va->publicKey,
1937 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1939 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1942 GNUNET_free (va->transport_name);
1948 neighbour_timeout_task (void *cls,
1949 const struct GNUNET_SCHEDULER_TaskContext *tc)
1951 struct NeighbourList *n = cls;
1954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1955 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1957 GNUNET_STATISTICS_update (stats,
1958 gettext_noop ("# disconnects due to timeout"),
1961 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1962 disconnect_neighbour (n, GNUNET_NO);
1967 * Schedule the job that will cause us to send a PING to the
1968 * foreign address to evaluate its validity and latency.
1970 * @param fal address to PING
1973 schedule_next_ping (struct ForeignAddressList *fal);
1977 * Add the given address to the list of foreign addresses
1978 * available for the given peer (check for duplicates).
1980 * @param cls the respective 'struct NeighbourList' to update
1981 * @param tname name of the transport
1982 * @param expiration expiration time
1983 * @param addr the address
1984 * @param addrlen length of the address
1985 * @return GNUNET_OK (always)
1988 add_to_foreign_address_list (void *cls,
1990 struct GNUNET_TIME_Absolute expiration,
1991 const void *addr, size_t addrlen)
1993 struct NeighbourList *n = cls;
1994 struct ForeignAddressList *fal;
1997 GNUNET_STATISTICS_update (stats,
1998 gettext_noop ("# valid peer addresses returned by peerinfo"),
2002 fal = find_peer_address (n, tname, addr, addrlen);
2006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2008 GNUNET_a2s (addr, addrlen),
2010 GNUNET_i2s (&n->id),
2013 fal = add_peer_address (n, tname, addr, addrlen);
2016 GNUNET_STATISTICS_update (stats,
2017 gettext_noop ("# previously validated addresses lacking transport"),
2023 fal->expires = GNUNET_TIME_absolute_max (expiration,
2025 schedule_next_ping (fal);
2031 fal->expires = GNUNET_TIME_absolute_max (expiration,
2036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2037 "Failed to add new address for `%4s'\n",
2038 GNUNET_i2s (&n->id));
2041 if (fal->validated == GNUNET_NO)
2043 fal->validated = GNUNET_YES;
2044 GNUNET_STATISTICS_update (stats,
2045 gettext_noop ("# peer addresses considered valid"),
2049 if (try == GNUNET_YES)
2051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2052 "Have new addresses, will try to trigger transmissions.\n");
2053 try_transmission_to_peer (n);
2060 * Add addresses in validated HELLO "h" to the set of addresses
2061 * we have for this peer.
2063 * @param cls closure ('struct NeighbourList*')
2064 * @param peer id of the peer, NULL for last call
2065 * @param h hello message for the peer (can be NULL)
2066 * @param trust amount of trust we have in the peer (not used)
2069 add_hello_for_peer (void *cls,
2070 const struct GNUNET_PeerIdentity *peer,
2071 const struct GNUNET_HELLO_Message *h,
2074 struct NeighbourList *n = cls;
2082 return; /* no HELLO available */
2084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085 "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2089 if (GNUNET_YES != n->public_key_valid)
2091 GNUNET_HELLO_get_key (h, &n->publicKey);
2092 n->public_key_valid = GNUNET_YES;
2094 GNUNET_HELLO_iterate_addresses (h,
2096 &add_to_foreign_address_list,
2102 * Create a fresh entry in our neighbour list for the given peer.
2103 * Will try to transmit our current HELLO to the new neighbour.
2105 * @param peer the peer for which we create the entry
2106 * @return the new neighbour list entry
2108 static struct NeighbourList *
2109 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2111 struct NeighbourList *n;
2112 struct TransportPlugin *tp;
2113 struct ReadyList *rl;
2115 GNUNET_assert (our_hello != NULL);
2116 GNUNET_STATISTICS_update (stats,
2117 gettext_noop ("# active neighbours"),
2120 n = GNUNET_malloc (sizeof (struct NeighbourList));
2121 n->next = neighbours;
2125 GNUNET_TIME_relative_to_absolute
2126 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2127 GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2128 GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2129 MAX_BANDWIDTH_CARRY_S);
2133 if (tp->api->send != NULL)
2135 rl = GNUNET_malloc (sizeof (struct ReadyList));
2137 rl->next = n->plugins;
2140 rl->addresses = NULL;
2144 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2146 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2147 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2148 &neighbour_timeout_task, n);
2149 n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2150 0, GNUNET_TIME_UNIT_FOREVER_REL,
2151 &add_hello_for_peer, n);
2152 transmit_to_peer (NULL, NULL, 0,
2153 HELLO_ADDRESS_EXPIRATION,
2154 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2161 * Send periodic PING messages to a give foreign address.
2163 * @param cls our 'struct PeriodicValidationContext*'
2164 * @param tc task context
2167 send_periodic_ping (void *cls,
2168 const struct GNUNET_SCHEDULER_TaskContext *tc)
2170 struct ForeignAddressList *peer_address = cls;
2171 struct TransportPlugin *tp;
2172 struct ValidationEntry *va;
2173 struct NeighbourList *neighbour;
2174 struct TransportPingMessage ping;
2175 struct CheckAddressExistsClosure caec;
2177 uint16_t hello_size;
2180 peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2181 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2183 tp = peer_address->ready_list->plugin;
2184 neighbour = peer_address->ready_list->neighbour;
2185 if (GNUNET_YES != neighbour->public_key_valid)
2187 /* no public key yet, try again later */
2188 schedule_next_ping (peer_address);
2191 caec.addr = peer_address->addr;
2192 caec.addrlen = peer_address->addrlen;
2193 caec.tname = tp->short_name;
2194 caec.exists = GNUNET_NO;
2195 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2196 &check_address_exists,
2198 if (caec.exists == GNUNET_YES)
2200 /* During validation attempts we will likely trigger the other
2201 peer trying to validate our address which in turn will cause
2202 it to send us its HELLO, so we expect to hit this case rather
2203 frequently. Only print something if we are very verbose. */
2204 #if DEBUG_TRANSPORT > 1
2205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2206 "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2207 GNUNET_a2s (peer_address->addr,
2208 peer_address->addrlen),
2210 GNUNET_i2s (&neighbour->id));
2212 schedule_next_ping (peer_address);
2215 va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2216 va->transport_name = GNUNET_strdup (tp->short_name);
2217 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2219 va->send_time = GNUNET_TIME_absolute_get();
2220 va->addr = (const void*) &va[1];
2221 memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2222 va->addrlen = peer_address->addrlen;
2224 memcpy(&va->publicKey,
2225 &neighbour->publicKey,
2226 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2228 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2229 HELLO_VERIFICATION_TIMEOUT,
2230 &timeout_hello_validation,
2232 GNUNET_CONTAINER_multihashmap_put (validation_map,
2233 &neighbour->id.hashPubKey,
2235 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2236 hello_size = GNUNET_HELLO_size(our_hello);
2237 tsize = sizeof(struct TransportPingMessage) + hello_size;
2238 message_buf = GNUNET_malloc(tsize);
2239 ping.challenge = htonl(va->challenge);
2240 ping.header.size = htons(sizeof(struct TransportPingMessage));
2241 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2242 memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2243 memcpy(message_buf, our_hello, hello_size);
2244 memcpy(&message_buf[hello_size],
2246 sizeof(struct TransportPingMessage));
2247 #if DEBUG_TRANSPORT_REVALIDATION
2248 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2249 "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2250 GNUNET_a2s (peer_address->addr,
2251 peer_address->addrlen),
2253 GNUNET_i2s (&neighbour->id),
2254 "HELLO", hello_size,
2255 "PING", sizeof (struct TransportPingMessage));
2257 GNUNET_STATISTICS_update (stats,
2258 gettext_noop ("# PING messages sent for re-validation"),
2261 transmit_to_peer (NULL, peer_address,
2262 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2263 HELLO_VERIFICATION_TIMEOUT,
2265 GNUNET_YES, neighbour);
2266 GNUNET_free(message_buf);
2267 schedule_next_ping (peer_address);
2272 * Schedule the job that will cause us to send a PING to the
2273 * foreign address to evaluate its validity and latency.
2275 * @param fal address to PING
2278 schedule_next_ping (struct ForeignAddressList *fal)
2280 struct GNUNET_TIME_Relative delay;
2282 if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2284 delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2285 delay.value /= 2; /* do before expiration */
2286 delay = GNUNET_TIME_relative_min (delay,
2287 LATENCY_EVALUATION_MAX_DELAY);
2288 if (GNUNET_YES != fal->estimated)
2290 delay = GNUNET_TIME_UNIT_ZERO;
2291 fal->estimated = GNUNET_YES;
2293 if (GNUNET_YES == fal->connected)
2295 delay = GNUNET_TIME_relative_min (delay,
2296 CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2298 /* FIXME: also adjust delay based on how close the last
2299 observed latency is to the latency of the best alternative */
2300 /* bound how fast we can go */
2301 delay = GNUNET_TIME_relative_max (delay,
2302 GNUNET_TIME_UNIT_SECONDS);
2303 /* randomize a bit (to avoid doing all at the same time) */
2304 delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2305 fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched,
2307 &send_periodic_ping,
2313 * Iterator over hash map entries. Checks if the given validation
2314 * entry is for the same challenge as what is given in the PONG.
2316 * @param cls the 'struct TransportPongMessage*'
2317 * @param key peer identity
2318 * @param value value in the hash map ('struct ValidationEntry')
2319 * @return GNUNET_YES if we should continue to
2320 * iterate (mismatch), GNUNET_NO if not (entry matched)
2323 check_pending_validation (void *cls,
2324 const GNUNET_HashCode * key,
2327 const struct TransportPongMessage *pong = cls;
2328 struct ValidationEntry *ve = value;
2329 struct AddValidatedAddressContext avac;
2330 unsigned int challenge = ntohl(pong->challenge);
2331 struct GNUNET_HELLO_Message *hello;
2332 struct GNUNET_PeerIdentity target;
2333 struct NeighbourList *n;
2334 struct ForeignAddressList *fal;
2336 if (ve->challenge != challenge)
2340 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2341 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2343 GNUNET_a2s ((const struct sockaddr *) ve->addr,
2345 ve->transport_name);
2347 GNUNET_STATISTICS_update (stats,
2348 gettext_noop ("# address validation successes"),
2351 /* create the updated HELLO */
2352 GNUNET_CRYPTO_hash (&ve->publicKey,
2353 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2354 &target.hashPubKey);
2355 avac.done = GNUNET_NO;
2357 hello = GNUNET_HELLO_create (&ve->publicKey,
2358 &add_validated_address,
2360 GNUNET_PEERINFO_add_peer (cfg, sched,
2363 GNUNET_free (hello);
2364 n = find_neighbour (&target);
2367 n->publicKey = ve->publicKey;
2368 n->public_key_valid = GNUNET_YES;
2369 fal = add_peer_address (n,
2373 GNUNET_assert (fal != NULL);
2374 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2375 fal->validated = GNUNET_YES;
2376 GNUNET_STATISTICS_update (stats,
2377 gettext_noop ("# peer addresses considered valid"),
2380 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2381 schedule_next_ping (fal);
2382 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2383 n->latency = fal->latency;
2385 n->latency.value = (fal->latency.value + n->latency.value) / 2;
2386 n->distance = fal->distance;
2387 if (GNUNET_NO == n->received_pong)
2389 notify_clients_connect (&target, n->latency, n->distance);
2390 n->received_pong = GNUNET_YES;
2392 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2394 GNUNET_SCHEDULER_cancel (sched,
2396 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2397 try_transmission_to_peer (n);
2401 /* clean up validation entry */
2402 GNUNET_assert (GNUNET_YES ==
2403 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2406 GNUNET_SCHEDULER_cancel (sched,
2408 GNUNET_free (ve->transport_name);
2415 * Function that will be called if we receive a validation
2416 * of an address challenge that we transmitted to another
2417 * peer. Note that the validation should only be considered
2418 * acceptable if the challenge matches AND if the sender
2419 * address is at least a plausible address for this peer
2420 * (otherwise we may be seeing a MiM attack).
2422 * @param cls closure
2423 * @param message the pong message
2424 * @param peer who responded to our challenge
2425 * @param sender_address string describing our sender address (as observed
2426 * by the other peer in binary format)
2427 * @param sender_address_len number of bytes in 'sender_address'
2430 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2431 const struct GNUNET_PeerIdentity *peer,
2432 const char *sender_address,
2433 size_t sender_address_len)
2435 #if DEBUG_TRANSPORT > 1
2436 /* we get tons of these that just get discarded, only log
2437 if we are quite verbose */
2438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439 "Receiving `%s' message from `%4s'.\n", "PONG",
2442 GNUNET_STATISTICS_update (stats,
2443 gettext_noop ("# PONG messages received"),
2446 if (GNUNET_SYSERR !=
2447 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2449 &check_pending_validation,
2452 /* This is *expected* to happen a lot since we send
2453 PONGs to *all* known addresses of the sender of
2454 the PING, so most likely we get multiple PONGs
2455 per PING, and all but the first PONG will end up
2456 here. So really we should not print anything here
2457 unless we want to be very, very verbose... */
2458 #if DEBUG_TRANSPORT > 2
2459 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2460 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2469 /* FIXME: add given address to potential pool of our addresses
2471 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2472 _("Another peer saw us using the address `%s' via `%s'.\n"),
2473 GNUNET_a2s ((const struct sockaddr *) &pong[1],
2474 ntohs(pong->addrlen)),
2475 va->transport_name);
2481 * Check if the given address is already being validated; if not,
2482 * append the given address to the list of entries that are being be
2483 * validated and initiate validation.
2485 * @param cls closure ('struct CheckHelloValidatedContext *')
2486 * @param tname name of the transport
2487 * @param expiration expiration time
2488 * @param addr the address
2489 * @param addrlen length of the address
2490 * @return GNUNET_OK (always)
2493 run_validation (void *cls,
2495 struct GNUNET_TIME_Absolute expiration,
2496 const void *addr, size_t addrlen)
2498 struct CheckHelloValidatedContext *chvc = cls;
2499 struct GNUNET_PeerIdentity id;
2500 struct TransportPlugin *tp;
2501 struct ValidationEntry *va;
2502 struct NeighbourList *neighbour;
2503 struct ForeignAddressList *peer_address;
2504 struct TransportPingMessage ping;
2505 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2506 struct CheckAddressExistsClosure caec;
2508 uint16_t hello_size;
2511 GNUNET_STATISTICS_update (stats,
2512 gettext_noop ("# peer addresses scheduled for validation"),
2515 tp = find_transport (tname);
2518 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2519 GNUNET_ERROR_TYPE_BULK,
2521 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2523 GNUNET_STATISTICS_update (stats,
2524 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2529 GNUNET_HELLO_get_key (chvc->hello, &pk);
2530 GNUNET_CRYPTO_hash (&pk,
2532 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2535 caec.addrlen = addrlen;
2537 caec.exists = GNUNET_NO;
2538 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2539 &check_address_exists,
2541 if (caec.exists == GNUNET_YES)
2543 /* During validation attempts we will likely trigger the other
2544 peer trying to validate our address which in turn will cause
2545 it to send us its HELLO, so we expect to hit this case rather
2546 frequently. Only print something if we are very verbose. */
2547 #if DEBUG_TRANSPORT > 1
2548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2549 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2550 GNUNET_a2s (addr, addrlen),
2554 GNUNET_STATISTICS_update (stats,
2555 gettext_noop ("# peer addresses not validated (in progress)"),
2560 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2561 va->transport_name = GNUNET_strdup (tname);
2562 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2564 va->send_time = GNUNET_TIME_absolute_get();
2565 va->addr = (const void*) &va[1];
2566 memcpy (&va[1], addr, addrlen);
2567 va->addrlen = addrlen;
2568 GNUNET_HELLO_get_key (chvc->hello,
2570 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2571 HELLO_VERIFICATION_TIMEOUT,
2572 &timeout_hello_validation,
2574 GNUNET_CONTAINER_multihashmap_put (validation_map,
2577 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2578 neighbour = find_neighbour(&id);
2579 if (neighbour == NULL)
2580 neighbour = setup_new_neighbour(&id);
2581 neighbour->publicKey = va->publicKey;
2582 neighbour->public_key_valid = GNUNET_YES;
2583 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2584 GNUNET_assert(peer_address != NULL);
2585 hello_size = GNUNET_HELLO_size(our_hello);
2586 tsize = sizeof(struct TransportPingMessage) + hello_size;
2587 message_buf = GNUNET_malloc(tsize);
2588 ping.challenge = htonl(va->challenge);
2589 ping.header.size = htons(sizeof(struct TransportPingMessage));
2590 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2591 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2592 memcpy(message_buf, our_hello, hello_size);
2593 memcpy(&message_buf[hello_size],
2595 sizeof(struct TransportPingMessage));
2597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2598 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2599 GNUNET_a2s (addr, addrlen),
2602 "HELLO", hello_size,
2603 "PING", sizeof (struct TransportPingMessage));
2605 GNUNET_STATISTICS_update (stats,
2606 gettext_noop ("# PING messages sent for initial validation"),
2609 transmit_to_peer (NULL, peer_address,
2610 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2611 HELLO_VERIFICATION_TIMEOUT,
2613 GNUNET_YES, neighbour);
2614 GNUNET_free(message_buf);
2620 * Check if addresses in validated hello "h" overlap with
2621 * those in "chvc->hello" and validate the rest.
2623 * @param cls closure
2624 * @param peer id of the peer, NULL for last call
2625 * @param h hello message for the peer (can be NULL)
2626 * @param trust amount of trust we have in the peer (not used)
2629 check_hello_validated (void *cls,
2630 const struct GNUNET_PeerIdentity *peer,
2631 const struct GNUNET_HELLO_Message *h,
2634 struct CheckHelloValidatedContext *chvc = cls;
2635 struct GNUNET_HELLO_Message *plain_hello;
2636 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2637 struct GNUNET_PeerIdentity target;
2638 struct NeighbourList *n;
2643 GNUNET_CONTAINER_DLL_remove (chvc_head,
2646 if (GNUNET_NO == chvc->hello_known)
2648 /* notify PEERINFO about the peer now, so that we at least
2649 have the public key if some other component needs it */
2650 GNUNET_HELLO_get_key (chvc->hello, &pk);
2651 GNUNET_CRYPTO_hash (&pk,
2652 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2653 &target.hashPubKey);
2654 plain_hello = GNUNET_HELLO_create (&pk,
2657 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2658 GNUNET_free (plain_hello);
2660 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2661 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2663 GNUNET_i2s (&target));
2665 GNUNET_STATISTICS_update (stats,
2666 gettext_noop ("# new HELLOs requiring full validation"),
2669 GNUNET_HELLO_iterate_addresses (chvc->hello,
2676 GNUNET_STATISTICS_update (stats,
2677 gettext_noop ("# duplicate HELLO (peer known)"),
2687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2688 "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2692 chvc->hello_known = GNUNET_YES;
2693 n = find_neighbour (peer);
2696 GNUNET_HELLO_iterate_addresses (h,
2698 &add_to_foreign_address_list,
2700 try_transmission_to_peer (n);
2704 GNUNET_STATISTICS_update (stats,
2705 gettext_noop ("# no existing neighbour record (validating HELLO)"),
2709 GNUNET_STATISTICS_update (stats,
2710 gettext_noop ("# HELLO validations (update case)"),
2713 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2715 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2721 * Process HELLO-message.
2723 * @param plugin transport involved, may be NULL
2724 * @param message the actual message
2725 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2728 process_hello (struct TransportPlugin *plugin,
2729 const struct GNUNET_MessageHeader *message)
2732 struct GNUNET_PeerIdentity target;
2733 const struct GNUNET_HELLO_Message *hello;
2734 struct CheckHelloValidatedContext *chvc;
2735 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2737 hsize = ntohs (message->size);
2738 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2739 (hsize < sizeof (struct GNUNET_MessageHeader)))
2742 return GNUNET_SYSERR;
2744 GNUNET_STATISTICS_update (stats,
2745 gettext_noop ("# HELLOs received for validation"),
2748 /* first, check if load is too high */
2749 if (GNUNET_SCHEDULER_get_load (sched,
2750 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2752 GNUNET_STATISTICS_update (stats,
2753 gettext_noop ("# HELLOs ignored due to high load"),
2758 hello = (const struct GNUNET_HELLO_Message *) message;
2759 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2761 GNUNET_break_op (0);
2762 return GNUNET_SYSERR;
2764 GNUNET_CRYPTO_hash (&publicKey,
2765 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2766 &target.hashPubKey);
2767 if (0 == memcmp (&my_identity,
2769 sizeof (struct GNUNET_PeerIdentity)))
2771 GNUNET_STATISTICS_update (stats,
2772 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
2777 #if DEBUG_TRANSPORT > 1
2778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2779 "Processing `%s' message for `%4s' of size %u\n",
2781 GNUNET_i2s (&target),
2782 GNUNET_HELLO_size(hello));
2784 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2785 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2786 memcpy (&chvc[1], hello, hsize);
2787 GNUNET_CONTAINER_DLL_insert (chvc_head,
2790 /* finally, check if HELLO was previously validated
2791 (continuation will then schedule actual validation) */
2792 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2796 HELLO_VERIFICATION_TIMEOUT,
2797 &check_hello_validated, chvc);
2803 * The peer specified by the given neighbour has timed-out or a plugin
2804 * has disconnected. We may either need to do nothing (other plugins
2805 * still up), or trigger a full disconnect and clean up. This
2806 * function updates our state and does the necessary notifications.
2807 * Also notifies our clients that the neighbour is now officially
2810 * @param n the neighbour list entry for the peer
2811 * @param check should we just check if all plugins
2812 * disconnected or must we ask all plugins to
2816 disconnect_neighbour (struct NeighbourList *n, int check)
2818 struct ReadyList *rpos;
2819 struct NeighbourList *npos;
2820 struct NeighbourList *nprev;
2821 struct MessageQueue *mq;
2822 struct ForeignAddressList *peer_addresses;
2823 struct ForeignAddressList *peer_pos;
2825 if (GNUNET_YES == check)
2828 while (NULL != rpos)
2830 peer_addresses = rpos->addresses;
2831 while (peer_addresses != NULL)
2833 if (GNUNET_YES == peer_addresses->connected)
2834 return; /* still connected */
2835 peer_addresses = peer_addresses->next;
2841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2842 "Disconnecting from `%4s'\n",
2843 GNUNET_i2s (&n->id));
2845 /* remove n from neighbours list */
2848 while ((npos != NULL) && (npos != n))
2853 GNUNET_assert (npos != NULL);
2855 neighbours = n->next;
2857 nprev->next = n->next;
2859 /* notify all clients about disconnect */
2860 if (GNUNET_YES == n->received_pong)
2861 notify_clients_disconnect (&n->id);
2863 /* clean up all plugins, cancel connections and pending transmissions */
2864 while (NULL != (rpos = n->plugins))
2866 n->plugins = rpos->next;
2867 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2868 while (rpos->addresses != NULL)
2870 peer_pos = rpos->addresses;
2871 rpos->addresses = peer_pos->next;
2872 if (peer_pos->connected == GNUNET_YES)
2873 GNUNET_STATISTICS_update (stats,
2874 gettext_noop ("# connected addresses"),
2877 if (GNUNET_YES == peer_pos->validated)
2878 GNUNET_STATISTICS_update (stats,
2879 gettext_noop ("# peer addresses considered valid"),
2882 if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
2884 GNUNET_SCHEDULER_cancel (sched,
2885 peer_pos->revalidate_task);
2886 peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2888 GNUNET_free(peer_pos);
2893 /* free all messages on the queue */
2894 while (NULL != (mq = n->messages_head))
2896 GNUNET_STATISTICS_update (stats,
2897 gettext_noop ("# bytes in message queue for other peers"),
2898 -mq->message_buf_size,
2900 GNUNET_STATISTICS_update (stats,
2901 gettext_noop ("# bytes discarded due to disconnect"),
2902 mq->message_buf_size,
2904 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2907 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2909 sizeof(struct GNUNET_PeerIdentity)));
2912 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2914 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2915 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2917 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2919 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2920 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2922 if (n->piter != NULL)
2924 GNUNET_PEERINFO_iterate_cancel (n->piter);
2927 /* finally, free n itself */
2928 GNUNET_STATISTICS_update (stats,
2929 gettext_noop ("# active neighbours"),
2937 * We have received a PING message from someone. Need to send a PONG message
2938 * in response to the peer by any means necessary.
2940 * FIXME: With something like TCP where a connection exists, we may
2941 * want to send it that way. But the current API does not seem to
2942 * allow us to do so (can't tell this to the transport!)
2945 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2946 const struct GNUNET_PeerIdentity *peer,
2947 const char *sender_address,
2948 size_t sender_address_len)
2950 struct TransportPlugin *plugin = cls;
2951 struct TransportPingMessage *ping;
2952 struct TransportPongMessage *pong;
2953 struct NeighbourList *n;
2954 struct ReadyList *rl;
2955 struct ForeignAddressList *fal;
2957 if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2959 GNUNET_break_op (0);
2960 return GNUNET_SYSERR;
2962 ping = (struct TransportPingMessage *) message;
2963 if (0 != memcmp (&ping->target,
2964 plugin->env.my_identity,
2965 sizeof (struct GNUNET_PeerIdentity)))
2967 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2968 _("Received `%s' message not destined for me!\n"),
2970 return GNUNET_SYSERR;
2973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2974 "Processing `%s' from `%s'\n",
2976 GNUNET_a2s ((const struct sockaddr *)sender_address,
2977 sender_address_len));
2979 GNUNET_STATISTICS_update (stats,
2980 gettext_noop ("# PING messages received"),
2983 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2984 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2985 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2986 pong->purpose.size =
2987 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2989 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2990 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2991 pong->challenge = ping->challenge;
2992 pong->addrlen = htons(sender_address_len);
2993 memcpy(&pong->signer,
2995 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2996 memcpy (&pong[1], sender_address, sender_address_len);
2997 GNUNET_assert (GNUNET_OK ==
2998 GNUNET_CRYPTO_rsa_sign (my_private_key,
2999 &pong->purpose, &pong->signature));
3001 n = find_neighbour(peer);
3003 n = setup_new_neighbour(peer);
3004 /* broadcast 'PONG' to all available addresses */
3008 fal = rl->addresses;
3011 transmit_to_peer(NULL, fal,
3012 TRANSPORT_PONG_PRIORITY,
3013 HELLO_VERIFICATION_TIMEOUT,
3015 ntohs(pong->header.size),
3028 * Function called by the plugin for each received message.
3029 * Update data volumes, possibly notify plugins about
3030 * reducing the rate at which they read from the socket
3031 * and generally forward to our receive callback.
3033 * @param cls the "struct TransportPlugin *" we gave to the plugin
3034 * @param peer (claimed) identity of the other peer
3035 * @param message the message, NULL if we only care about
3036 * learning about the delay until we should receive again
3037 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3038 * @param sender_address binary address of the sender (if observed)
3039 * @param sender_address_len number of bytes in sender_address
3040 * @return how long the plugin should wait until receiving more data
3041 * (plugins that do not support this, can ignore the return value)
3043 static struct GNUNET_TIME_Relative
3044 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3045 const struct GNUNET_MessageHeader *message,
3046 unsigned int distance, const char *sender_address,
3047 size_t sender_address_len)
3049 struct ReadyList *service_context;
3050 struct TransportPlugin *plugin = cls;
3051 struct TransportClient *cpos;
3052 struct InboundMessage *im;
3053 struct ForeignAddressList *peer_address;
3055 struct NeighbourList *n;
3056 struct GNUNET_TIME_Relative ret;
3058 n = find_neighbour (peer);
3060 n = setup_new_neighbour (peer);
3061 service_context = n->plugins;
3062 while ((service_context != NULL) && (plugin != service_context->plugin))
3063 service_context = service_context->next;
3064 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3065 if (message != NULL)
3067 peer_address = add_peer_address(n,
3070 sender_address_len);
3071 if (peer_address != NULL)
3073 peer_address->distance = distance;
3074 if (peer_address->connected == GNUNET_NO)
3076 /* FIXME: be careful here to not mark
3077 MULTIPLE addresses as connected! */
3078 peer_address->connected = GNUNET_YES;
3079 GNUNET_STATISTICS_update (stats,
3080 gettext_noop ("# connected addresses"),
3084 peer_address->timeout
3086 GNUNET_TIME_relative_to_absolute
3087 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3088 schedule_next_ping (peer_address);
3090 /* update traffic received amount ... */
3091 msize = ntohs (message->size);
3092 GNUNET_STATISTICS_update (stats,
3093 gettext_noop ("# bytes received from other peers"),
3096 n->distance = distance;
3098 GNUNET_TIME_relative_to_absolute
3099 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3100 GNUNET_SCHEDULER_cancel (sched,
3103 GNUNET_SCHEDULER_add_delayed (sched,
3104 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3105 &neighbour_timeout_task, n);
3106 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3108 /* dropping message due to frequent inbound volume violations! */
3109 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3110 GNUNET_ERROR_TYPE_BULK,
3112 ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
3113 n->in_tracker.available_bytes_per_s__,
3114 n->quota_violation_count);
3115 GNUNET_STATISTICS_update (stats,
3116 gettext_noop ("# bandwidth quota violations by other peers"),
3119 return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
3121 switch (ntohs (message->type))
3123 case GNUNET_MESSAGE_TYPE_HELLO:
3124 GNUNET_STATISTICS_update (stats,
3125 gettext_noop ("# HELLO messages received from other peers"),
3128 process_hello (plugin, message);
3130 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3131 handle_ping(plugin, message, peer, sender_address, sender_address_len);
3133 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3134 handle_pong(plugin, message, peer, sender_address, sender_address_len);
3138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3139 "Received message of type %u from `%4s', sending to all clients.\n",
3140 ntohs (message->type), GNUNET_i2s (peer));
3142 if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3144 n->quota_violation_count++;
3146 n->quota_violation_count = 0; /* back within limits */
3147 GNUNET_STATISTICS_update (stats,
3148 gettext_noop ("# payload received from other peers"),
3151 /* transmit message to all clients */
3152 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3153 im->header.size = htons (sizeof (struct InboundMessage) + msize);
3154 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3155 im->latency = GNUNET_TIME_relative_hton (n->latency);
3157 memcpy (&im[1], message, msize);
3159 while (cpos != NULL)
3161 transmit_to_client (cpos, &im->header, GNUNET_YES);
3167 ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3170 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3171 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3172 (unsigned long long) n->in_tracker.consumption_since_last_update__,
3173 (unsigned int) n->in_tracker.available_bytes_per_s__,
3174 (unsigned long long) ret.value);
3175 GNUNET_STATISTICS_update (stats,
3176 gettext_noop ("# ms throttling suggested"),
3177 (int64_t) ret.value,
3185 * Handle START-message. This is the first message sent to us
3186 * by any client which causes us to add it to our list.
3188 * @param cls closure (always NULL)
3189 * @param client identification of the client
3190 * @param message the actual message
3193 handle_start (void *cls,
3194 struct GNUNET_SERVER_Client *client,
3195 const struct GNUNET_MessageHeader *message)
3197 struct TransportClient *c;
3198 struct ConnectInfoMessage cim;
3199 struct NeighbourList *n;
3202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3203 "Received `%s' request from client\n", "START");
3208 if (c->client == client)
3210 /* client already on our list! */
3212 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3217 c = GNUNET_malloc (sizeof (struct TransportClient));
3221 if (our_hello != NULL)
3224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3225 "Sending our own `%s' to new client\n", "HELLO");
3227 transmit_to_client (c,
3228 (const struct GNUNET_MessageHeader *) our_hello,
3230 /* tell new client about all existing connections */
3231 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3232 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3236 if (GNUNET_YES == n->received_pong)
3239 cim.latency = GNUNET_TIME_relative_hton (n->latency);
3240 cim.distance = htonl (n->distance);
3241 transmit_to_client (c, &cim.header, GNUNET_NO);
3246 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3251 * Handle HELLO-message.
3253 * @param cls closure (always NULL)
3254 * @param client identification of the client
3255 * @param message the actual message
3258 handle_hello (void *cls,
3259 struct GNUNET_SERVER_Client *client,
3260 const struct GNUNET_MessageHeader *message)
3264 GNUNET_STATISTICS_update (stats,
3265 gettext_noop ("# HELLOs received from clients"),
3268 ret = process_hello (NULL, message);
3269 GNUNET_SERVER_receive_done (client, ret);
3274 * Handle SEND-message.
3276 * @param cls closure (always NULL)
3277 * @param client identification of the client
3278 * @param message the actual message
3281 handle_send (void *cls,
3282 struct GNUNET_SERVER_Client *client,
3283 const struct GNUNET_MessageHeader *message)
3285 struct TransportClient *tc;
3286 struct NeighbourList *n;
3287 const struct OutboundMessage *obm;
3288 const struct GNUNET_MessageHeader *obmm;
3292 size = ntohs (message->size);
3294 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3297 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3300 GNUNET_STATISTICS_update (stats,
3301 gettext_noop ("# payload received for other peers"),
3304 obm = (const struct OutboundMessage *) message;
3306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307 "Received `%s' request from client with target `%4s'\n",
3308 "SEND", GNUNET_i2s (&obm->peer));
3310 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3311 msize = ntohs (obmm->size);
3312 if (size != msize + sizeof (struct OutboundMessage))
3315 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3318 n = find_neighbour (&obm->peer);
3320 n = setup_new_neighbour (&obm->peer);
3322 while ((tc != NULL) && (tc->client != client))
3326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3327 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3329 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3331 transmit_to_peer (tc, NULL, ntohl (obm->priority),
3332 GNUNET_TIME_relative_ntoh (obm->timeout),
3334 ntohs (obmm->size), GNUNET_NO, n);
3335 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3340 * Handle SET_QUOTA-message.
3342 * @param cls closure (always NULL)
3343 * @param client identification of the client
3344 * @param message the actual message
3347 handle_set_quota (void *cls,
3348 struct GNUNET_SERVER_Client *client,
3349 const struct GNUNET_MessageHeader *message)
3351 const struct QuotaSetMessage *qsm =
3352 (const struct QuotaSetMessage *) message;
3353 struct NeighbourList *n;
3355 GNUNET_STATISTICS_update (stats,
3356 gettext_noop ("# SET QUOTA messages received"),
3359 n = find_neighbour (&qsm->peer);
3362 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3363 GNUNET_STATISTICS_update (stats,
3364 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3371 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3373 (unsigned int) ntohl (qsm->quota.value__),
3374 (unsigned int) n->in_tracker.available_bytes_per_s__,
3375 GNUNET_i2s (&qsm->peer));
3377 GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3379 if (0 == ntohl (qsm->quota.value__))
3380 disconnect_neighbour (n, GNUNET_NO);
3381 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3386 transmit_address_to_client (void *cls, const char *address)
3388 struct GNUNET_SERVER_TransmitContext *tc = cls;
3391 if (NULL == address)
3394 slen = strlen (address) + 1;
3395 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3396 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3397 if (NULL == address)
3398 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3403 * Handle AddressLookup-message.
3405 * @param cls closure (always NULL)
3406 * @param client identification of the client
3407 * @param message the actual message
3410 handle_address_lookup (void *cls,
3411 struct GNUNET_SERVER_Client *client,
3412 const struct GNUNET_MessageHeader *message)
3414 const struct AddressLookupMessage *alum;
3415 struct TransportPlugin *lsPlugin;
3416 const char *nameTransport;
3417 const char *address;
3419 struct GNUNET_SERVER_TransmitContext *tc;
3421 size = ntohs (message->size);
3422 if (size < sizeof (struct AddressLookupMessage))
3424 GNUNET_break_op (0);
3425 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3428 alum = (const struct AddressLookupMessage *) message;
3429 uint32_t addressLen = ntohl (alum->addrlen);
3430 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3432 GNUNET_break_op (0);
3433 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3436 address = (const char *) &alum[1];
3437 nameTransport = (const char *) &address[addressLen];
3439 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3441 GNUNET_break_op (0);
3442 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3445 struct GNUNET_TIME_Absolute timeout =
3446 GNUNET_TIME_absolute_ntoh (alum->timeout);
3447 struct GNUNET_TIME_Relative rtimeout =
3448 GNUNET_TIME_absolute_get_remaining (timeout);
3449 lsPlugin = find_transport (nameTransport);
3450 if (NULL == lsPlugin)
3452 tc = GNUNET_SERVER_transmit_context_create (client);
3453 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3454 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3455 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3458 tc = GNUNET_SERVER_transmit_context_create (client);
3459 lsPlugin->api->address_pretty_printer (cls, nameTransport,
3460 address, addressLen, GNUNET_YES,
3462 &transmit_address_to_client, tc);
3466 * List of handlers for the messages understood by this
3469 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3470 {&handle_start, NULL,
3471 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3472 {&handle_hello, NULL,
3473 GNUNET_MESSAGE_TYPE_HELLO, 0},
3474 {&handle_send, NULL,
3475 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3476 {&handle_set_quota, NULL,
3477 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3478 {&handle_address_lookup, NULL,
3479 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3486 * Setup the environment for this plugin.
3489 create_environment (struct TransportPlugin *plug)
3491 plug->env.cfg = cfg;
3492 plug->env.sched = sched;
3493 plug->env.my_identity = &my_identity;
3494 plug->env.cls = plug;
3495 plug->env.receive = &plugin_env_receive;
3496 plug->env.notify_address = &plugin_env_notify_address;
3497 plug->env.max_connections = max_connect_per_transport;
3498 plug->env.stats = stats;
3503 * Start the specified transport (load the plugin).
3506 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3508 struct TransportPlugin *plug;
3511 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3512 _("Loading `%s' transport plugin\n"), name);
3513 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3514 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3515 create_environment (plug);
3516 plug->short_name = GNUNET_strdup (name);
3517 plug->lib_name = libname;
3518 plug->next = plugins;
3520 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3521 if (plug->api == NULL)
3523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3524 _("Failed to load transport plugin for `%s'\n"), name);
3525 GNUNET_free (plug->short_name);
3526 plugins = plug->next;
3527 GNUNET_free (libname);
3534 * Called whenever a client is disconnected. Frees our
3535 * resources associated with that client.
3537 * @param cls closure
3538 * @param client identification of the client
3541 client_disconnect_notification (void *cls,
3542 struct GNUNET_SERVER_Client *client)
3544 struct TransportClient *pos;
3545 struct TransportClient *prev;
3546 struct ClientMessageQueueEntry *mqe;
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3552 "Client disconnected, cleaning up.\n");
3556 while ((pos != NULL) && (pos->client != client))
3563 while (NULL != (mqe = pos->message_queue_head))
3565 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3566 pos->message_queue_tail,
3568 pos->message_count--;
3572 clients = pos->next;
3574 prev->next = pos->next;
3575 if (GNUNET_YES == pos->tcs_pending)
3580 if (pos->th != NULL)
3582 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3585 GNUNET_break (0 == pos->message_count);
3591 * Iterator to free entries in the validation_map.
3593 * @param cls closure (unused)
3594 * @param key current key code
3595 * @param value value in the hash map (validation to abort)
3596 * @return GNUNET_YES (always)
3599 abort_validation (void *cls,
3600 const GNUNET_HashCode * key,
3603 struct ValidationEntry *va = value;
3605 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3606 GNUNET_free (va->transport_name);
3613 * Function called when the service shuts down. Unloads our plugins
3614 * and cancels pending validations.
3616 * @param cls closure, unused
3617 * @param tc task context (unused)
3620 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3622 struct TransportPlugin *plug;
3623 struct OwnAddressList *al;
3624 struct CheckHelloValidatedContext *chvc;
3626 while (neighbours != NULL)
3627 disconnect_neighbour (neighbours, GNUNET_NO);
3629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3630 "Transport service is unloading plugins...\n");
3632 while (NULL != (plug = plugins))
3634 plugins = plug->next;
3635 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3636 GNUNET_free (plug->lib_name);
3637 GNUNET_free (plug->short_name);
3638 while (NULL != (al = plug->addresses))
3640 plug->addresses = al->next;
3645 if (my_private_key != NULL)
3646 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3647 GNUNET_free_non_null (our_hello);
3649 /* free 'chvc' data structure */
3650 while (NULL != (chvc = chvc_head))
3652 chvc_head = chvc->next;
3653 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3658 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3661 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3662 validation_map = NULL;
3665 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3672 * Initiate transport service.
3674 * @param cls closure
3675 * @param s scheduler to use
3676 * @param serv the initialized server
3677 * @param c configuration to use
3681 struct GNUNET_SCHEDULER_Handle *s,
3682 struct GNUNET_SERVER_Handle *serv,
3683 const struct GNUNET_CONFIGURATION_Handle *c)
3688 unsigned long long tneigh;
3693 stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3694 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3695 /* parse configuration */
3697 GNUNET_CONFIGURATION_get_value_number (c,
3702 GNUNET_CONFIGURATION_get_value_filename (c,
3704 "HOSTKEY", &keyfile)))
3706 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3708 ("Transport service is lacking key configuration settings. Exiting.\n"));
3709 GNUNET_SCHEDULER_shutdown (s);
3712 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3715 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3716 validation_map = NULL;
3719 max_connect_per_transport = (uint32_t) tneigh;
3720 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3721 GNUNET_free (keyfile);
3722 if (my_private_key == NULL)
3724 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3726 ("Transport service could not access hostkey. Exiting.\n"));
3727 GNUNET_SCHEDULER_shutdown (s);
3730 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3733 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3734 validation_map = NULL;
3737 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3738 GNUNET_CRYPTO_hash (&my_public_key,
3739 sizeof (my_public_key), &my_identity.hashPubKey);
3740 /* setup notification */
3742 GNUNET_SERVER_disconnect_notify (server,
3743 &client_disconnect_notification, NULL);
3744 /* load plugins... */
3747 GNUNET_CONFIGURATION_get_value_string (c,
3748 "TRANSPORT", "PLUGINS", &plugs))
3750 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3751 _("Starting transport plugins `%s'\n"), plugs);
3752 pos = strtok (plugs, " ");
3755 start_transport (server, pos);
3757 pos = strtok (NULL, " ");
3759 GNUNET_free (plugs);
3761 GNUNET_SCHEDULER_add_delayed (sched,
3762 GNUNET_TIME_UNIT_FOREVER_REL,
3763 &shutdown_task, NULL);
3768 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3770 /* process client requests */
3771 GNUNET_SERVER_add_handlers (server, handlers);
3776 * The main function for the transport service.
3778 * @param argc number of arguments from the command line
3779 * @param argv command line arguments
3780 * @return 0 ok, 1 on error
3783 main (int argc, char *const *argv)
3785 return (GNUNET_OK ==
3786 GNUNET_SERVICE_run (argc,
3789 GNUNET_SERVICE_OPTION_NONE,
3790 &run, NULL)) ? 0 : 1;
3793 /* end of gnunet-service-transport.c */