2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file transport/gnunet-service-transport.c
23 * @brief low-level P2P messaging
24 * @author Christian Grothoff
27 * - This code uses 'GNUNET_a2s' for debug printing in many places,
28 * which is technically wrong since it assumes we have IP+Port
29 * (v4/v6) addresses. Once we add transports like http or smtp
30 * this will have to be changed!
33 #include "gnunet_client_lib.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_os_lib.h"
39 #include "gnunet_peerinfo_service.h"
40 #include "gnunet_plugin_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_signatures.h"
44 #include "plugin_transport.h"
45 #include "transport.h"
48 * Should we do some additional checks (to validate behavior
51 #define EXTRA_CHECKS GNUNET_YES
54 * How many messages can we have pending for a given client process
55 * before we start to drop incoming messages? We typically should
56 * have only one client and so this would be the primary buffer for
57 * messages, so the number should be chosen rather generously.
59 * The expectation here is that most of the time the queue is large
60 * enough so that a drop is virtually never required.
62 #define MAX_PENDING 128
65 * How often should we try to reconnect to a peer using a particular
66 * transport plugin before giving up? Note that the plugin may be
67 * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
69 #define MAX_CONNECT_RETRY 3
72 * Limit on the number of ready-to-run tasks when validating
73 * HELLOs. If more tasks are ready to run, we will drop
74 * HELLOs instead of validating them.
76 #define MAX_HELLO_LOAD 4
79 * How often must a peer violate bandwidth quotas before we start
80 * to simply drop its messages?
82 #define QUOTA_VIOLATION_DROP_THRESHOLD 100
85 * How long until a HELLO verification attempt should time out?
86 * Must be rather small, otherwise a partially successful HELLO
87 * validation (some addresses working) might not be available
88 * before a client's request for a connection fails for good.
89 * Besides, if a single request to an address takes a long time,
90 * then the peer is unlikely worthwhile anyway.
92 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
95 * How long will we allow sending of a ping to be delayed?
97 #define TRANSPORT_DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
100 * Priority to use for PONG messages.
102 #define TRANSPORT_PONG_PRIORITY 4
105 * How often do we re-add (cheaper) plugins to our list of plugins
106 * to try for a given connected peer?
108 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
111 * After how long do we expire an address in a HELLO that we just
112 * validated? This value is also used for our own addresses when we
115 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
119 * How long before an existing address expires should we again try to
120 * validate it? Must be (significantly) smaller than
121 * HELLO_ADDRESS_EXPIRATION.
123 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
127 * List of addresses of other peers
129 struct ForeignAddressList
132 * This is a linked list.
134 struct ForeignAddressList *next;
137 * Which ready list does this entry belong to.
139 struct ReadyList *ready_list;
142 * How long until we auto-expire this address (unless it is
143 * re-confirmed by the transport)?
145 struct GNUNET_TIME_Absolute expires;
158 * What was the last latency observed for this plugin
159 * and peer? Invalid if connected is GNUNET_NO.
161 struct GNUNET_TIME_Relative latency;
164 * If we did not successfully transmit a message to the given peer
165 * via this connection during the specified time, we should consider
166 * the connection to be dead. This is used in the case that a TCP
167 * transport simply stalls writing to the stream but does not
168 * formerly get a signal that the other peer died.
170 struct GNUNET_TIME_Absolute timeout;
173 * Are we currently connected via this address? The first time we
174 * successfully transmit or receive data to a peer via a particular
175 * address, we set this to GNUNET_YES. If we later get an error
176 * (disconnect notification, transmission failure, timeout), we set
177 * it back to GNUNET_NO.
182 * Is this plugin currently busy transmitting to the specific target?
183 * GNUNET_NO if not (initial, default state is GNUNET_NO). Internal
184 * messages do not count as 'in transmit'.
189 * Has this address been validated yet?
194 * How often have we tried to connect using this plugin? Used to
195 * discriminate against addresses that do not work well.
196 * FIXME: not yet used, but should be!
198 unsigned int connect_attempts;
201 * DV distance to this peer (1 if no DV is used).
202 * FIXME: need to set this from transport plugins!
210 * Entry in linked list of network addresses for ourselves.
212 struct OwnAddressList
215 * This is a linked list.
217 struct OwnAddressList *next;
220 * The address, actually a pointer to the end
221 * of this struct. Do not free!
226 * How long until we auto-expire this address (unless it is
227 * re-confirmed by the transport)?
229 struct GNUNET_TIME_Absolute expires;
240 * Entry in linked list of all of our plugins.
242 struct TransportPlugin
246 * This is a linked list.
248 struct TransportPlugin *next;
251 * API of the transport as returned by the plugin's
252 * initialization function.
254 struct GNUNET_TRANSPORT_PluginFunctions *api;
257 * Short name for the plugin (i.e. "tcp").
262 * Name of the library (i.e. "gnunet_plugin_transport_tcp").
267 * List of our known addresses for this transport.
269 struct OwnAddressList *addresses;
272 * Environment this transport service is using
275 struct GNUNET_TRANSPORT_PluginEnvironment env;
278 * ID of task that is used to clean up expired addresses.
280 GNUNET_SCHEDULER_TaskIdentifier address_update_task;
283 * Set to GNUNET_YES if we need to scrap the existing
284 * list of "addresses" and start fresh when we receive
285 * the next address update from a transport. Set to
286 * GNUNET_NO if we should just add the new address
287 * to the list and wait for the commit call.
293 struct NeighbourList;
296 * For each neighbour we keep a list of messages
297 * that we still want to transmit to the neighbour.
303 * This is a doubly linked list.
305 struct MessageQueue *next;
308 * This is a doubly linked list.
310 struct MessageQueue *prev;
313 * The message(s) we want to transmit, GNUNET_MessageHeader(s)
314 * stuck together in memory. Allocated at the end of this struct.
316 const char *message_buf;
319 * Size of the message buf
321 size_t message_buf_size;
324 * Client responsible for queueing the message;
325 * used to check that a client has no two messages
326 * pending for the same target. Can be NULL.
328 struct TransportClient *client;
331 * Using which specific address should we send this message?
333 struct ForeignAddressList *specific_address;
336 * Peer ID of the Neighbour this entry belongs to.
338 struct GNUNET_PeerIdentity neighbour_id;
341 * Plugin that we used for the transmission.
342 * NULL until we scheduled a transmission.
344 struct TransportPlugin *plugin;
347 * At what time should we fail?
349 struct GNUNET_TIME_Absolute timeout;
352 * Internal message of the transport system that should not be
353 * included in the usual SEND-SEND_OK transmission confirmation
354 * traffic management scheme. Typically, "internal_msg" will
355 * be set whenever "client" is NULL (but it is not strictly
361 * How important is the message?
363 unsigned int priority;
369 * For a given Neighbour, which plugins are available
370 * to talk to this peer and what are their costs?
375 * This is a linked list.
377 struct ReadyList *next;
380 * Which of our transport plugins does this entry
383 struct TransportPlugin *plugin;
386 * Transport addresses, latency, and readiness for
387 * this particular plugin.
389 struct ForeignAddressList *addresses;
395 * Entry in linked list of all of our current neighbours.
401 * This is a linked list.
403 struct NeighbourList *next;
406 * Which of our transports is connected to this peer
407 * and what is their status?
409 struct ReadyList *plugins;
412 * Head of list of messages we would like to send to this peer;
413 * must contain at most one message per client.
415 struct MessageQueue *messages_head;
418 * Tail of list of messages we would like to send to this peer; must
419 * contain at most one message per client.
421 struct MessageQueue *messages_tail;
424 * Identity of this neighbour.
426 struct GNUNET_PeerIdentity id;
429 * ID of task scheduled to run when this peer is about to
430 * time out (will free resources associated with the peer).
432 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
435 * ID of task scheduled to run when we should retry transmitting
436 * the head of the message queue.
438 GNUNET_SCHEDULER_TaskIdentifier retry_task;
441 * How long until we should consider this peer dead
442 * (if we don't receive another message in the
445 struct GNUNET_TIME_Absolute peer_timeout;
448 * At what time did we reset last_received last?
450 struct GNUNET_TIME_Absolute last_quota_update;
453 * The latency we have seen for this particular address for
454 * this particular peer. This latency may have been calculated
455 * over multiple transports. This value reflects how long it took
456 * us to receive a response when SENDING via this particular
457 * transport/neighbour/address combination!
459 * FIXME: we need to periodically send PINGs to update this
460 * latency (at least more often than the current "huge" (11h?)
463 struct GNUNET_TIME_Relative latency;
466 * DV distance to this peer (1 if no DV is used).
471 * How many bytes have we received since the "last_quota_update"
474 uint64_t last_received;
477 * Global quota for inbound traffic for the neighbour in bytes/ms.
482 * How often has the other peer (recently) violated the
483 * inbound traffic limit? Incremented by 10 per violation,
484 * decremented by 1 per non-violation (for each
487 unsigned int quota_violation_count;
490 * Have we seen an PONG from this neighbour in the past (and
491 * not had a disconnect since)?
498 * Message used to ask a peer to validate receipt (to check an address
499 * from a HELLO). Followed by the address used. Note that the
500 * recipients response does not affirm that he has this address,
501 * only that he got the challenge message.
503 struct TransportPingMessage
507 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
509 struct GNUNET_MessageHeader header;
512 * Random challenge number (in network byte order).
514 uint32_t challenge GNUNET_PACKED;
517 * Who is the intended recipient?
519 struct GNUNET_PeerIdentity target;
525 * Message used to validate a HELLO. The challenge is included in the
526 * confirmation to make matching of replies to requests possible. The
527 * signature signs the original challenge number, our public key, the
528 * sender's address (so that the sender can check that the address we
529 * saw is plausible for him and possibly detect a MiM attack) and a
530 * timestamp (to limit replay).<p>
532 * This message is followed by the address of the
533 * client that we are observing (which is part of what
536 struct TransportPongMessage
540 * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
542 struct GNUNET_MessageHeader header;
545 * For padding, always zero.
547 uint32_t reserved GNUNET_PACKED;
552 struct GNUNET_CRYPTO_RsaSignature signature;
555 * What are we signing and why?
557 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
560 * Random challenge number (in network byte order).
562 uint32_t challenge GNUNET_PACKED;
565 * Who signed this message?
567 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
570 * Size of address appended to this message
578 * Linked list of messages to be transmitted to the client. Each
579 * entry is followed by the actual message.
581 struct ClientMessageQueueEntry
584 * This is a doubly-linked list.
586 struct ClientMessageQueueEntry *next;
589 * This is a doubly-linked list.
591 struct ClientMessageQueueEntry *prev;
596 * Client connected to the transport service.
598 struct TransportClient
602 * This is a linked list.
604 struct TransportClient *next;
607 * Handle to the client.
609 struct GNUNET_SERVER_Client *client;
612 * Linked list of messages yet to be transmitted to
615 struct ClientMessageQueueEntry *message_queue_head;
618 * Tail of linked list of messages yet to be transmitted to the
621 struct ClientMessageQueueEntry *message_queue_tail;
624 * Current transmit request handle.
626 struct GNUNET_CONNECTION_TransmitHandle *th;
629 * Is a call to "transmit_send_continuation" pending? If so, we
630 * must not free this struct (even if the corresponding client
631 * disconnects) and instead only remove it from the linked list and
632 * set the "client" field to NULL.
637 * Length of the list of messages pending for this client.
639 unsigned int message_count;
645 * Entry in map of all HELLOs awaiting validation.
647 struct ValidationEntry
651 * The address, actually a pointer to the end
652 * of this struct. Do not free!
657 * Name of the transport.
659 char *transport_name;
662 * The public key of the peer.
664 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
667 * ID of task that will clean up this entry if we don't succeed
668 * with the validation first.
670 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
673 * At what time did we send this validation?
675 struct GNUNET_TIME_Absolute send_time;
683 * Challenge number we used.
691 * Context of currently active requests to peerinfo
692 * for validation of HELLOs.
694 struct CheckHelloValidatedContext
698 * This is a doubly-linked list.
700 struct CheckHelloValidatedContext *next;
703 * This is a doubly-linked list.
705 struct CheckHelloValidatedContext *prev;
708 * Hello that we are validating.
710 const struct GNUNET_HELLO_Message *hello;
713 * Context for peerinfo iteration.
714 * NULL after we are done processing peerinfo's information.
716 struct GNUNET_PEERINFO_IteratorContext *piter;
719 * Was a HELLO known for this peer to peerinfo?
729 static struct GNUNET_HELLO_Message *our_hello;
732 * "version" of "our_hello". Used to see if a given neighbour has
733 * already been sent the latest version of our HELLO message.
735 static unsigned int our_hello_version;
740 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
745 static struct GNUNET_PeerIdentity my_identity;
750 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
755 struct GNUNET_SCHEDULER_Handle *sched;
760 const struct GNUNET_CONFIGURATION_Handle *cfg;
763 * Linked list of all clients to this service.
765 static struct TransportClient *clients;
768 * All loaded plugins.
770 static struct TransportPlugin *plugins;
775 static struct GNUNET_SERVER_Handle *server;
778 * All known neighbours and their HELLOs.
780 static struct NeighbourList *neighbours;
783 * Number of neighbours we'd like to have.
785 static uint32_t max_connect_per_transport;
788 * Head of linked list.
790 static struct CheckHelloValidatedContext *chvc_head;
793 * Tail of linked list.
795 static struct CheckHelloValidatedContext *chvc_tail;
799 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
800 * of the given peer that we are currently validating).
802 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
806 * The peer specified by the given neighbour has timed-out or a plugin
807 * has disconnected. We may either need to do nothing (other plugins
808 * still up), or trigger a full disconnect and clean up. This
809 * function updates our state and do the necessary notifications.
810 * Also notifies our clients that the neighbour is now officially
813 * @param n the neighbour list entry for the peer
814 * @param check should we just check if all plugins
815 * disconnected or must we ask all plugins to
818 static void disconnect_neighbour (struct NeighbourList *n, int check);
821 * Check the ready list for the given neighbour and if a plugin is
822 * ready for transmission (and if we have a message), do so!
824 * @param neighbour target peer for which to transmit
826 static void try_transmission_to_peer (struct NeighbourList *neighbour);
830 * Find an entry in the neighbour list for a particular peer.
831 * if sender_address is not specified (NULL) then return the
832 * first matching entry. If sender_address is specified, then
833 * make sure that the address and address_len also matches.
835 * @return NULL if not found.
837 static struct NeighbourList *
838 find_neighbour (const struct GNUNET_PeerIdentity *key)
840 struct NeighbourList *head = neighbours;
842 while ((head != NULL) &&
843 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
850 * Find an entry in the transport list for a particular transport.
852 * @return NULL if not found.
854 static struct TransportPlugin *
855 find_transport (const char *short_name)
857 struct TransportPlugin *head = plugins;
858 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
865 * Update the quota values for the given neighbour now.
868 update_quota (struct NeighbourList *n)
870 struct GNUNET_TIME_Relative delta;
874 delta = GNUNET_TIME_absolute_get_duration (n->last_quota_update);
875 if (delta.value < MIN_QUOTA_REFRESH_TIME)
876 return; /* not enough time passed for doing quota update */
877 allowed = delta.value * n->quota_in;
879 if (n->last_received < allowed)
881 remaining = allowed - n->last_received;
883 remaining /= n->quota_in;
886 if (remaining > MAX_BANDWIDTH_CARRY)
887 remaining = MAX_BANDWIDTH_CARRY;
888 n->last_received = 0;
889 n->last_quota_update = GNUNET_TIME_absolute_get ();
890 n->last_quota_update.value -= remaining;
891 if (n->quota_violation_count > 0)
892 n->quota_violation_count--;
896 n->last_received -= allowed;
897 n->last_quota_update = GNUNET_TIME_absolute_get ();
898 if (n->last_received > allowed)
900 /* more than twice the allowed rate! */
901 n->quota_violation_count += 10;
908 * Function called to notify a client about the socket being ready to
909 * queue more data. "buf" will be NULL and "size" zero if the socket
910 * was closed for writing in the meantime.
913 * @param size number of bytes available in buf
914 * @param buf where the callee should write the message
915 * @return number of bytes written to buf
918 transmit_to_client_callback (void *cls, size_t size, void *buf)
920 struct TransportClient *client = cls;
921 struct ClientMessageQueueEntry *q;
924 const struct GNUNET_MessageHeader *msg;
930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
931 "Transmission to client failed, closing connection.\n");
932 /* fatal error with client, free message queue! */
933 while (NULL != (q = client->message_queue_head))
935 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
936 client->message_queue_tail,
940 client->message_count = 0;
945 while (NULL != (q = client->message_queue_head))
947 msg = (const struct GNUNET_MessageHeader *) &q[1];
948 msize = ntohs (msg->size);
949 if (msize + tsize > size)
952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
953 "Transmitting message of type %u to client.\n",
956 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
957 client->message_queue_tail,
959 memcpy (&cbuf[tsize], msg, msize);
962 client->message_count--;
966 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
967 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
969 GNUNET_TIME_UNIT_FOREVER_REL,
970 &transmit_to_client_callback,
972 GNUNET_assert (client->th != NULL);
979 * Send the specified message to the specified client. Since multiple
980 * messages may be pending for the same client at a time, this code
981 * makes sure that no message is lost.
983 * @param client client to transmit the message to
984 * @param msg the message to send
985 * @param may_drop can this message be dropped if the
986 * message queue for this client is getting far too large?
989 transmit_to_client (struct TransportClient *client,
990 const struct GNUNET_MessageHeader *msg, int may_drop)
992 struct ClientMessageQueueEntry *q;
995 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
997 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
999 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1000 client->message_count, MAX_PENDING);
1001 /* TODO: call to statistics... */
1004 msize = ntohs (msg->size);
1005 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1006 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1007 memcpy (&q[1], msg, msize);
1008 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1009 client->message_queue_tail,
1010 client->message_queue_tail,
1012 client->message_count++;
1013 if (client->th == NULL)
1015 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1017 GNUNET_TIME_UNIT_FOREVER_REL,
1018 &transmit_to_client_callback,
1020 GNUNET_assert (client->th != NULL);
1026 * Transmit a 'SEND_OK' notification to the given client for the
1029 * @param client who to notify
1030 * @param n neighbour to notify about
1031 * @param result status code for the transmission request
1034 transmit_send_ok (struct TransportClient *client,
1035 struct NeighbourList *n,
1038 struct SendOkMessage send_ok_msg;
1040 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1041 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1042 send_ok_msg.success = htonl (result);
1043 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1044 send_ok_msg.peer = n->id;
1045 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1050 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1051 * upon "completion" of a send request. This tells the API
1052 * that it is now legal to send another message to the given
1055 * @param cls closure, identifies the entry on the
1056 * message queue that was transmitted and the
1057 * client responsible for queueing the message
1058 * @param target the peer receiving the message
1059 * @param result GNUNET_OK on success, if the transmission
1060 * failed, we should not tell the client to transmit
1064 transmit_send_continuation (void *cls,
1065 const struct GNUNET_PeerIdentity *target,
1068 struct MessageQueue *mq = cls;
1069 struct NeighbourList *n;
1071 n = find_neighbour(&mq->neighbour_id);
1072 GNUNET_assert (n != NULL);
1073 if (mq->specific_address != NULL)
1075 if (result == GNUNET_OK)
1077 mq->specific_address->timeout =
1078 GNUNET_TIME_relative_to_absolute
1079 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1080 mq->specific_address->connected = GNUNET_YES;
1084 mq->specific_address->connected = GNUNET_NO;
1086 if (! mq->internal_msg)
1087 mq->specific_address->in_transmit = GNUNET_NO;
1089 if (mq->client != NULL)
1090 transmit_send_ok (mq->client, n, result);
1092 try_transmission_to_peer (n);
1093 if (result != GNUNET_OK)
1094 disconnect_neighbour (n, GNUNET_YES);
1099 * Find an address in any of the available transports for
1100 * the given neighbour that would be good for message
1101 * transmission. This is essentially the transport selection
1104 * @param neighbour for whom to select an address
1105 * @return selected address, NULL if we have none
1107 struct ForeignAddressList *
1108 find_ready_address(struct NeighbourList *neighbour)
1110 struct ReadyList *head = neighbour->plugins;
1111 struct ForeignAddressList *addresses;
1112 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1113 struct ForeignAddressList *best_address;
1115 best_address = NULL;
1116 while (head != NULL)
1118 addresses = head->addresses;
1119 while (addresses != NULL)
1121 if ( (addresses->timeout.value < now.value) &&
1122 (addresses->connected == GNUNET_YES) )
1125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1126 "Marking long-time inactive connection to `%4s' as down.\n",
1127 GNUNET_i2s (&neighbour->id));
1129 addresses->connected = GNUNET_NO;
1131 addresses = addresses->next;
1134 addresses = head->addresses;
1135 while (addresses != NULL)
1137 if ( ( (best_address == NULL) ||
1138 (addresses->connected == GNUNET_YES) ||
1139 (best_address->connected == GNUNET_NO) ) &&
1140 (addresses->in_transmit == GNUNET_NO) &&
1141 ( (best_address == NULL) ||
1142 (addresses->latency.value < best_address->latency.value)) )
1143 best_address = addresses;
1144 /* FIXME: also give lower-latency addresses that are not
1145 connected a chance some times... */
1146 addresses = addresses->next;
1151 if (best_address != NULL)
1153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1154 "Best address found has latency of %llu ms.\n",
1155 best_address->latency.value);
1158 return best_address;
1164 * We should re-try transmitting to the given peer,
1165 * hopefully we've learned something in the meantime.
1168 retry_transmission_task (void *cls,
1169 const struct GNUNET_SCHEDULER_TaskContext *tc)
1171 struct NeighbourList *n = cls;
1173 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1174 try_transmission_to_peer (n);
1179 * Check the ready list for the given neighbour and if a plugin is
1180 * ready for transmission (and if we have a message), do so!
1182 * @param neighbour target peer for which to transmit
1185 try_transmission_to_peer (struct NeighbourList *neighbour)
1187 struct ReadyList *rl;
1188 struct MessageQueue *mq;
1189 struct GNUNET_TIME_Relative timeout;
1191 if (neighbour->messages_head == NULL)
1192 return; /* nothing to do */
1194 mq = neighbour->messages_head;
1195 /* FIXME: support bi-directional use of TCP */
1196 if (mq->specific_address == NULL)
1197 mq->specific_address = find_ready_address(neighbour);
1198 if (mq->specific_address == NULL)
1200 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1201 if (timeout.value == 0)
1204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1205 "No destination address available to transmit message of size %u to peer `%4s'\n",
1206 mq->message_buf_size,
1207 GNUNET_i2s (&mq->neighbour_id));
1209 if (mq->client != NULL)
1210 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1211 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1212 neighbour->messages_tail,
1215 return; /* nobody ready */
1217 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1218 GNUNET_SCHEDULER_cancel (sched,
1219 neighbour->retry_task);
1220 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1222 &retry_transmission_task,
1225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1226 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1227 mq->message_buf_size,
1228 GNUNET_i2s (&mq->neighbour_id),
1233 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1234 neighbour->messages_tail,
1236 if (mq->specific_address->connected == GNUNET_NO)
1237 mq->specific_address->connect_attempts++;
1238 rl = mq->specific_address->ready_list;
1239 mq->plugin = rl->plugin;
1240 if (!mq->internal_msg)
1241 mq->specific_address->in_transmit = GNUNET_YES;
1243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1245 mq->message_buf_size,
1246 GNUNET_i2s (&neighbour->id),
1247 GNUNET_a2s (mq->specific_address->addr,
1248 mq->specific_address->addrlen),
1249 rl->plugin->short_name);
1251 rl->plugin->api->send (rl->plugin->api->cls,
1254 mq->message_buf_size,
1256 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1257 mq->specific_address->addr,
1258 mq->specific_address->addrlen,
1259 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1260 &transmit_send_continuation, mq);
1265 * Send the specified message to the specified peer.
1267 * @param client source of the transmission request (can be NULL)
1268 * @param peer_address ForeignAddressList where we should send this message
1269 * @param priority how important is the message
1270 * @param timeout how long do we have to transmit?
1271 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1272 * @param message_buf_size total size of all messages in message_buf
1273 * @param is_internal is this an internal message; these are pre-pended and
1274 * also do not count for plugins being "ready" to transmit
1275 * @param neighbour handle to the neighbour for transmission
1278 transmit_to_peer (struct TransportClient *client,
1279 struct ForeignAddressList *peer_address,
1280 unsigned int priority,
1281 struct GNUNET_TIME_Relative timeout,
1282 const char *message_buf,
1283 size_t message_buf_size,
1284 int is_internal, struct NeighbourList *neighbour)
1286 struct MessageQueue *mq;
1291 /* check for duplicate submission */
1292 mq = neighbour->messages_head;
1295 if (mq->client == client)
1297 /* client transmitted to same peer twice
1298 before getting SendOk! */
1306 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1307 mq->specific_address = peer_address;
1308 mq->client = client;
1309 memcpy (&mq[1], message_buf, message_buf_size);
1310 mq->message_buf = (const char*) &mq[1];
1311 mq->message_buf_size = message_buf_size;
1312 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1313 mq->internal_msg = is_internal;
1314 mq->priority = priority;
1315 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1317 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1318 neighbour->messages_tail,
1321 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1322 neighbour->messages_tail,
1323 neighbour->messages_tail,
1325 try_transmission_to_peer (neighbour);
1332 struct GeneratorContext
1334 struct TransportPlugin *plug_pos;
1335 struct OwnAddressList *addr_pos;
1336 struct GNUNET_TIME_Absolute expiration;
1344 address_generator (void *cls, size_t max, void *buf)
1346 struct GeneratorContext *gc = cls;
1349 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1351 gc->plug_pos = gc->plug_pos->next;
1352 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1354 if (NULL == gc->plug_pos)
1359 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1362 gc->addr_pos->addrlen, buf, max);
1363 gc->addr_pos = gc->addr_pos->next;
1369 * Construct our HELLO message from all of the addresses of
1370 * all of the transports.
1375 struct GNUNET_HELLO_Message *hello;
1376 struct TransportClient *cpos;
1377 struct NeighbourList *npos;
1378 struct GeneratorContext gc;
1380 gc.plug_pos = plugins;
1381 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1382 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1383 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1386 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1389 while (cpos != NULL)
1391 transmit_to_client (cpos,
1392 (const struct GNUNET_MessageHeader *) hello,
1397 GNUNET_free_non_null (our_hello);
1399 our_hello_version++;
1400 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1402 while (npos != NULL)
1405 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1406 "Transmitting updated `%s' to neighbour `%4s'\n",
1407 "HELLO", GNUNET_i2s (&npos->id));
1409 transmit_to_peer (NULL, NULL, 0,
1410 HELLO_ADDRESS_EXPIRATION,
1411 (const char *) our_hello,
1412 GNUNET_HELLO_size(our_hello),
1420 * Task used to clean up expired addresses for a plugin.
1422 * @param cls closure
1426 expire_address_task (void *cls,
1427 const struct GNUNET_SCHEDULER_TaskContext *tc);
1431 * Update the list of addresses for this plugin,
1432 * expiring those that are past their expiration date.
1434 * @param plugin addresses of which plugin should be recomputed?
1435 * @param fresh set to GNUNET_YES if a new address was added
1436 * and we need to regenerate the HELLO even if nobody
1440 update_addresses (struct TransportPlugin *plugin, int fresh)
1442 struct GNUNET_TIME_Relative min_remaining;
1443 struct GNUNET_TIME_Relative remaining;
1444 struct GNUNET_TIME_Absolute now;
1445 struct OwnAddressList *pos;
1446 struct OwnAddressList *prev;
1447 struct OwnAddressList *next;
1450 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1451 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1452 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1453 now = GNUNET_TIME_absolute_get ();
1454 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1455 expired = GNUNET_NO;
1457 pos = plugin->addresses;
1461 if (pos->expires.value < now.value)
1463 expired = GNUNET_YES;
1465 plugin->addresses = pos->next;
1467 prev->next = pos->next;
1472 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1473 if (remaining.value < min_remaining.value)
1474 min_remaining = remaining;
1480 if (expired || fresh)
1482 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1483 plugin->address_update_task
1484 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1486 &expire_address_task, plugin);
1492 * Task used to clean up expired addresses for a plugin.
1494 * @param cls closure
1498 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1500 struct TransportPlugin *plugin = cls;
1501 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1502 update_addresses (plugin, GNUNET_NO);
1507 * Function that must be called by each plugin to notify the
1508 * transport service about the addresses under which the transport
1509 * provided by the plugin can be reached.
1511 * @param cls closure
1512 * @param name name of the transport that generated the address
1513 * @param addr one of the addresses of the host, NULL for the last address
1514 * the specific address format depends on the transport
1515 * @param addrlen length of the address
1516 * @param expires when should this address automatically expire?
1519 plugin_env_notify_address (void *cls,
1523 struct GNUNET_TIME_Relative expires)
1525 struct TransportPlugin *p = cls;
1526 struct OwnAddressList *al;
1527 struct GNUNET_TIME_Absolute abex;
1529 abex = GNUNET_TIME_relative_to_absolute (expires);
1530 GNUNET_assert (p == find_transport (name));
1535 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1537 if (al->expires.value < abex.value)
1544 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1546 al->next = p->addresses;
1549 al->addrlen = addrlen;
1550 memcpy (&al[1], addr, addrlen);
1551 update_addresses (p, GNUNET_YES);
1556 * Notify all of our clients about a peer connecting.
1559 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1560 struct GNUNET_TIME_Relative latency,
1563 struct ConnectInfoMessage cim;
1564 struct TransportClient *cpos;
1567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568 "Notifying clients about connection from `%s'\n",
1571 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1572 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1573 cim.distance = htonl (distance);
1574 cim.latency = GNUNET_TIME_relative_hton (latency);
1575 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1577 while (cpos != NULL)
1579 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1586 * Notify all of our clients about a peer disconnecting.
1589 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1591 struct DisconnectInfoMessage dim;
1592 struct TransportClient *cpos;
1595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1596 "Notifying clients about lost connection to `%s'\n",
1599 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1600 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1601 dim.reserved = htonl (0);
1602 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1604 while (cpos != NULL)
1606 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1613 * Find a ForeignAddressList entry for the given neighbour
1614 * that matches the given address and transport.
1616 * @param neighbour which peer we care about
1617 * @param tname name of the transport plugin
1618 * @param addr binary address
1619 * @param addrlen length of addr
1620 * @return NULL if no such entry exists
1622 static struct ForeignAddressList *
1623 find_peer_address(struct NeighbourList *neighbour,
1628 struct ReadyList *head;
1629 struct ForeignAddressList *address_head;
1631 head = neighbour->plugins;
1632 while (head != NULL)
1634 if (0 == strcmp (tname, head->plugin->short_name))
1641 address_head = head->addresses;
1642 while ( (address_head != NULL) &&
1643 ( (address_head->addrlen != addrlen) ||
1644 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1645 address_head = address_head->next;
1646 return address_head;
1651 * Get the peer address struct for the given neighbour and
1652 * address. If it doesn't yet exist, create it.
1654 * @param neighbour which peer we care about
1655 * @param tname name of the transport plugin
1656 * @param addr binary address
1657 * @param addrlen length of addr
1658 * @return NULL if we do not have a transport plugin for 'tname'
1660 static struct ForeignAddressList *
1661 add_peer_address(struct NeighbourList *neighbour,
1666 struct ReadyList *head;
1667 struct ForeignAddressList *ret;
1669 ret = find_peer_address (neighbour, tname, addr, addrlen);
1672 head = neighbour->plugins;
1673 while (head != NULL)
1675 if (0 == strcmp (tname, head->plugin->short_name))
1681 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1682 ret->addr = (const char*) &ret[1];
1683 memcpy (&ret[1], addr, addrlen);
1684 ret->addrlen = addrlen;
1685 ret->expires = GNUNET_TIME_relative_to_absolute
1686 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1687 ret->latency = GNUNET_TIME_relative_get_forever();
1689 ret->timeout = GNUNET_TIME_relative_to_absolute
1690 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1691 ret->ready_list = head;
1692 ret->next = head->addresses;
1693 head->addresses = ret;
1699 * Closure for 'add_validated_address'.
1701 struct AddValidatedAddressContext
1704 * Entry that has been validated.
1706 const struct ValidationEntry *ve;
1709 * Flag set after we have added the address so
1710 * that we terminate the iteration next time.
1717 * Callback function used to fill a buffer of max bytes with a list of
1718 * addresses in the format used by HELLOs. Should use
1719 * "GNUNET_HELLO_add_address" as a helper function.
1721 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1722 * @param max maximum number of bytes that can be written to buf
1723 * @param buf where to write the address information
1724 * @return number of bytes written, 0 to signal the
1725 * end of the iteration.
1728 add_validated_address (void *cls,
1729 size_t max, void *buf)
1731 struct AddValidatedAddressContext *avac = cls;
1732 const struct ValidationEntry *ve = avac->ve;
1734 if (GNUNET_YES == avac->done)
1736 avac->done = GNUNET_YES;
1737 return GNUNET_HELLO_add_address (ve->transport_name,
1738 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1747 * Iterator over hash map entries. Checks if the given
1748 * validation entry is for the same challenge as what
1749 * is given in the PONG.
1751 * @param cls the 'struct TransportPongMessage*'
1752 * @param key peer identity
1753 * @param value value in the hash map ('struct ValidationEntry')
1754 * @return GNUNET_YES if we should continue to
1755 * iterate (mismatch), GNUNET_NO if not (entry matched)
1758 check_pending_validation (void *cls,
1759 const GNUNET_HashCode * key,
1762 const struct TransportPongMessage *pong = cls;
1763 struct ValidationEntry *ve = value;
1764 struct AddValidatedAddressContext avac;
1765 unsigned int challenge = ntohl(pong->challenge);
1766 struct GNUNET_HELLO_Message *hello;
1767 struct GNUNET_PeerIdentity target;
1768 struct NeighbourList *n;
1769 struct ForeignAddressList *fal;
1771 if (ve->challenge != challenge)
1775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1776 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1778 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1780 ve->transport_name);
1782 /* create the updated HELLO */
1783 GNUNET_CRYPTO_hash (&ve->publicKey,
1784 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1785 &target.hashPubKey);
1786 avac.done = GNUNET_NO;
1788 hello = GNUNET_HELLO_create (&ve->publicKey,
1789 &add_validated_address,
1791 GNUNET_PEERINFO_add_peer (cfg, sched,
1794 GNUNET_free (hello);
1795 n = find_neighbour (&target);
1798 fal = add_peer_address (n, ve->transport_name,
1801 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1802 fal->validated = GNUNET_YES;
1803 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1804 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1805 n->latency = fal->latency;
1807 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1808 n->distance = fal->distance;
1809 if (GNUNET_NO == n->received_pong)
1811 notify_clients_connect (&target, n->latency, n->distance);
1812 n->received_pong = GNUNET_YES;
1814 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1816 GNUNET_SCHEDULER_cancel (sched,
1818 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1819 try_transmission_to_peer (n);
1823 /* clean up validation entry */
1824 GNUNET_assert (GNUNET_YES ==
1825 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1828 GNUNET_SCHEDULER_cancel (sched,
1830 GNUNET_free (ve->transport_name);
1837 * Function that will be called if we receive a validation
1838 * of an address challenge that we transmitted to another
1839 * peer. Note that the validation should only be considered
1840 * acceptable if the challenge matches AND if the sender
1841 * address is at least a plausible address for this peer
1842 * (otherwise we may be seeing a MiM attack).
1844 * @param cls closure
1845 * @param message the pong message
1846 * @param peer who responded to our challenge
1847 * @param sender_address string describing our sender address (as observed
1848 * by the other peer in binary format)
1849 * @param sender_address_len number of bytes in 'sender_address'
1852 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1853 const struct GNUNET_PeerIdentity *peer,
1854 const char *sender_address,
1855 size_t sender_address_len)
1857 #if DEBUG_TRANSPORT > 1
1858 /* we get tons of these that just get discarded, only log
1859 if we are quite verbose */
1860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1861 "Receiving `%s' message from `%4s'.\n", "PONG",
1864 if (GNUNET_SYSERR !=
1865 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1867 &check_pending_validation,
1870 /* This is *expected* to happen a lot since we send
1871 PONGs to *all* known addresses of the sender of
1872 the PING, so most likely we get multiple PONGs
1873 per PING, and all but the first PONG will end up
1874 here. So really we should not print anything here
1875 unless we want to be very, very verbose... */
1876 #if DEBUG_TRANSPORT > 2
1877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1878 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1887 /* FIXME: add given address to potential pool of our addresses
1889 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1890 _("Another peer saw us using the address `%s' via `%s'.\n"),
1891 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1892 ntohs(pong->addrlen)),
1893 va->transport_name);
1899 neighbour_timeout_task (void *cls,
1900 const struct GNUNET_SCHEDULER_TaskContext *tc)
1902 struct NeighbourList *n = cls;
1905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1906 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1908 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1909 disconnect_neighbour (n, GNUNET_NO);
1914 * Create a fresh entry in our neighbour list for the given peer.
1915 * Will try to transmit our current HELLO to the new neighbour. Also
1916 * notifies our clients about the new "connection".
1918 * @param peer the peer for which we create the entry
1919 * @return the new neighbour list entry
1921 static struct NeighbourList *
1922 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1924 struct NeighbourList *n;
1925 struct TransportPlugin *tp;
1926 struct ReadyList *rl;
1928 GNUNET_assert (our_hello != NULL);
1929 n = GNUNET_malloc (sizeof (struct NeighbourList));
1930 n->next = neighbours;
1933 n->last_quota_update = GNUNET_TIME_absolute_get ();
1935 GNUNET_TIME_relative_to_absolute
1936 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1937 n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1941 if (tp->api->send != NULL)
1943 rl = GNUNET_malloc (sizeof (struct ReadyList));
1944 rl->next = n->plugins;
1947 rl->addresses = NULL;
1951 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1953 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1954 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1955 &neighbour_timeout_task, n);
1956 transmit_to_peer (NULL, NULL, 0,
1957 HELLO_ADDRESS_EXPIRATION,
1958 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1965 * Closure for 'check_address_exists'.
1967 struct CheckAddressExistsClosure
1970 * Address to check for.
1975 * Name of the transport.
1985 * Set to GNUNET_YES if the address exists.
1992 * Iterator over hash map entries. Checks if the given
1993 * validation entry is for the same address as what is given
1996 * @param cls the 'struct CheckAddressExistsClosure*'
1997 * @param key current key code (ignored)
1998 * @param value value in the hash map ('struct ValidationEntry')
1999 * @return GNUNET_YES if we should continue to
2000 * iterate (mismatch), GNUNET_NO if not (entry matched)
2003 check_address_exists (void *cls,
2004 const GNUNET_HashCode * key,
2007 struct CheckAddressExistsClosure *caec = cls;
2008 struct ValidationEntry *ve = value;
2009 if ( (0 == strcmp (caec->tname,
2010 ve->transport_name)) &&
2011 (caec->addrlen == ve->addrlen) &&
2012 (0 == memcmp (caec->addr,
2016 caec->exists = GNUNET_YES;
2024 * HELLO validation cleanup task (validation failed).
2026 * @param cls the 'struct ValidationEntry' that failed
2027 * @param tc scheduler context (unused)
2030 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2032 struct ValidationEntry *va = cls;
2033 struct GNUNET_PeerIdentity pid;
2035 GNUNET_CRYPTO_hash (&va->publicKey,
2037 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2039 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2042 GNUNET_free (va->transport_name);
2048 * Check if the given address is already being validated; if not,
2049 * append the given address to the list of entries that are being be
2050 * validated and initiate validation.
2052 * @param cls closure ('struct CheckHelloValidatedContext *')
2053 * @param tname name of the transport
2054 * @param expiration expiration time
2055 * @param addr the address
2056 * @param addrlen length of the address
2057 * @return GNUNET_OK (always)
2060 run_validation (void *cls,
2062 struct GNUNET_TIME_Absolute expiration,
2063 const void *addr, size_t addrlen)
2065 struct CheckHelloValidatedContext *chvc = cls;
2066 struct GNUNET_PeerIdentity id;
2067 struct TransportPlugin *tp;
2068 struct ValidationEntry *va;
2069 struct NeighbourList *neighbour;
2070 struct ForeignAddressList *peer_address;
2071 struct TransportPingMessage ping;
2072 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2073 struct CheckAddressExistsClosure caec;
2075 uint16_t hello_size;
2078 tp = find_transport (tname);
2081 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2082 GNUNET_ERROR_TYPE_BULK,
2084 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2088 GNUNET_HELLO_get_key (chvc->hello, &pk);
2089 GNUNET_CRYPTO_hash (&pk,
2091 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2094 caec.addrlen = addrlen;
2096 caec.exists = GNUNET_NO;
2097 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2098 &check_address_exists,
2100 if (caec.exists == GNUNET_YES)
2102 /* During validation attempts we will likely trigger the other
2103 peer trying to validate our address which in turn will cause
2104 it to send us its HELLO, so we expect to hit this case rather
2105 frequently. Only print something if we are very verbose. */
2106 #if DEBUG_TRANSPORT > 1
2107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2108 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2109 GNUNET_a2s (addr, addrlen),
2115 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2116 va->transport_name = GNUNET_strdup (tname);
2117 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2119 va->send_time = GNUNET_TIME_absolute_get();
2120 va->addr = (const void*) &va[1];
2121 memcpy (&va[1], addr, addrlen);
2122 va->addrlen = addrlen;
2123 GNUNET_HELLO_get_key (chvc->hello,
2125 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2126 HELLO_VERIFICATION_TIMEOUT,
2127 &timeout_hello_validation,
2129 GNUNET_CONTAINER_multihashmap_put (validation_map,
2132 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2133 neighbour = find_neighbour(&id);
2134 if (neighbour == NULL)
2135 neighbour = setup_new_neighbour(&id);
2136 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2137 GNUNET_assert(peer_address != NULL);
2138 hello_size = GNUNET_HELLO_size(our_hello);
2139 tsize = sizeof(struct TransportPingMessage) + hello_size;
2140 message_buf = GNUNET_malloc(tsize);
2141 ping.challenge = htonl(va->challenge);
2142 ping.header.size = htons(sizeof(struct TransportPingMessage));
2143 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2144 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2145 memcpy(message_buf, our_hello, hello_size);
2146 memcpy(&message_buf[hello_size],
2148 sizeof(struct TransportPingMessage));
2150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2152 GNUNET_a2s (addr, addrlen),
2155 "HELLO", hello_size,
2156 "PING", sizeof (struct TransportPingMessage));
2158 transmit_to_peer (NULL, peer_address,
2159 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2160 HELLO_VERIFICATION_TIMEOUT,
2162 GNUNET_YES, neighbour);
2163 GNUNET_free(message_buf);
2169 * Add the given address to the list of foreign addresses
2170 * available for the given peer (check for duplicates).
2172 * @param cls the respective 'struct NeighbourList' to update
2173 * @param tname name of the transport
2174 * @param expiration expiration time
2175 * @param addr the address
2176 * @param addrlen length of the address
2177 * @return GNUNET_OK (always)
2180 add_to_foreign_address_list (void *cls,
2182 struct GNUNET_TIME_Absolute expiration,
2183 const void *addr, size_t addrlen)
2185 struct NeighbourList *n = cls;
2186 struct ForeignAddressList *fal;
2188 fal = find_peer_address (n, tname, addr, addrlen);
2192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2194 GNUNET_a2s (addr, addrlen),
2196 GNUNET_i2s (&n->id),
2199 fal = add_peer_address (n, tname, addr, addrlen);
2203 fal->expires = GNUNET_TIME_absolute_max (expiration,
2205 fal->validated = GNUNET_YES;
2211 * Check if addresses in validated hello "h" overlap with
2212 * those in "chvc->hello" and validate the rest.
2214 * @param cls closure
2215 * @param peer id of the peer, NULL for last call
2216 * @param h hello message for the peer (can be NULL)
2217 * @param trust amount of trust we have in the peer (not used)
2220 check_hello_validated (void *cls,
2221 const struct GNUNET_PeerIdentity *peer,
2222 const struct GNUNET_HELLO_Message *h,
2225 struct CheckHelloValidatedContext *chvc = cls;
2226 struct GNUNET_HELLO_Message *plain_hello;
2227 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2228 struct GNUNET_PeerIdentity target;
2229 struct NeighbourList *n;
2234 GNUNET_CONTAINER_DLL_remove (chvc_head,
2237 if (GNUNET_NO == chvc->hello_known)
2239 /* notify PEERINFO about the peer now, so that we at least
2240 have the public key if some other component needs it */
2241 GNUNET_HELLO_get_key (chvc->hello, &pk);
2242 GNUNET_CRYPTO_hash (&pk,
2243 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2244 &target.hashPubKey);
2245 plain_hello = GNUNET_HELLO_create (&pk,
2248 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2249 GNUNET_free (plain_hello);
2251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2252 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2254 GNUNET_i2s (&target));
2256 GNUNET_HELLO_iterate_addresses (chvc->hello,
2266 chvc->hello_known = GNUNET_YES;
2267 n = find_neighbour (peer);
2270 GNUNET_HELLO_iterate_addresses (h,
2272 &add_to_foreign_address_list,
2274 try_transmission_to_peer (n);
2276 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2278 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2284 * Process HELLO-message.
2286 * @param plugin transport involved, may be NULL
2287 * @param message the actual message
2288 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2291 process_hello (struct TransportPlugin *plugin,
2292 const struct GNUNET_MessageHeader *message)
2295 struct GNUNET_PeerIdentity target;
2296 const struct GNUNET_HELLO_Message *hello;
2297 struct CheckHelloValidatedContext *chvc;
2298 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2300 hsize = ntohs (message->size);
2301 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2302 (hsize < sizeof (struct GNUNET_MessageHeader)))
2305 return GNUNET_SYSERR;
2307 /* first, check if load is too high */
2308 if (GNUNET_SCHEDULER_get_load (sched,
2309 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2311 /* TODO: call to stats? */
2314 hello = (const struct GNUNET_HELLO_Message *) message;
2315 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2317 GNUNET_break_op (0);
2318 return GNUNET_SYSERR;
2320 GNUNET_CRYPTO_hash (&publicKey,
2321 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2322 &target.hashPubKey);
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "Processing `%s' message for `%4s' of size %u\n",
2327 GNUNET_i2s (&target),
2328 GNUNET_HELLO_size(hello));
2331 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2332 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2333 memcpy (&chvc[1], hello, hsize);
2334 GNUNET_CONTAINER_DLL_insert (chvc_head,
2337 /* finally, check if HELLO was previously validated
2338 (continuation will then schedule actual validation) */
2339 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2343 HELLO_VERIFICATION_TIMEOUT,
2344 &check_hello_validated, chvc);
2350 * The peer specified by the given neighbour has timed-out or a plugin
2351 * has disconnected. We may either need to do nothing (other plugins
2352 * still up), or trigger a full disconnect and clean up. This
2353 * function updates our state and does the necessary notifications.
2354 * Also notifies our clients that the neighbour is now officially
2357 * @param n the neighbour list entry for the peer
2358 * @param check should we just check if all plugins
2359 * disconnected or must we ask all plugins to
2363 disconnect_neighbour (struct NeighbourList *n, int check)
2365 struct ReadyList *rpos;
2366 struct NeighbourList *npos;
2367 struct NeighbourList *nprev;
2368 struct MessageQueue *mq;
2369 struct ForeignAddressList *peer_addresses;
2370 struct ForeignAddressList *peer_pos;
2372 if (GNUNET_YES == check)
2375 while (NULL != rpos)
2377 peer_addresses = rpos->addresses;
2378 while (peer_addresses != NULL)
2380 if (GNUNET_YES == peer_addresses->connected)
2381 return; /* still connected */
2382 peer_addresses = peer_addresses->next;
2388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2389 "Disconnecting from `%4s'\n",
2390 GNUNET_i2s (&n->id));
2392 /* remove n from neighbours list */
2395 while ((npos != NULL) && (npos != n))
2400 GNUNET_assert (npos != NULL);
2402 neighbours = n->next;
2404 nprev->next = n->next;
2406 /* notify all clients about disconnect */
2407 if (GNUNET_YES == n->received_pong)
2408 notify_clients_disconnect (&n->id);
2410 /* clean up all plugins, cancel connections and pending transmissions */
2411 while (NULL != (rpos = n->plugins))
2413 n->plugins = rpos->next;
2414 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2416 while (rpos->addresses != NULL)
2418 peer_pos = rpos->addresses;
2419 rpos->addresses = peer_pos->next;
2420 GNUNET_free(peer_pos);
2425 /* free all messages on the queue */
2426 while (NULL != (mq = n->messages_head))
2428 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2431 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2433 sizeof(struct GNUNET_PeerIdentity)));
2436 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2438 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2439 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2441 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2443 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2444 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2446 /* finally, free n itself */
2452 * We have received a PING message from someone. Need to send a PONG message
2453 * in response to the peer by any means necessary.
2455 * FIXME: With something like TCP where a connection exists, we may
2456 * want to send it that way. But the current API does not seem to
2457 * allow us to do so (can't tell this to the transport!)
2460 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2461 const struct GNUNET_PeerIdentity *peer,
2462 const char *sender_address,
2463 size_t sender_address_len)
2465 struct TransportPlugin *plugin = cls;
2466 struct TransportPingMessage *ping;
2467 struct TransportPongMessage *pong;
2469 struct NeighbourList *n;
2470 struct ReadyList *rl;
2471 struct ForeignAddressList *fal;
2473 msize = ntohs (message->size);
2474 if (msize < sizeof (struct TransportPingMessage))
2476 GNUNET_break_op (0);
2477 return GNUNET_SYSERR;
2479 ping = (struct TransportPingMessage *) message;
2480 if (0 != memcmp (&ping->target,
2481 plugin->env.my_identity,
2482 sizeof (struct GNUNET_PeerIdentity)))
2484 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2485 _("Received `%s' message not destined for me!\n"),
2487 return GNUNET_SYSERR;
2490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2491 "Processing `%s' from `%s'\n",
2493 GNUNET_a2s ((const struct sockaddr *)sender_address,
2494 sender_address_len));
2496 msize -= sizeof (struct TransportPingMessage);
2497 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2498 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2499 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2500 pong->purpose.size =
2501 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2503 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2504 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2505 pong->challenge = ping->challenge;
2506 pong->addrlen = htons(sender_address_len);
2507 memcpy(&pong->signer,
2509 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2510 memcpy (&pong[1], sender_address, sender_address_len);
2511 GNUNET_assert (GNUNET_OK ==
2512 GNUNET_CRYPTO_rsa_sign (my_private_key,
2513 &pong->purpose, &pong->signature));
2515 n = find_neighbour(peer);
2517 n = setup_new_neighbour(peer);
2518 /* broadcast 'PONG' to all available addresses */
2522 fal = rl->addresses;
2525 transmit_to_peer(NULL, fal,
2526 TRANSPORT_PONG_PRIORITY,
2527 HELLO_VERIFICATION_TIMEOUT,
2529 ntohs(pong->header.size),
2542 * Function called by the plugin for each received message.
2543 * Update data volumes, possibly notify plugins about
2544 * reducing the rate at which they read from the socket
2545 * and generally forward to our receive callback.
2547 * @param cls the "struct TransportPlugin *" we gave to the plugin
2548 * @param message the message, NULL if peer was disconnected
2549 * @param distance the transport cost to this peer (not latency!)
2550 * @param sender_address the address that the sender reported
2551 * (opaque to transport service)
2552 * @param sender_address_len the length of the sender address
2553 * @param peer (claimed) identity of the other peer
2554 * @return the new service_context that the plugin should use
2555 * for future receive calls for messages from this
2560 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2561 const struct GNUNET_MessageHeader *message,
2562 unsigned int distance, const char *sender_address,
2563 size_t sender_address_len)
2565 struct ReadyList *service_context;
2566 struct TransportPlugin *plugin = cls;
2567 struct TransportClient *cpos;
2568 struct InboundMessage *im;
2569 struct ForeignAddressList *peer_address;
2571 struct NeighbourList *n;
2573 n = find_neighbour (peer);
2576 if (message == NULL)
2577 return; /* disconnect of peer already marked down */
2578 n = setup_new_neighbour (peer);
2580 service_context = n->plugins;
2581 while ((service_context != NULL) && (plugin != service_context->plugin))
2582 service_context = service_context->next;
2583 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2584 if (message == NULL)
2587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2588 "Receive failed from `%4s', triggering disconnect\n",
2589 GNUNET_i2s (&n->id));
2591 /* TODO: call stats */
2592 disconnect_neighbour (n, GNUNET_YES);
2595 peer_address = add_peer_address(n,
2598 sender_address_len);
2599 if (peer_address != NULL)
2601 peer_address->distance = distance;
2602 if (peer_address->connected == GNUNET_NO)
2604 peer_address->connected = GNUNET_YES;
2605 peer_address->connect_attempts++;
2607 peer_address->timeout
2609 GNUNET_TIME_relative_to_absolute
2610 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2612 /* update traffic received amount ... */
2613 msize = ntohs (message->size);
2614 n->last_received += msize;
2615 n->distance = distance;
2617 GNUNET_TIME_relative_to_absolute
2618 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2619 GNUNET_SCHEDULER_cancel (sched,
2622 GNUNET_SCHEDULER_add_delayed (sched,
2623 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2624 &neighbour_timeout_task, n);
2626 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2628 /* dropping message due to frequent inbound volume violations! */
2629 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2630 GNUNET_ERROR_TYPE_BULK,
2632 ("Dropping incoming message due to repeated bandwidth quota violations (total of %u).\n"), n->quota_violation_count);
2633 /* TODO: call stats */
2636 switch (ntohs (message->type))
2638 case GNUNET_MESSAGE_TYPE_HELLO:
2639 process_hello (plugin, message);
2641 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2642 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2644 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2645 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2650 "Received message of type %u from `%4s', sending to all clients.\n",
2651 ntohs (message->type), GNUNET_i2s (peer));
2653 /* transmit message to all clients */
2654 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2655 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2656 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2657 im->latency = GNUNET_TIME_relative_hton (n->latency);
2659 memcpy (&im[1], message, msize);
2661 while (cpos != NULL)
2663 transmit_to_client (cpos, &im->header, GNUNET_YES);
2672 * Handle START-message. This is the first message sent to us
2673 * by any client which causes us to add it to our list.
2675 * @param cls closure (always NULL)
2676 * @param client identification of the client
2677 * @param message the actual message
2680 handle_start (void *cls,
2681 struct GNUNET_SERVER_Client *client,
2682 const struct GNUNET_MessageHeader *message)
2684 struct TransportClient *c;
2685 struct ConnectInfoMessage cim;
2686 struct NeighbourList *n;
2689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2690 "Received `%s' request from client\n", "START");
2695 if (c->client == client)
2697 /* client already on our list! */
2699 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2704 c = GNUNET_malloc (sizeof (struct TransportClient));
2708 if (our_hello != NULL)
2711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712 "Sending our own `%s' to new client\n", "HELLO");
2714 transmit_to_client (c,
2715 (const struct GNUNET_MessageHeader *) our_hello,
2717 /* tell new client about all existing connections */
2718 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2719 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2723 if (GNUNET_YES == n->received_pong)
2726 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2727 cim.distance = htonl (n->distance);
2728 transmit_to_client (c, &cim.header, GNUNET_NO);
2733 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2738 * Handle HELLO-message.
2740 * @param cls closure (always NULL)
2741 * @param client identification of the client
2742 * @param message the actual message
2745 handle_hello (void *cls,
2746 struct GNUNET_SERVER_Client *client,
2747 const struct GNUNET_MessageHeader *message)
2751 ret = process_hello (NULL, message);
2752 GNUNET_SERVER_receive_done (client, ret);
2757 * Handle SEND-message.
2759 * @param cls closure (always NULL)
2760 * @param client identification of the client
2761 * @param message the actual message
2764 handle_send (void *cls,
2765 struct GNUNET_SERVER_Client *client,
2766 const struct GNUNET_MessageHeader *message)
2768 struct TransportClient *tc;
2769 struct NeighbourList *n;
2770 const struct OutboundMessage *obm;
2771 const struct GNUNET_MessageHeader *obmm;
2775 size = ntohs (message->size);
2777 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2780 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2783 obm = (const struct OutboundMessage *) message;
2785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2786 "Received `%s' request from client with target `%4s'\n",
2787 "SEND", GNUNET_i2s (&obm->peer));
2789 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2790 msize = ntohs (obmm->size);
2791 if (size != msize + sizeof (struct OutboundMessage))
2794 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2797 n = find_neighbour (&obm->peer);
2799 n = setup_new_neighbour (&obm->peer);
2801 while ((tc != NULL) && (tc->client != client))
2805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2806 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2808 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2810 transmit_to_peer (tc, NULL, ntohl (obm->priority),
2811 GNUNET_TIME_relative_ntoh (obm->timeout),
2813 ntohs (obmm->size), GNUNET_NO, n);
2814 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2819 * Handle SET_QUOTA-message.
2821 * @param cls closure (always NULL)
2822 * @param client identification of the client
2823 * @param message the actual message
2826 handle_set_quota (void *cls,
2827 struct GNUNET_SERVER_Client *client,
2828 const struct GNUNET_MessageHeader *message)
2830 const struct QuotaSetMessage *qsm =
2831 (const struct QuotaSetMessage *) message;
2832 struct NeighbourList *n;
2833 struct TransportPlugin *p;
2834 struct ReadyList *rl;
2836 n = find_neighbour (&qsm->peer);
2839 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2845 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
2846 "SET_QUOTA", ntohl(qsm->quota_in), n->quota_in, GNUNET_i2s (&qsm->peer));
2850 if (n->quota_in < ntohl (qsm->quota_in))
2851 n->last_quota_update = GNUNET_TIME_absolute_get ();
2852 n->quota_in = ntohl (qsm->quota_in);
2857 p->api->set_receive_quota (p->api->cls,
2858 &qsm->peer, ntohl (qsm->quota_in));
2861 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2866 transmit_address_to_client (void *cls, const char *address)
2868 struct GNUNET_SERVER_TransmitContext *tc = cls;
2871 if (NULL == address)
2874 slen = strlen (address) + 1;
2875 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
2876 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2877 if (NULL == address)
2878 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
2883 * Handle AddressLookup-message.
2885 * @param cls closure (always NULL)
2886 * @param client identification of the client
2887 * @param message the actual message
2890 handle_address_lookup (void *cls,
2891 struct GNUNET_SERVER_Client *client,
2892 const struct GNUNET_MessageHeader *message)
2894 const struct AddressLookupMessage *alum;
2895 struct TransportPlugin *lsPlugin;
2896 const char *nameTransport;
2897 const char *address;
2899 struct GNUNET_SERVER_TransmitContext *tc;
2901 size = ntohs (message->size);
2902 if (size < sizeof (struct AddressLookupMessage))
2904 GNUNET_break_op (0);
2905 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2908 alum = (const struct AddressLookupMessage *) message;
2909 uint32_t addressLen = ntohl (alum->addrlen);
2910 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
2912 GNUNET_break_op (0);
2913 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2916 address = (const char *) &alum[1];
2917 nameTransport = (const char *) &address[addressLen];
2919 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
2921 GNUNET_break_op (0);
2922 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2925 struct GNUNET_TIME_Absolute timeout =
2926 GNUNET_TIME_absolute_ntoh (alum->timeout);
2927 struct GNUNET_TIME_Relative rtimeout =
2928 GNUNET_TIME_absolute_get_remaining (timeout);
2929 lsPlugin = find_transport (nameTransport);
2930 if (NULL == lsPlugin)
2932 tc = GNUNET_SERVER_transmit_context_create (client);
2933 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
2934 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2935 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2938 tc = GNUNET_SERVER_transmit_context_create (client);
2939 lsPlugin->api->address_pretty_printer (cls, nameTransport,
2940 address, addressLen, GNUNET_YES,
2942 &transmit_address_to_client, tc);
2946 * List of handlers for the messages understood by this
2949 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2950 {&handle_start, NULL,
2951 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2952 {&handle_hello, NULL,
2953 GNUNET_MESSAGE_TYPE_HELLO, 0},
2954 {&handle_send, NULL,
2955 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2956 {&handle_set_quota, NULL,
2957 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2958 {&handle_address_lookup, NULL,
2959 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2966 * Setup the environment for this plugin.
2969 create_environment (struct TransportPlugin *plug)
2971 plug->env.cfg = cfg;
2972 plug->env.sched = sched;
2973 plug->env.my_identity = &my_identity;
2974 plug->env.cls = plug;
2975 plug->env.receive = &plugin_env_receive;
2976 plug->env.notify_address = &plugin_env_notify_address;
2977 plug->env.default_quota_in =
2978 (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2979 plug->env.max_connections = max_connect_per_transport;
2984 * Start the specified transport (load the plugin).
2987 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2989 struct TransportPlugin *plug;
2992 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2993 _("Loading `%s' transport plugin\n"), name);
2994 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2995 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2996 create_environment (plug);
2997 plug->short_name = GNUNET_strdup (name);
2998 plug->lib_name = libname;
2999 plug->next = plugins;
3001 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3002 if (plug->api == NULL)
3004 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3005 _("Failed to load transport plugin for `%s'\n"), name);
3006 GNUNET_free (plug->short_name);
3007 plugins = plug->next;
3008 GNUNET_free (libname);
3015 * Called whenever a client is disconnected. Frees our
3016 * resources associated with that client.
3018 * @param cls closure
3019 * @param client identification of the client
3022 client_disconnect_notification (void *cls,
3023 struct GNUNET_SERVER_Client *client)
3025 struct TransportClient *pos;
3026 struct TransportClient *prev;
3027 struct ClientMessageQueueEntry *mqe;
3032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3033 "Client disconnected, cleaning up.\n");
3037 while ((pos != NULL) && (pos->client != client))
3044 while (NULL != (mqe = pos->message_queue_head))
3046 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3047 pos->message_queue_tail,
3049 pos->message_count--;
3053 clients = pos->next;
3055 prev->next = pos->next;
3056 if (GNUNET_YES == pos->tcs_pending)
3061 if (pos->th != NULL)
3063 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3066 GNUNET_break (0 == pos->message_count);
3072 * Iterator to free entries in the validation_map.
3074 * @param cls closure (unused)
3075 * @param key current key code
3076 * @param value value in the hash map (validation to abort)
3077 * @return GNUNET_YES (always)
3080 abort_validation (void *cls,
3081 const GNUNET_HashCode * key,
3084 struct ValidationEntry *va = value;
3086 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3087 GNUNET_free (va->transport_name);
3094 * Function called when the service shuts down. Unloads our plugins
3095 * and cancels pending validations.
3097 * @param cls closure, unused
3098 * @param tc task context (unused)
3101 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3103 struct TransportPlugin *plug;
3104 struct OwnAddressList *al;
3105 struct CheckHelloValidatedContext *chvc;
3107 while (neighbours != NULL)
3108 disconnect_neighbour (neighbours, GNUNET_NO);
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3111 "Transport service is unloading plugins...\n");
3113 while (NULL != (plug = plugins))
3115 plugins = plug->next;
3116 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3117 GNUNET_free (plug->lib_name);
3118 GNUNET_free (plug->short_name);
3119 while (NULL != (al = plug->addresses))
3121 plug->addresses = al->next;
3126 if (my_private_key != NULL)
3127 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3128 GNUNET_free_non_null (our_hello);
3130 /* free 'chvc' data structure */
3131 while (NULL != (chvc = chvc_head))
3133 chvc_head = chvc->next;
3134 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3139 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3142 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3147 * Initiate transport service.
3149 * @param cls closure
3150 * @param s scheduler to use
3151 * @param serv the initialized server
3152 * @param c configuration to use
3156 struct GNUNET_SCHEDULER_Handle *s,
3157 struct GNUNET_SERVER_Handle *serv,
3158 const struct GNUNET_CONFIGURATION_Handle *c)
3163 unsigned long long tneigh;
3168 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3169 /* parse configuration */
3171 GNUNET_CONFIGURATION_get_value_number (c,
3176 GNUNET_CONFIGURATION_get_value_filename (c,
3178 "HOSTKEY", &keyfile)))
3180 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3182 ("Transport service is lacking key configuration settings. Exiting.\n"));
3183 GNUNET_SCHEDULER_shutdown (s);
3186 max_connect_per_transport = (uint32_t) tneigh;
3187 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3188 GNUNET_free (keyfile);
3189 if (my_private_key == NULL)
3191 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3193 ("Transport service could not access hostkey. Exiting.\n"));
3194 GNUNET_SCHEDULER_shutdown (s);
3197 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3198 GNUNET_CRYPTO_hash (&my_public_key,
3199 sizeof (my_public_key), &my_identity.hashPubKey);
3200 /* setup notification */
3202 GNUNET_SERVER_disconnect_notify (server,
3203 &client_disconnect_notification, NULL);
3204 /* load plugins... */
3207 GNUNET_CONFIGURATION_get_value_string (c,
3208 "TRANSPORT", "PLUGINS", &plugs))
3210 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3211 _("Starting transport plugins `%s'\n"), plugs);
3212 pos = strtok (plugs, " ");
3215 start_transport (server, pos);
3217 pos = strtok (NULL, " ");
3219 GNUNET_free (plugs);
3221 GNUNET_SCHEDULER_add_delayed (sched,
3222 GNUNET_TIME_UNIT_FOREVER_REL,
3223 &shutdown_task, NULL);
3228 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3230 /* process client requests */
3231 GNUNET_SERVER_add_handlers (server, handlers);
3236 * The main function for the transport service.
3238 * @param argc number of arguments from the command line
3239 * @param argv command line arguments
3240 * @return 0 ok, 1 on error
3243 main (int argc, char *const *argv)
3245 return (GNUNET_OK ==
3246 GNUNET_SERVICE_run (argc,
3249 GNUNET_SERVICE_OPTION_NONE,
3250 &run, NULL)) ? 0 : 1;
3253 /* end of gnunet-service-transport.c */