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.
867 * @param n neighbour to update
868 * @param force GNUNET_YES to force recalculation now
871 update_quota (struct NeighbourList *n,
874 struct GNUNET_TIME_Absolute now;
875 unsigned long long delta;
879 now = GNUNET_TIME_absolute_get ();
880 delta = now.value - n->last_quota_update.value;
881 allowed = n->quota_in * delta;
882 if ( (delta < MIN_QUOTA_REFRESH_TIME) &&
884 (allowed < 32 * 1024) )
885 return; /* too early, not enough data */
886 if (n->last_received < allowed)
888 remaining = allowed - n->last_received;
890 remaining /= n->quota_in;
893 if (remaining > MAX_BANDWIDTH_CARRY)
894 remaining = MAX_BANDWIDTH_CARRY;
895 n->last_received = 0;
896 n->last_quota_update = now;
897 n->last_quota_update.value -= remaining;
898 if (n->quota_violation_count > 0)
899 n->quota_violation_count--;
903 n->last_received -= allowed;
904 n->last_quota_update = now;
905 if (n->last_received > allowed)
907 /* much more than the allowed rate! */
908 n->quota_violation_count += 10;
915 * Function called to notify a client about the socket being ready to
916 * queue more data. "buf" will be NULL and "size" zero if the socket
917 * was closed for writing in the meantime.
920 * @param size number of bytes available in buf
921 * @param buf where the callee should write the message
922 * @return number of bytes written to buf
925 transmit_to_client_callback (void *cls, size_t size, void *buf)
927 struct TransportClient *client = cls;
928 struct ClientMessageQueueEntry *q;
931 const struct GNUNET_MessageHeader *msg;
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Transmission to client failed, closing connection.\n");
939 /* fatal error with client, free message queue! */
940 while (NULL != (q = client->message_queue_head))
942 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
943 client->message_queue_tail,
947 client->message_count = 0;
952 while (NULL != (q = client->message_queue_head))
954 msg = (const struct GNUNET_MessageHeader *) &q[1];
955 msize = ntohs (msg->size);
956 if (msize + tsize > size)
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
960 "Transmitting message of type %u to client.\n",
963 GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
964 client->message_queue_tail,
966 memcpy (&cbuf[tsize], msg, msize);
969 client->message_count--;
973 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
974 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
976 GNUNET_TIME_UNIT_FOREVER_REL,
977 &transmit_to_client_callback,
979 GNUNET_assert (client->th != NULL);
986 * Send the specified message to the specified client. Since multiple
987 * messages may be pending for the same client at a time, this code
988 * makes sure that no message is lost.
990 * @param client client to transmit the message to
991 * @param msg the message to send
992 * @param may_drop can this message be dropped if the
993 * message queue for this client is getting far too large?
996 transmit_to_client (struct TransportClient *client,
997 const struct GNUNET_MessageHeader *msg, int may_drop)
999 struct ClientMessageQueueEntry *q;
1002 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1004 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1006 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
1007 client->message_count, MAX_PENDING);
1008 /* TODO: call to statistics... */
1011 msize = ntohs (msg->size);
1012 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1013 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1014 memcpy (&q[1], msg, msize);
1015 GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1016 client->message_queue_tail,
1017 client->message_queue_tail,
1019 client->message_count++;
1020 if (client->th == NULL)
1022 client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1024 GNUNET_TIME_UNIT_FOREVER_REL,
1025 &transmit_to_client_callback,
1027 GNUNET_assert (client->th != NULL);
1033 * Transmit a 'SEND_OK' notification to the given client for the
1036 * @param client who to notify
1037 * @param n neighbour to notify about
1038 * @param result status code for the transmission request
1041 transmit_send_ok (struct TransportClient *client,
1042 struct NeighbourList *n,
1045 struct SendOkMessage send_ok_msg;
1047 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1048 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1049 send_ok_msg.success = htonl (result);
1050 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1051 send_ok_msg.peer = n->id;
1052 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1057 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1058 * upon "completion" of a send request. This tells the API
1059 * that it is now legal to send another message to the given
1062 * @param cls closure, identifies the entry on the
1063 * message queue that was transmitted and the
1064 * client responsible for queueing the message
1065 * @param target the peer receiving the message
1066 * @param result GNUNET_OK on success, if the transmission
1067 * failed, we should not tell the client to transmit
1071 transmit_send_continuation (void *cls,
1072 const struct GNUNET_PeerIdentity *target,
1075 struct MessageQueue *mq = cls;
1076 struct NeighbourList *n;
1078 n = find_neighbour(&mq->neighbour_id);
1079 GNUNET_assert (n != NULL);
1080 if (mq->specific_address != NULL)
1082 if (result == GNUNET_OK)
1084 mq->specific_address->timeout =
1085 GNUNET_TIME_relative_to_absolute
1086 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1087 mq->specific_address->connected = GNUNET_YES;
1091 mq->specific_address->connected = GNUNET_NO;
1093 if (! mq->internal_msg)
1094 mq->specific_address->in_transmit = GNUNET_NO;
1096 if (mq->client != NULL)
1097 transmit_send_ok (mq->client, n, result);
1099 try_transmission_to_peer (n);
1100 if (result != GNUNET_OK)
1101 disconnect_neighbour (n, GNUNET_YES);
1106 * Find an address in any of the available transports for
1107 * the given neighbour that would be good for message
1108 * transmission. This is essentially the transport selection
1111 * @param neighbour for whom to select an address
1112 * @return selected address, NULL if we have none
1114 struct ForeignAddressList *
1115 find_ready_address(struct NeighbourList *neighbour)
1117 struct ReadyList *head = neighbour->plugins;
1118 struct ForeignAddressList *addresses;
1119 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1120 struct ForeignAddressList *best_address;
1122 best_address = NULL;
1123 while (head != NULL)
1125 addresses = head->addresses;
1126 while (addresses != NULL)
1128 if ( (addresses->timeout.value < now.value) &&
1129 (addresses->connected == GNUNET_YES) )
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "Marking long-time inactive connection to `%4s' as down.\n",
1134 GNUNET_i2s (&neighbour->id));
1136 addresses->connected = GNUNET_NO;
1138 addresses = addresses->next;
1141 addresses = head->addresses;
1142 while (addresses != NULL)
1144 if ( ( (best_address == NULL) ||
1145 (addresses->connected == GNUNET_YES) ||
1146 (best_address->connected == GNUNET_NO) ) &&
1147 (addresses->in_transmit == GNUNET_NO) &&
1148 ( (best_address == NULL) ||
1149 (addresses->latency.value < best_address->latency.value)) )
1150 best_address = addresses;
1151 /* FIXME: also give lower-latency addresses that are not
1152 connected a chance some times... */
1153 addresses = addresses->next;
1158 if (best_address != NULL)
1160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1161 "Best address found has latency of %llu ms.\n",
1162 best_address->latency.value);
1165 return best_address;
1171 * We should re-try transmitting to the given peer,
1172 * hopefully we've learned something in the meantime.
1175 retry_transmission_task (void *cls,
1176 const struct GNUNET_SCHEDULER_TaskContext *tc)
1178 struct NeighbourList *n = cls;
1180 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1181 try_transmission_to_peer (n);
1186 * Check the ready list for the given neighbour and if a plugin is
1187 * ready for transmission (and if we have a message), do so!
1189 * @param neighbour target peer for which to transmit
1192 try_transmission_to_peer (struct NeighbourList *neighbour)
1194 struct ReadyList *rl;
1195 struct MessageQueue *mq;
1196 struct GNUNET_TIME_Relative timeout;
1198 if (neighbour->messages_head == NULL)
1199 return; /* nothing to do */
1201 mq = neighbour->messages_head;
1202 /* FIXME: support bi-directional use of TCP */
1203 if (mq->specific_address == NULL)
1204 mq->specific_address = find_ready_address(neighbour);
1205 if (mq->specific_address == NULL)
1207 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1208 if (timeout.value == 0)
1211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212 "No destination address available to transmit message of size %u to peer `%4s'\n",
1213 mq->message_buf_size,
1214 GNUNET_i2s (&mq->neighbour_id));
1216 if (mq->client != NULL)
1217 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1218 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1219 neighbour->messages_tail,
1222 return; /* nobody ready */
1224 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1225 GNUNET_SCHEDULER_cancel (sched,
1226 neighbour->retry_task);
1227 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1229 &retry_transmission_task,
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1234 mq->message_buf_size,
1235 GNUNET_i2s (&mq->neighbour_id),
1240 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1241 neighbour->messages_tail,
1243 if (mq->specific_address->connected == GNUNET_NO)
1244 mq->specific_address->connect_attempts++;
1245 rl = mq->specific_address->ready_list;
1246 mq->plugin = rl->plugin;
1247 if (!mq->internal_msg)
1248 mq->specific_address->in_transmit = GNUNET_YES;
1250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1251 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1252 mq->message_buf_size,
1253 GNUNET_i2s (&neighbour->id),
1254 GNUNET_a2s (mq->specific_address->addr,
1255 mq->specific_address->addrlen),
1256 rl->plugin->short_name);
1258 rl->plugin->api->send (rl->plugin->api->cls,
1261 mq->message_buf_size,
1263 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1264 mq->specific_address->addr,
1265 mq->specific_address->addrlen,
1266 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1267 &transmit_send_continuation, mq);
1272 * Send the specified message to the specified peer.
1274 * @param client source of the transmission request (can be NULL)
1275 * @param peer_address ForeignAddressList where we should send this message
1276 * @param priority how important is the message
1277 * @param timeout how long do we have to transmit?
1278 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1279 * @param message_buf_size total size of all messages in message_buf
1280 * @param is_internal is this an internal message; these are pre-pended and
1281 * also do not count for plugins being "ready" to transmit
1282 * @param neighbour handle to the neighbour for transmission
1285 transmit_to_peer (struct TransportClient *client,
1286 struct ForeignAddressList *peer_address,
1287 unsigned int priority,
1288 struct GNUNET_TIME_Relative timeout,
1289 const char *message_buf,
1290 size_t message_buf_size,
1291 int is_internal, struct NeighbourList *neighbour)
1293 struct MessageQueue *mq;
1298 /* check for duplicate submission */
1299 mq = neighbour->messages_head;
1302 if (mq->client == client)
1304 /* client transmitted to same peer twice
1305 before getting SendOk! */
1313 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1314 mq->specific_address = peer_address;
1315 mq->client = client;
1316 memcpy (&mq[1], message_buf, message_buf_size);
1317 mq->message_buf = (const char*) &mq[1];
1318 mq->message_buf_size = message_buf_size;
1319 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1320 mq->internal_msg = is_internal;
1321 mq->priority = priority;
1322 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1324 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1325 neighbour->messages_tail,
1328 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1329 neighbour->messages_tail,
1330 neighbour->messages_tail,
1332 try_transmission_to_peer (neighbour);
1339 struct GeneratorContext
1341 struct TransportPlugin *plug_pos;
1342 struct OwnAddressList *addr_pos;
1343 struct GNUNET_TIME_Absolute expiration;
1351 address_generator (void *cls, size_t max, void *buf)
1353 struct GeneratorContext *gc = cls;
1356 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1358 gc->plug_pos = gc->plug_pos->next;
1359 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1361 if (NULL == gc->plug_pos)
1366 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1369 gc->addr_pos->addrlen, buf, max);
1370 gc->addr_pos = gc->addr_pos->next;
1376 * Construct our HELLO message from all of the addresses of
1377 * all of the transports.
1382 struct GNUNET_HELLO_Message *hello;
1383 struct TransportClient *cpos;
1384 struct NeighbourList *npos;
1385 struct GeneratorContext gc;
1387 gc.plug_pos = plugins;
1388 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1389 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1390 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1393 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1396 while (cpos != NULL)
1398 transmit_to_client (cpos,
1399 (const struct GNUNET_MessageHeader *) hello,
1404 GNUNET_free_non_null (our_hello);
1406 our_hello_version++;
1407 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1409 while (npos != NULL)
1412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1413 "Transmitting updated `%s' to neighbour `%4s'\n",
1414 "HELLO", GNUNET_i2s (&npos->id));
1416 transmit_to_peer (NULL, NULL, 0,
1417 HELLO_ADDRESS_EXPIRATION,
1418 (const char *) our_hello,
1419 GNUNET_HELLO_size(our_hello),
1427 * Task used to clean up expired addresses for a plugin.
1429 * @param cls closure
1433 expire_address_task (void *cls,
1434 const struct GNUNET_SCHEDULER_TaskContext *tc);
1438 * Update the list of addresses for this plugin,
1439 * expiring those that are past their expiration date.
1441 * @param plugin addresses of which plugin should be recomputed?
1442 * @param fresh set to GNUNET_YES if a new address was added
1443 * and we need to regenerate the HELLO even if nobody
1447 update_addresses (struct TransportPlugin *plugin, int fresh)
1449 struct GNUNET_TIME_Relative min_remaining;
1450 struct GNUNET_TIME_Relative remaining;
1451 struct GNUNET_TIME_Absolute now;
1452 struct OwnAddressList *pos;
1453 struct OwnAddressList *prev;
1454 struct OwnAddressList *next;
1457 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1458 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1459 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1460 now = GNUNET_TIME_absolute_get ();
1461 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1462 expired = GNUNET_NO;
1464 pos = plugin->addresses;
1468 if (pos->expires.value < now.value)
1470 expired = GNUNET_YES;
1472 plugin->addresses = pos->next;
1474 prev->next = pos->next;
1479 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1480 if (remaining.value < min_remaining.value)
1481 min_remaining = remaining;
1487 if (expired || fresh)
1489 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1490 plugin->address_update_task
1491 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1493 &expire_address_task, plugin);
1499 * Task used to clean up expired addresses for a plugin.
1501 * @param cls closure
1505 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1507 struct TransportPlugin *plugin = cls;
1508 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1509 update_addresses (plugin, GNUNET_NO);
1514 * Function that must be called by each plugin to notify the
1515 * transport service about the addresses under which the transport
1516 * provided by the plugin can be reached.
1518 * @param cls closure
1519 * @param name name of the transport that generated the address
1520 * @param addr one of the addresses of the host, NULL for the last address
1521 * the specific address format depends on the transport
1522 * @param addrlen length of the address
1523 * @param expires when should this address automatically expire?
1526 plugin_env_notify_address (void *cls,
1530 struct GNUNET_TIME_Relative expires)
1532 struct TransportPlugin *p = cls;
1533 struct OwnAddressList *al;
1534 struct GNUNET_TIME_Absolute abex;
1536 abex = GNUNET_TIME_relative_to_absolute (expires);
1537 GNUNET_assert (p == find_transport (name));
1542 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1544 if (al->expires.value < abex.value)
1551 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1553 al->next = p->addresses;
1556 al->addrlen = addrlen;
1557 memcpy (&al[1], addr, addrlen);
1558 update_addresses (p, GNUNET_YES);
1563 * Notify all of our clients about a peer connecting.
1566 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1567 struct GNUNET_TIME_Relative latency,
1570 struct ConnectInfoMessage cim;
1571 struct TransportClient *cpos;
1574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1575 "Notifying clients about connection from `%s'\n",
1578 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1579 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1580 cim.distance = htonl (distance);
1581 cim.latency = GNUNET_TIME_relative_hton (latency);
1582 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1584 while (cpos != NULL)
1586 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1593 * Notify all of our clients about a peer disconnecting.
1596 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1598 struct DisconnectInfoMessage dim;
1599 struct TransportClient *cpos;
1602 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1603 "Notifying clients about lost connection to `%s'\n",
1606 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1607 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1608 dim.reserved = htonl (0);
1609 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1611 while (cpos != NULL)
1613 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1620 * Find a ForeignAddressList entry for the given neighbour
1621 * that matches the given address and transport.
1623 * @param neighbour which peer we care about
1624 * @param tname name of the transport plugin
1625 * @param addr binary address
1626 * @param addrlen length of addr
1627 * @return NULL if no such entry exists
1629 static struct ForeignAddressList *
1630 find_peer_address(struct NeighbourList *neighbour,
1635 struct ReadyList *head;
1636 struct ForeignAddressList *address_head;
1638 head = neighbour->plugins;
1639 while (head != NULL)
1641 if (0 == strcmp (tname, head->plugin->short_name))
1648 address_head = head->addresses;
1649 while ( (address_head != NULL) &&
1650 ( (address_head->addrlen != addrlen) ||
1651 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1652 address_head = address_head->next;
1653 return address_head;
1658 * Get the peer address struct for the given neighbour and
1659 * address. If it doesn't yet exist, create it.
1661 * @param neighbour which peer we care about
1662 * @param tname name of the transport plugin
1663 * @param addr binary address
1664 * @param addrlen length of addr
1665 * @return NULL if we do not have a transport plugin for 'tname'
1667 static struct ForeignAddressList *
1668 add_peer_address(struct NeighbourList *neighbour,
1673 struct ReadyList *head;
1674 struct ForeignAddressList *ret;
1676 ret = find_peer_address (neighbour, tname, addr, addrlen);
1679 head = neighbour->plugins;
1680 while (head != NULL)
1682 if (0 == strcmp (tname, head->plugin->short_name))
1688 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1689 ret->addr = (const char*) &ret[1];
1690 memcpy (&ret[1], addr, addrlen);
1691 ret->addrlen = addrlen;
1692 ret->expires = GNUNET_TIME_relative_to_absolute
1693 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1694 ret->latency = GNUNET_TIME_relative_get_forever();
1696 ret->timeout = GNUNET_TIME_relative_to_absolute
1697 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1698 ret->ready_list = head;
1699 ret->next = head->addresses;
1700 head->addresses = ret;
1706 * Closure for 'add_validated_address'.
1708 struct AddValidatedAddressContext
1711 * Entry that has been validated.
1713 const struct ValidationEntry *ve;
1716 * Flag set after we have added the address so
1717 * that we terminate the iteration next time.
1724 * Callback function used to fill a buffer of max bytes with a list of
1725 * addresses in the format used by HELLOs. Should use
1726 * "GNUNET_HELLO_add_address" as a helper function.
1728 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1729 * @param max maximum number of bytes that can be written to buf
1730 * @param buf where to write the address information
1731 * @return number of bytes written, 0 to signal the
1732 * end of the iteration.
1735 add_validated_address (void *cls,
1736 size_t max, void *buf)
1738 struct AddValidatedAddressContext *avac = cls;
1739 const struct ValidationEntry *ve = avac->ve;
1741 if (GNUNET_YES == avac->done)
1743 avac->done = GNUNET_YES;
1744 return GNUNET_HELLO_add_address (ve->transport_name,
1745 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1754 * Iterator over hash map entries. Checks if the given
1755 * validation entry is for the same challenge as what
1756 * is given in the PONG.
1758 * @param cls the 'struct TransportPongMessage*'
1759 * @param key peer identity
1760 * @param value value in the hash map ('struct ValidationEntry')
1761 * @return GNUNET_YES if we should continue to
1762 * iterate (mismatch), GNUNET_NO if not (entry matched)
1765 check_pending_validation (void *cls,
1766 const GNUNET_HashCode * key,
1769 const struct TransportPongMessage *pong = cls;
1770 struct ValidationEntry *ve = value;
1771 struct AddValidatedAddressContext avac;
1772 unsigned int challenge = ntohl(pong->challenge);
1773 struct GNUNET_HELLO_Message *hello;
1774 struct GNUNET_PeerIdentity target;
1775 struct NeighbourList *n;
1776 struct ForeignAddressList *fal;
1778 if (ve->challenge != challenge)
1782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1783 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1785 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1787 ve->transport_name);
1789 /* create the updated HELLO */
1790 GNUNET_CRYPTO_hash (&ve->publicKey,
1791 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1792 &target.hashPubKey);
1793 avac.done = GNUNET_NO;
1795 hello = GNUNET_HELLO_create (&ve->publicKey,
1796 &add_validated_address,
1798 GNUNET_PEERINFO_add_peer (cfg, sched,
1801 GNUNET_free (hello);
1802 n = find_neighbour (&target);
1805 fal = add_peer_address (n, ve->transport_name,
1808 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1809 fal->validated = GNUNET_YES;
1810 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1811 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1812 n->latency = fal->latency;
1814 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1815 n->distance = fal->distance;
1816 if (GNUNET_NO == n->received_pong)
1818 notify_clients_connect (&target, n->latency, n->distance);
1819 n->received_pong = GNUNET_YES;
1821 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1823 GNUNET_SCHEDULER_cancel (sched,
1825 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1826 try_transmission_to_peer (n);
1830 /* clean up validation entry */
1831 GNUNET_assert (GNUNET_YES ==
1832 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1835 GNUNET_SCHEDULER_cancel (sched,
1837 GNUNET_free (ve->transport_name);
1844 * Function that will be called if we receive a validation
1845 * of an address challenge that we transmitted to another
1846 * peer. Note that the validation should only be considered
1847 * acceptable if the challenge matches AND if the sender
1848 * address is at least a plausible address for this peer
1849 * (otherwise we may be seeing a MiM attack).
1851 * @param cls closure
1852 * @param message the pong message
1853 * @param peer who responded to our challenge
1854 * @param sender_address string describing our sender address (as observed
1855 * by the other peer in binary format)
1856 * @param sender_address_len number of bytes in 'sender_address'
1859 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1860 const struct GNUNET_PeerIdentity *peer,
1861 const char *sender_address,
1862 size_t sender_address_len)
1864 #if DEBUG_TRANSPORT > 1
1865 /* we get tons of these that just get discarded, only log
1866 if we are quite verbose */
1867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1868 "Receiving `%s' message from `%4s'.\n", "PONG",
1871 if (GNUNET_SYSERR !=
1872 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1874 &check_pending_validation,
1877 /* This is *expected* to happen a lot since we send
1878 PONGs to *all* known addresses of the sender of
1879 the PING, so most likely we get multiple PONGs
1880 per PING, and all but the first PONG will end up
1881 here. So really we should not print anything here
1882 unless we want to be very, very verbose... */
1883 #if DEBUG_TRANSPORT > 2
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1894 /* FIXME: add given address to potential pool of our addresses
1896 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1897 _("Another peer saw us using the address `%s' via `%s'.\n"),
1898 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1899 ntohs(pong->addrlen)),
1900 va->transport_name);
1906 neighbour_timeout_task (void *cls,
1907 const struct GNUNET_SCHEDULER_TaskContext *tc)
1909 struct NeighbourList *n = cls;
1912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1913 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1915 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1916 disconnect_neighbour (n, GNUNET_NO);
1921 * Create a fresh entry in our neighbour list for the given peer.
1922 * Will try to transmit our current HELLO to the new neighbour. Also
1923 * notifies our clients about the new "connection".
1925 * @param peer the peer for which we create the entry
1926 * @return the new neighbour list entry
1928 static struct NeighbourList *
1929 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1931 struct NeighbourList *n;
1932 struct TransportPlugin *tp;
1933 struct ReadyList *rl;
1935 GNUNET_assert (our_hello != NULL);
1936 n = GNUNET_malloc (sizeof (struct NeighbourList));
1937 n->next = neighbours;
1940 n->last_quota_update = GNUNET_TIME_absolute_get ();
1942 GNUNET_TIME_relative_to_absolute
1943 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1944 n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1948 if (tp->api->send != NULL)
1950 rl = GNUNET_malloc (sizeof (struct ReadyList));
1951 rl->next = n->plugins;
1954 rl->addresses = NULL;
1958 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1960 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1961 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1962 &neighbour_timeout_task, n);
1963 transmit_to_peer (NULL, NULL, 0,
1964 HELLO_ADDRESS_EXPIRATION,
1965 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1972 * Closure for 'check_address_exists'.
1974 struct CheckAddressExistsClosure
1977 * Address to check for.
1982 * Name of the transport.
1992 * Set to GNUNET_YES if the address exists.
1999 * Iterator over hash map entries. Checks if the given
2000 * validation entry is for the same address as what is given
2003 * @param cls the 'struct CheckAddressExistsClosure*'
2004 * @param key current key code (ignored)
2005 * @param value value in the hash map ('struct ValidationEntry')
2006 * @return GNUNET_YES if we should continue to
2007 * iterate (mismatch), GNUNET_NO if not (entry matched)
2010 check_address_exists (void *cls,
2011 const GNUNET_HashCode * key,
2014 struct CheckAddressExistsClosure *caec = cls;
2015 struct ValidationEntry *ve = value;
2016 if ( (0 == strcmp (caec->tname,
2017 ve->transport_name)) &&
2018 (caec->addrlen == ve->addrlen) &&
2019 (0 == memcmp (caec->addr,
2023 caec->exists = GNUNET_YES;
2031 * HELLO validation cleanup task (validation failed).
2033 * @param cls the 'struct ValidationEntry' that failed
2034 * @param tc scheduler context (unused)
2037 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2039 struct ValidationEntry *va = cls;
2040 struct GNUNET_PeerIdentity pid;
2042 GNUNET_CRYPTO_hash (&va->publicKey,
2044 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2046 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2049 GNUNET_free (va->transport_name);
2055 * Check if the given address is already being validated; if not,
2056 * append the given address to the list of entries that are being be
2057 * validated and initiate validation.
2059 * @param cls closure ('struct CheckHelloValidatedContext *')
2060 * @param tname name of the transport
2061 * @param expiration expiration time
2062 * @param addr the address
2063 * @param addrlen length of the address
2064 * @return GNUNET_OK (always)
2067 run_validation (void *cls,
2069 struct GNUNET_TIME_Absolute expiration,
2070 const void *addr, size_t addrlen)
2072 struct CheckHelloValidatedContext *chvc = cls;
2073 struct GNUNET_PeerIdentity id;
2074 struct TransportPlugin *tp;
2075 struct ValidationEntry *va;
2076 struct NeighbourList *neighbour;
2077 struct ForeignAddressList *peer_address;
2078 struct TransportPingMessage ping;
2079 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2080 struct CheckAddressExistsClosure caec;
2082 uint16_t hello_size;
2085 tp = find_transport (tname);
2088 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2089 GNUNET_ERROR_TYPE_BULK,
2091 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2095 GNUNET_HELLO_get_key (chvc->hello, &pk);
2096 GNUNET_CRYPTO_hash (&pk,
2098 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2101 caec.addrlen = addrlen;
2103 caec.exists = GNUNET_NO;
2104 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2105 &check_address_exists,
2107 if (caec.exists == GNUNET_YES)
2109 /* During validation attempts we will likely trigger the other
2110 peer trying to validate our address which in turn will cause
2111 it to send us its HELLO, so we expect to hit this case rather
2112 frequently. Only print something if we are very verbose. */
2113 #if DEBUG_TRANSPORT > 1
2114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2115 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2116 GNUNET_a2s (addr, addrlen),
2122 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2123 va->transport_name = GNUNET_strdup (tname);
2124 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2126 va->send_time = GNUNET_TIME_absolute_get();
2127 va->addr = (const void*) &va[1];
2128 memcpy (&va[1], addr, addrlen);
2129 va->addrlen = addrlen;
2130 GNUNET_HELLO_get_key (chvc->hello,
2132 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2133 HELLO_VERIFICATION_TIMEOUT,
2134 &timeout_hello_validation,
2136 GNUNET_CONTAINER_multihashmap_put (validation_map,
2139 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2140 neighbour = find_neighbour(&id);
2141 if (neighbour == NULL)
2142 neighbour = setup_new_neighbour(&id);
2143 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2144 GNUNET_assert(peer_address != NULL);
2145 hello_size = GNUNET_HELLO_size(our_hello);
2146 tsize = sizeof(struct TransportPingMessage) + hello_size;
2147 message_buf = GNUNET_malloc(tsize);
2148 ping.challenge = htonl(va->challenge);
2149 ping.header.size = htons(sizeof(struct TransportPingMessage));
2150 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2151 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2152 memcpy(message_buf, our_hello, hello_size);
2153 memcpy(&message_buf[hello_size],
2155 sizeof(struct TransportPingMessage));
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2159 GNUNET_a2s (addr, addrlen),
2162 "HELLO", hello_size,
2163 "PING", sizeof (struct TransportPingMessage));
2165 transmit_to_peer (NULL, peer_address,
2166 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2167 HELLO_VERIFICATION_TIMEOUT,
2169 GNUNET_YES, neighbour);
2170 GNUNET_free(message_buf);
2176 * Add the given address to the list of foreign addresses
2177 * available for the given peer (check for duplicates).
2179 * @param cls the respective 'struct NeighbourList' to update
2180 * @param tname name of the transport
2181 * @param expiration expiration time
2182 * @param addr the address
2183 * @param addrlen length of the address
2184 * @return GNUNET_OK (always)
2187 add_to_foreign_address_list (void *cls,
2189 struct GNUNET_TIME_Absolute expiration,
2190 const void *addr, size_t addrlen)
2192 struct NeighbourList *n = cls;
2193 struct ForeignAddressList *fal;
2195 fal = find_peer_address (n, tname, addr, addrlen);
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2201 GNUNET_a2s (addr, addrlen),
2203 GNUNET_i2s (&n->id),
2206 fal = add_peer_address (n, tname, addr, addrlen);
2210 fal->expires = GNUNET_TIME_absolute_max (expiration,
2212 fal->validated = GNUNET_YES;
2218 * Check if addresses in validated hello "h" overlap with
2219 * those in "chvc->hello" and validate the rest.
2221 * @param cls closure
2222 * @param peer id of the peer, NULL for last call
2223 * @param h hello message for the peer (can be NULL)
2224 * @param trust amount of trust we have in the peer (not used)
2227 check_hello_validated (void *cls,
2228 const struct GNUNET_PeerIdentity *peer,
2229 const struct GNUNET_HELLO_Message *h,
2232 struct CheckHelloValidatedContext *chvc = cls;
2233 struct GNUNET_HELLO_Message *plain_hello;
2234 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2235 struct GNUNET_PeerIdentity target;
2236 struct NeighbourList *n;
2241 GNUNET_CONTAINER_DLL_remove (chvc_head,
2244 if (GNUNET_NO == chvc->hello_known)
2246 /* notify PEERINFO about the peer now, so that we at least
2247 have the public key if some other component needs it */
2248 GNUNET_HELLO_get_key (chvc->hello, &pk);
2249 GNUNET_CRYPTO_hash (&pk,
2250 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2251 &target.hashPubKey);
2252 plain_hello = GNUNET_HELLO_create (&pk,
2255 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2256 GNUNET_free (plain_hello);
2258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2261 GNUNET_i2s (&target));
2263 GNUNET_HELLO_iterate_addresses (chvc->hello,
2273 chvc->hello_known = GNUNET_YES;
2274 n = find_neighbour (peer);
2277 GNUNET_HELLO_iterate_addresses (h,
2279 &add_to_foreign_address_list,
2281 try_transmission_to_peer (n);
2283 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2285 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2291 * Process HELLO-message.
2293 * @param plugin transport involved, may be NULL
2294 * @param message the actual message
2295 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2298 process_hello (struct TransportPlugin *plugin,
2299 const struct GNUNET_MessageHeader *message)
2302 struct GNUNET_PeerIdentity target;
2303 const struct GNUNET_HELLO_Message *hello;
2304 struct CheckHelloValidatedContext *chvc;
2305 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2307 hsize = ntohs (message->size);
2308 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2309 (hsize < sizeof (struct GNUNET_MessageHeader)))
2312 return GNUNET_SYSERR;
2314 /* first, check if load is too high */
2315 if (GNUNET_SCHEDULER_get_load (sched,
2316 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2318 /* TODO: call to stats? */
2321 hello = (const struct GNUNET_HELLO_Message *) message;
2322 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2324 GNUNET_break_op (0);
2325 return GNUNET_SYSERR;
2327 GNUNET_CRYPTO_hash (&publicKey,
2328 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2329 &target.hashPubKey);
2331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2332 "Processing `%s' message for `%4s' of size %u\n",
2334 GNUNET_i2s (&target),
2335 GNUNET_HELLO_size(hello));
2338 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2339 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2340 memcpy (&chvc[1], hello, hsize);
2341 GNUNET_CONTAINER_DLL_insert (chvc_head,
2344 /* finally, check if HELLO was previously validated
2345 (continuation will then schedule actual validation) */
2346 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2350 HELLO_VERIFICATION_TIMEOUT,
2351 &check_hello_validated, chvc);
2357 * The peer specified by the given neighbour has timed-out or a plugin
2358 * has disconnected. We may either need to do nothing (other plugins
2359 * still up), or trigger a full disconnect and clean up. This
2360 * function updates our state and does the necessary notifications.
2361 * Also notifies our clients that the neighbour is now officially
2364 * @param n the neighbour list entry for the peer
2365 * @param check should we just check if all plugins
2366 * disconnected or must we ask all plugins to
2370 disconnect_neighbour (struct NeighbourList *n, int check)
2372 struct ReadyList *rpos;
2373 struct NeighbourList *npos;
2374 struct NeighbourList *nprev;
2375 struct MessageQueue *mq;
2376 struct ForeignAddressList *peer_addresses;
2377 struct ForeignAddressList *peer_pos;
2379 if (GNUNET_YES == check)
2382 while (NULL != rpos)
2384 peer_addresses = rpos->addresses;
2385 while (peer_addresses != NULL)
2387 if (GNUNET_YES == peer_addresses->connected)
2388 return; /* still connected */
2389 peer_addresses = peer_addresses->next;
2395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2396 "Disconnecting from `%4s'\n",
2397 GNUNET_i2s (&n->id));
2399 /* remove n from neighbours list */
2402 while ((npos != NULL) && (npos != n))
2407 GNUNET_assert (npos != NULL);
2409 neighbours = n->next;
2411 nprev->next = n->next;
2413 /* notify all clients about disconnect */
2414 if (GNUNET_YES == n->received_pong)
2415 notify_clients_disconnect (&n->id);
2417 /* clean up all plugins, cancel connections and pending transmissions */
2418 while (NULL != (rpos = n->plugins))
2420 n->plugins = rpos->next;
2421 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2423 while (rpos->addresses != NULL)
2425 peer_pos = rpos->addresses;
2426 rpos->addresses = peer_pos->next;
2427 GNUNET_free(peer_pos);
2432 /* free all messages on the queue */
2433 while (NULL != (mq = n->messages_head))
2435 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2438 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2440 sizeof(struct GNUNET_PeerIdentity)));
2443 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2445 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2446 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2448 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2450 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2451 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2453 /* finally, free n itself */
2459 * We have received a PING message from someone. Need to send a PONG message
2460 * in response to the peer by any means necessary.
2462 * FIXME: With something like TCP where a connection exists, we may
2463 * want to send it that way. But the current API does not seem to
2464 * allow us to do so (can't tell this to the transport!)
2467 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2468 const struct GNUNET_PeerIdentity *peer,
2469 const char *sender_address,
2470 size_t sender_address_len)
2472 struct TransportPlugin *plugin = cls;
2473 struct TransportPingMessage *ping;
2474 struct TransportPongMessage *pong;
2476 struct NeighbourList *n;
2477 struct ReadyList *rl;
2478 struct ForeignAddressList *fal;
2480 msize = ntohs (message->size);
2481 if (msize < sizeof (struct TransportPingMessage))
2483 GNUNET_break_op (0);
2484 return GNUNET_SYSERR;
2486 ping = (struct TransportPingMessage *) message;
2487 if (0 != memcmp (&ping->target,
2488 plugin->env.my_identity,
2489 sizeof (struct GNUNET_PeerIdentity)))
2491 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2492 _("Received `%s' message not destined for me!\n"),
2494 return GNUNET_SYSERR;
2497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2498 "Processing `%s' from `%s'\n",
2500 GNUNET_a2s ((const struct sockaddr *)sender_address,
2501 sender_address_len));
2503 msize -= sizeof (struct TransportPingMessage);
2504 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2505 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2506 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2507 pong->purpose.size =
2508 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2510 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2511 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2512 pong->challenge = ping->challenge;
2513 pong->addrlen = htons(sender_address_len);
2514 memcpy(&pong->signer,
2516 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2517 memcpy (&pong[1], sender_address, sender_address_len);
2518 GNUNET_assert (GNUNET_OK ==
2519 GNUNET_CRYPTO_rsa_sign (my_private_key,
2520 &pong->purpose, &pong->signature));
2522 n = find_neighbour(peer);
2524 n = setup_new_neighbour(peer);
2525 /* broadcast 'PONG' to all available addresses */
2529 fal = rl->addresses;
2532 transmit_to_peer(NULL, fal,
2533 TRANSPORT_PONG_PRIORITY,
2534 HELLO_VERIFICATION_TIMEOUT,
2536 ntohs(pong->header.size),
2549 * Calculate how long we should delay reading from the TCP socket to
2550 * ensure that we stay within our bandwidth limits (push back).
2552 * @param n for which neighbour should this be calculated
2553 * @return how long to delay receiving more data
2555 static struct GNUNET_TIME_Relative
2556 calculate_throttle_delay (struct NeighbourList *n)
2558 struct GNUNET_TIME_Relative ret;
2559 struct GNUNET_TIME_Absolute now;
2564 now = GNUNET_TIME_absolute_get ();
2565 del = now.value - n->last_quota_update.value;
2566 if (del > MAX_BANDWIDTH_CARRY)
2568 update_quota (n, GNUNET_YES);
2569 del = now.value - n->last_quota_update.value;
2570 GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
2572 if (n->quota_in == 0)
2573 n->quota_in = 1; /* avoid divison by zero */
2574 avail = del * n->quota_in;
2575 if (avail > n->last_received)
2576 return GNUNET_TIME_UNIT_ZERO; /* can receive right now */
2577 excess = n->last_received - avail;
2578 ret.value = excess / n->quota_in;
2580 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2581 "Throttling read (%llu bytes excess at %llu b/ms), waiting %llums before reading more.\n",
2582 (unsigned long long) excess,
2583 (unsigned long long) n->quota_in,
2584 (unsigned long long) ret.value);
2590 * Function called by the plugin for each received message.
2591 * Update data volumes, possibly notify plugins about
2592 * reducing the rate at which they read from the socket
2593 * and generally forward to our receive callback.
2595 * @param cls the "struct TransportPlugin *" we gave to the plugin
2596 * @param peer (claimed) identity of the other peer
2597 * @param message the message, NULL if we only care about
2598 * learning about the delay until we should receive again
2599 * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2600 * @param sender_address binary address of the sender (if observed)
2601 * @param sender_address_len number of bytes in sender_address
2602 * @return how long the plugin should wait until receiving more data
2603 * (plugins that do not support this, can ignore the return value)
2605 static struct GNUNET_TIME_Relative
2606 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2607 const struct GNUNET_MessageHeader *message,
2608 unsigned int distance, const char *sender_address,
2609 size_t sender_address_len)
2611 struct ReadyList *service_context;
2612 struct TransportPlugin *plugin = cls;
2613 struct TransportClient *cpos;
2614 struct InboundMessage *im;
2615 struct ForeignAddressList *peer_address;
2617 struct NeighbourList *n;
2619 n = find_neighbour (peer);
2621 n = setup_new_neighbour (peer);
2622 update_quota (n, GNUNET_NO);
2623 service_context = n->plugins;
2624 while ((service_context != NULL) && (plugin != service_context->plugin))
2625 service_context = service_context->next;
2626 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2627 if (message != NULL)
2629 peer_address = add_peer_address(n,
2632 sender_address_len);
2633 if (peer_address != NULL)
2635 peer_address->distance = distance;
2636 if (peer_address->connected == GNUNET_NO)
2638 peer_address->connected = GNUNET_YES;
2639 peer_address->connect_attempts++;
2641 peer_address->timeout
2643 GNUNET_TIME_relative_to_absolute
2644 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2646 /* update traffic received amount ... */
2647 msize = ntohs (message->size);
2648 n->distance = distance;
2650 GNUNET_TIME_relative_to_absolute
2651 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2652 GNUNET_SCHEDULER_cancel (sched,
2655 GNUNET_SCHEDULER_add_delayed (sched,
2656 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2657 &neighbour_timeout_task, n);
2658 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2660 /* dropping message due to frequent inbound volume violations! */
2661 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2662 GNUNET_ERROR_TYPE_BULK,
2664 ("Dropping incoming message due to repeated bandwidth quota violations (total of %u).\n"),
2665 n->quota_violation_count);
2666 return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2668 switch (ntohs (message->type))
2670 case GNUNET_MESSAGE_TYPE_HELLO:
2671 process_hello (plugin, message);
2673 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2674 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2676 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2677 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2682 "Received message of type %u from `%4s', sending to all clients.\n",
2683 ntohs (message->type), GNUNET_i2s (peer));
2685 /* transmit message to all clients */
2686 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2687 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2688 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2689 im->latency = GNUNET_TIME_relative_hton (n->latency);
2691 memcpy (&im[1], message, msize);
2693 while (cpos != NULL)
2695 transmit_to_client (cpos, &im->header, GNUNET_YES);
2701 return calculate_throttle_delay (n);
2706 * Handle START-message. This is the first message sent to us
2707 * by any client which causes us to add it to our list.
2709 * @param cls closure (always NULL)
2710 * @param client identification of the client
2711 * @param message the actual message
2714 handle_start (void *cls,
2715 struct GNUNET_SERVER_Client *client,
2716 const struct GNUNET_MessageHeader *message)
2718 struct TransportClient *c;
2719 struct ConnectInfoMessage cim;
2720 struct NeighbourList *n;
2723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2724 "Received `%s' request from client\n", "START");
2729 if (c->client == client)
2731 /* client already on our list! */
2733 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2738 c = GNUNET_malloc (sizeof (struct TransportClient));
2742 if (our_hello != NULL)
2745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2746 "Sending our own `%s' to new client\n", "HELLO");
2748 transmit_to_client (c,
2749 (const struct GNUNET_MessageHeader *) our_hello,
2751 /* tell new client about all existing connections */
2752 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2753 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2757 if (GNUNET_YES == n->received_pong)
2760 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2761 cim.distance = htonl (n->distance);
2762 transmit_to_client (c, &cim.header, GNUNET_NO);
2767 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2772 * Handle HELLO-message.
2774 * @param cls closure (always NULL)
2775 * @param client identification of the client
2776 * @param message the actual message
2779 handle_hello (void *cls,
2780 struct GNUNET_SERVER_Client *client,
2781 const struct GNUNET_MessageHeader *message)
2785 ret = process_hello (NULL, message);
2786 GNUNET_SERVER_receive_done (client, ret);
2791 * Handle SEND-message.
2793 * @param cls closure (always NULL)
2794 * @param client identification of the client
2795 * @param message the actual message
2798 handle_send (void *cls,
2799 struct GNUNET_SERVER_Client *client,
2800 const struct GNUNET_MessageHeader *message)
2802 struct TransportClient *tc;
2803 struct NeighbourList *n;
2804 const struct OutboundMessage *obm;
2805 const struct GNUNET_MessageHeader *obmm;
2809 size = ntohs (message->size);
2811 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2814 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2817 obm = (const struct OutboundMessage *) message;
2819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2820 "Received `%s' request from client with target `%4s'\n",
2821 "SEND", GNUNET_i2s (&obm->peer));
2823 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2824 msize = ntohs (obmm->size);
2825 if (size != msize + sizeof (struct OutboundMessage))
2828 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2831 n = find_neighbour (&obm->peer);
2833 n = setup_new_neighbour (&obm->peer);
2835 while ((tc != NULL) && (tc->client != client))
2839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2840 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2842 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2844 transmit_to_peer (tc, NULL, ntohl (obm->priority),
2845 GNUNET_TIME_relative_ntoh (obm->timeout),
2847 ntohs (obmm->size), GNUNET_NO, n);
2848 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2853 * Handle SET_QUOTA-message.
2855 * @param cls closure (always NULL)
2856 * @param client identification of the client
2857 * @param message the actual message
2860 handle_set_quota (void *cls,
2861 struct GNUNET_SERVER_Client *client,
2862 const struct GNUNET_MessageHeader *message)
2864 const struct QuotaSetMessage *qsm =
2865 (const struct QuotaSetMessage *) message;
2866 struct NeighbourList *n;
2869 n = find_neighbour (&qsm->peer);
2872 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2875 qin = ntohl (qsm->quota_in);
2877 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2878 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
2879 "SET_QUOTA", qin, n->quota_in, GNUNET_i2s (&qsm->peer));
2881 update_quota (n, GNUNET_YES);
2882 if (n->quota_in < qin)
2883 n->last_quota_update = GNUNET_TIME_absolute_get ();
2885 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2890 transmit_address_to_client (void *cls, const char *address)
2892 struct GNUNET_SERVER_TransmitContext *tc = cls;
2895 if (NULL == address)
2898 slen = strlen (address) + 1;
2899 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
2900 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2901 if (NULL == address)
2902 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
2907 * Handle AddressLookup-message.
2909 * @param cls closure (always NULL)
2910 * @param client identification of the client
2911 * @param message the actual message
2914 handle_address_lookup (void *cls,
2915 struct GNUNET_SERVER_Client *client,
2916 const struct GNUNET_MessageHeader *message)
2918 const struct AddressLookupMessage *alum;
2919 struct TransportPlugin *lsPlugin;
2920 const char *nameTransport;
2921 const char *address;
2923 struct GNUNET_SERVER_TransmitContext *tc;
2925 size = ntohs (message->size);
2926 if (size < sizeof (struct AddressLookupMessage))
2928 GNUNET_break_op (0);
2929 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2932 alum = (const struct AddressLookupMessage *) message;
2933 uint32_t addressLen = ntohl (alum->addrlen);
2934 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
2936 GNUNET_break_op (0);
2937 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2940 address = (const char *) &alum[1];
2941 nameTransport = (const char *) &address[addressLen];
2943 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
2945 GNUNET_break_op (0);
2946 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2949 struct GNUNET_TIME_Absolute timeout =
2950 GNUNET_TIME_absolute_ntoh (alum->timeout);
2951 struct GNUNET_TIME_Relative rtimeout =
2952 GNUNET_TIME_absolute_get_remaining (timeout);
2953 lsPlugin = find_transport (nameTransport);
2954 if (NULL == lsPlugin)
2956 tc = GNUNET_SERVER_transmit_context_create (client);
2957 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
2958 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2959 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2962 tc = GNUNET_SERVER_transmit_context_create (client);
2963 lsPlugin->api->address_pretty_printer (cls, nameTransport,
2964 address, addressLen, GNUNET_YES,
2966 &transmit_address_to_client, tc);
2970 * List of handlers for the messages understood by this
2973 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2974 {&handle_start, NULL,
2975 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2976 {&handle_hello, NULL,
2977 GNUNET_MESSAGE_TYPE_HELLO, 0},
2978 {&handle_send, NULL,
2979 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2980 {&handle_set_quota, NULL,
2981 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2982 {&handle_address_lookup, NULL,
2983 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2990 * Setup the environment for this plugin.
2993 create_environment (struct TransportPlugin *plug)
2995 plug->env.cfg = cfg;
2996 plug->env.sched = sched;
2997 plug->env.my_identity = &my_identity;
2998 plug->env.cls = plug;
2999 plug->env.receive = &plugin_env_receive;
3000 plug->env.notify_address = &plugin_env_notify_address;
3001 plug->env.max_connections = max_connect_per_transport;
3006 * Start the specified transport (load the plugin).
3009 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3011 struct TransportPlugin *plug;
3014 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3015 _("Loading `%s' transport plugin\n"), name);
3016 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3017 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3018 create_environment (plug);
3019 plug->short_name = GNUNET_strdup (name);
3020 plug->lib_name = libname;
3021 plug->next = plugins;
3023 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3024 if (plug->api == NULL)
3026 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3027 _("Failed to load transport plugin for `%s'\n"), name);
3028 GNUNET_free (plug->short_name);
3029 plugins = plug->next;
3030 GNUNET_free (libname);
3037 * Called whenever a client is disconnected. Frees our
3038 * resources associated with that client.
3040 * @param cls closure
3041 * @param client identification of the client
3044 client_disconnect_notification (void *cls,
3045 struct GNUNET_SERVER_Client *client)
3047 struct TransportClient *pos;
3048 struct TransportClient *prev;
3049 struct ClientMessageQueueEntry *mqe;
3054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3055 "Client disconnected, cleaning up.\n");
3059 while ((pos != NULL) && (pos->client != client))
3066 while (NULL != (mqe = pos->message_queue_head))
3068 GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3069 pos->message_queue_tail,
3071 pos->message_count--;
3075 clients = pos->next;
3077 prev->next = pos->next;
3078 if (GNUNET_YES == pos->tcs_pending)
3083 if (pos->th != NULL)
3085 GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3088 GNUNET_break (0 == pos->message_count);
3094 * Iterator to free entries in the validation_map.
3096 * @param cls closure (unused)
3097 * @param key current key code
3098 * @param value value in the hash map (validation to abort)
3099 * @return GNUNET_YES (always)
3102 abort_validation (void *cls,
3103 const GNUNET_HashCode * key,
3106 struct ValidationEntry *va = value;
3108 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3109 GNUNET_free (va->transport_name);
3116 * Function called when the service shuts down. Unloads our plugins
3117 * and cancels pending validations.
3119 * @param cls closure, unused
3120 * @param tc task context (unused)
3123 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3125 struct TransportPlugin *plug;
3126 struct OwnAddressList *al;
3127 struct CheckHelloValidatedContext *chvc;
3129 while (neighbours != NULL)
3130 disconnect_neighbour (neighbours, GNUNET_NO);
3132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3133 "Transport service is unloading plugins...\n");
3135 while (NULL != (plug = plugins))
3137 plugins = plug->next;
3138 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3139 GNUNET_free (plug->lib_name);
3140 GNUNET_free (plug->short_name);
3141 while (NULL != (al = plug->addresses))
3143 plug->addresses = al->next;
3148 if (my_private_key != NULL)
3149 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3150 GNUNET_free_non_null (our_hello);
3152 /* free 'chvc' data structure */
3153 while (NULL != (chvc = chvc_head))
3155 chvc_head = chvc->next;
3156 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3161 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3164 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3169 * Initiate transport service.
3171 * @param cls closure
3172 * @param s scheduler to use
3173 * @param serv the initialized server
3174 * @param c configuration to use
3178 struct GNUNET_SCHEDULER_Handle *s,
3179 struct GNUNET_SERVER_Handle *serv,
3180 const struct GNUNET_CONFIGURATION_Handle *c)
3185 unsigned long long tneigh;
3190 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3191 /* parse configuration */
3193 GNUNET_CONFIGURATION_get_value_number (c,
3198 GNUNET_CONFIGURATION_get_value_filename (c,
3200 "HOSTKEY", &keyfile)))
3202 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3204 ("Transport service is lacking key configuration settings. Exiting.\n"));
3205 GNUNET_SCHEDULER_shutdown (s);
3208 max_connect_per_transport = (uint32_t) tneigh;
3209 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3210 GNUNET_free (keyfile);
3211 if (my_private_key == NULL)
3213 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3215 ("Transport service could not access hostkey. Exiting.\n"));
3216 GNUNET_SCHEDULER_shutdown (s);
3219 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3220 GNUNET_CRYPTO_hash (&my_public_key,
3221 sizeof (my_public_key), &my_identity.hashPubKey);
3222 /* setup notification */
3224 GNUNET_SERVER_disconnect_notify (server,
3225 &client_disconnect_notification, NULL);
3226 /* load plugins... */
3229 GNUNET_CONFIGURATION_get_value_string (c,
3230 "TRANSPORT", "PLUGINS", &plugs))
3232 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3233 _("Starting transport plugins `%s'\n"), plugs);
3234 pos = strtok (plugs, " ");
3237 start_transport (server, pos);
3239 pos = strtok (NULL, " ");
3241 GNUNET_free (plugs);
3243 GNUNET_SCHEDULER_add_delayed (sched,
3244 GNUNET_TIME_UNIT_FOREVER_REL,
3245 &shutdown_task, NULL);
3250 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3252 /* process client requests */
3253 GNUNET_SERVER_add_handlers (server, handlers);
3258 * The main function for the transport service.
3260 * @param argc number of arguments from the command line
3261 * @param argv command line arguments
3262 * @return 0 ok, 1 on error
3265 main (int argc, char *const *argv)
3267 return (GNUNET_OK ==
3268 GNUNET_SERVICE_run (argc,
3271 GNUNET_SERVICE_OPTION_NONE,
3272 &run, NULL)) ? 0 : 1;
3275 /* end of gnunet-service-transport.c */