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
577 * Linked list of messages to be transmitted to
578 * the client. Each entry is followed by the
581 struct ClientMessageQueueEntry
584 * This is a linked list.
586 struct ClientMessageQueueEntry *next;
591 * Client connected to the transport service.
593 struct TransportClient
597 * This is a linked list.
599 struct TransportClient *next;
602 * Handle to the client.
604 struct GNUNET_SERVER_Client *client;
607 * Linked list of messages yet to be transmitted to
610 struct ClientMessageQueueEntry *message_queue_head;
613 * Tail of linked list of messages yet to be transmitted to the
616 struct ClientMessageQueueEntry *message_queue_tail;
619 * Is a call to "transmit_send_continuation" pending? If so, we
620 * must not free this struct (even if the corresponding client
621 * disconnects) and instead only remove it from the linked list and
622 * set the "client" field to NULL.
627 * Length of the list of messages pending for this client.
629 unsigned int message_count;
635 * Entry in map of all HELLOs awaiting validation.
637 struct ValidationEntry
641 * The address, actually a pointer to the end
642 * of this struct. Do not free!
647 * Name of the transport.
649 char *transport_name;
652 * The public key of the peer.
654 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
657 * ID of task that will clean up this entry if we don't succeed
658 * with the validation first.
660 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
663 * At what time did we send this validation?
665 struct GNUNET_TIME_Absolute send_time;
673 * Challenge number we used.
681 * Context of currently active requests to peerinfo
682 * for validation of HELLOs.
684 struct CheckHelloValidatedContext
688 * This is a doubly-linked list.
690 struct CheckHelloValidatedContext *next;
693 * This is a doubly-linked list.
695 struct CheckHelloValidatedContext *prev;
698 * Hello that we are validating.
700 const struct GNUNET_HELLO_Message *hello;
703 * Context for peerinfo iteration.
704 * NULL after we are done processing peerinfo's information.
706 struct GNUNET_PEERINFO_IteratorContext *piter;
709 * Was a HELLO known for this peer to peerinfo?
719 static struct GNUNET_HELLO_Message *our_hello;
722 * "version" of "our_hello". Used to see if a given neighbour has
723 * already been sent the latest version of our HELLO message.
725 static unsigned int our_hello_version;
730 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
735 static struct GNUNET_PeerIdentity my_identity;
740 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
745 struct GNUNET_SCHEDULER_Handle *sched;
750 const struct GNUNET_CONFIGURATION_Handle *cfg;
753 * Linked list of all clients to this service.
755 static struct TransportClient *clients;
758 * All loaded plugins.
760 static struct TransportPlugin *plugins;
765 static struct GNUNET_SERVER_Handle *server;
768 * All known neighbours and their HELLOs.
770 static struct NeighbourList *neighbours;
773 * Number of neighbours we'd like to have.
775 static uint32_t max_connect_per_transport;
778 * Head of linked list.
780 static struct CheckHelloValidatedContext *chvc_head;
783 * Tail of linked list.
785 static struct CheckHelloValidatedContext *chvc_tail;
789 * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
790 * of the given peer that we are currently validating).
792 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
796 * The peer specified by the given neighbour has timed-out or a plugin
797 * has disconnected. We may either need to do nothing (other plugins
798 * still up), or trigger a full disconnect and clean up. This
799 * function updates our state and do the necessary notifications.
800 * Also notifies our clients that the neighbour is now officially
803 * @param n the neighbour list entry for the peer
804 * @param check should we just check if all plugins
805 * disconnected or must we ask all plugins to
808 static void disconnect_neighbour (struct NeighbourList *n, int check);
811 * Check the ready list for the given neighbour and if a plugin is
812 * ready for transmission (and if we have a message), do so!
814 * @param neighbour target peer for which to transmit
816 static void try_transmission_to_peer (struct NeighbourList *neighbour);
820 * Find an entry in the neighbour list for a particular peer.
821 * if sender_address is not specified (NULL) then return the
822 * first matching entry. If sender_address is specified, then
823 * make sure that the address and address_len also matches.
825 * @return NULL if not found.
827 static struct NeighbourList *
828 find_neighbour (const struct GNUNET_PeerIdentity *key)
830 struct NeighbourList *head = neighbours;
832 while ((head != NULL) &&
833 (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
840 * Find an entry in the transport list for a particular transport.
842 * @return NULL if not found.
844 static struct TransportPlugin *
845 find_transport (const char *short_name)
847 struct TransportPlugin *head = plugins;
848 while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
855 * Update the quota values for the given neighbour now.
858 update_quota (struct NeighbourList *n)
860 struct GNUNET_TIME_Relative delta;
864 delta = GNUNET_TIME_absolute_get_duration (n->last_quota_update);
865 if (delta.value < MIN_QUOTA_REFRESH_TIME)
866 return; /* not enough time passed for doing quota update */
867 allowed = delta.value * n->quota_in;
869 if (n->last_received < allowed)
871 remaining = allowed - n->last_received;
873 remaining /= n->quota_in;
876 if (remaining > MAX_BANDWIDTH_CARRY)
877 remaining = MAX_BANDWIDTH_CARRY;
878 n->last_received = 0;
879 n->last_quota_update = GNUNET_TIME_absolute_get ();
880 n->last_quota_update.value -= remaining;
881 if (n->quota_violation_count > 0)
882 n->quota_violation_count--;
886 n->last_received -= allowed;
887 n->last_quota_update = GNUNET_TIME_absolute_get ();
888 if (n->last_received > allowed)
890 /* more than twice the allowed rate! */
891 n->quota_violation_count += 10;
898 * Function called to notify a client about the socket being ready to
899 * queue more data. "buf" will be NULL and "size" zero if the socket
900 * was closed for writing in the meantime.
903 * @param size number of bytes available in buf
904 * @param buf where the callee should write the message
905 * @return number of bytes written to buf
908 transmit_to_client_callback (void *cls, size_t size, void *buf)
910 struct TransportClient *client = cls;
911 struct ClientMessageQueueEntry *q;
914 const struct GNUNET_MessageHeader *msg;
915 struct GNUNET_CONNECTION_TransmitHandle *th;
920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
921 "Transmission to client failed, closing connection.\n");
922 /* fatal error with client, free message queue! */
923 while (NULL != (q = client->message_queue_head))
925 client->message_queue_head = q->next;
928 client->message_queue_tail = NULL;
929 client->message_count = 0;
934 while (NULL != (q = client->message_queue_head))
936 msg = (const struct GNUNET_MessageHeader *) &q[1];
937 msize = ntohs (msg->size);
938 if (msize + tsize > size)
941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942 "Transmitting message of type %u to client.\n",
945 client->message_queue_head = q->next;
947 client->message_queue_tail = NULL;
948 memcpy (&cbuf[tsize], msg, msize);
951 client->message_count--;
955 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
956 th = GNUNET_SERVER_notify_transmit_ready (client->client,
958 GNUNET_TIME_UNIT_FOREVER_REL,
959 &transmit_to_client_callback,
961 GNUNET_assert (th != NULL);
968 * Send the specified message to the specified client. Since multiple
969 * messages may be pending for the same client at a time, this code
970 * makes sure that no message is lost.
972 * @param client client to transmit the message to
973 * @param msg the message to send
974 * @param may_drop can this message be dropped if the
975 * message queue for this client is getting far too large?
978 transmit_to_client (struct TransportClient *client,
979 const struct GNUNET_MessageHeader *msg, int may_drop)
981 struct ClientMessageQueueEntry *q;
983 struct GNUNET_CONNECTION_TransmitHandle *th;
985 if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
987 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
989 ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
990 client->message_count, MAX_PENDING);
991 /* TODO: call to statistics... */
994 client->message_count++;
995 msize = ntohs (msg->size);
996 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
997 q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
998 memcpy (&q[1], msg, msize);
999 /* append to message queue */
1000 if (client->message_queue_tail == NULL)
1002 client->message_queue_tail = q;
1006 client->message_queue_tail->next = q;
1007 client->message_queue_tail = q;
1009 if (client->message_queue_head == NULL)
1011 client->message_queue_head = q;
1012 th = GNUNET_SERVER_notify_transmit_ready (client->client,
1014 GNUNET_TIME_UNIT_FOREVER_REL,
1015 &transmit_to_client_callback,
1017 GNUNET_assert (th != NULL);
1023 * Transmit a 'SEND_OK' notification to the given client for the
1026 * @param client who to notify
1027 * @param n neighbour to notify about
1028 * @param result status code for the transmission request
1031 transmit_send_ok (struct TransportClient *client,
1032 struct NeighbourList *n,
1035 struct SendOkMessage send_ok_msg;
1037 send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1038 send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1039 send_ok_msg.success = htonl (result);
1040 send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1041 send_ok_msg.peer = n->id;
1042 transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1047 * Function called by the GNUNET_TRANSPORT_TransmitFunction
1048 * upon "completion" of a send request. This tells the API
1049 * that it is now legal to send another message to the given
1052 * @param cls closure, identifies the entry on the
1053 * message queue that was transmitted and the
1054 * client responsible for queueing the message
1055 * @param target the peer receiving the message
1056 * @param result GNUNET_OK on success, if the transmission
1057 * failed, we should not tell the client to transmit
1061 transmit_send_continuation (void *cls,
1062 const struct GNUNET_PeerIdentity *target,
1065 struct MessageQueue *mq = cls;
1066 struct NeighbourList *n;
1068 n = find_neighbour(&mq->neighbour_id);
1069 GNUNET_assert (n != NULL);
1070 if (mq->specific_address != NULL)
1072 if (result == GNUNET_OK)
1074 mq->specific_address->timeout =
1075 GNUNET_TIME_relative_to_absolute
1076 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1077 mq->specific_address->connected = GNUNET_YES;
1081 mq->specific_address->connected = GNUNET_NO;
1083 if (! mq->internal_msg)
1084 mq->specific_address->in_transmit = GNUNET_NO;
1086 if (mq->client != NULL)
1087 transmit_send_ok (mq->client, n, result);
1089 try_transmission_to_peer (n);
1090 if (result != GNUNET_OK)
1091 disconnect_neighbour (n, GNUNET_YES);
1096 * Find an address in any of the available transports for
1097 * the given neighbour that would be good for message
1098 * transmission. This is essentially the transport selection
1101 * @param neighbour for whom to select an address
1102 * @return selected address, NULL if we have none
1104 struct ForeignAddressList *
1105 find_ready_address(struct NeighbourList *neighbour)
1107 struct ReadyList *head = neighbour->plugins;
1108 struct ForeignAddressList *addresses;
1109 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1110 struct ForeignAddressList *best_address;
1112 best_address = NULL;
1113 while (head != NULL)
1115 addresses = head->addresses;
1116 while (addresses != NULL)
1118 if ( (addresses->timeout.value < now.value) &&
1119 (addresses->connected == GNUNET_YES) )
1122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123 "Marking long-time inactive connection to `%4s' as down.\n",
1124 GNUNET_i2s (&neighbour->id));
1126 addresses->connected = GNUNET_NO;
1128 addresses = addresses->next;
1131 addresses = head->addresses;
1132 while (addresses != NULL)
1134 if ( ( (best_address == NULL) ||
1135 (addresses->connected == GNUNET_YES) ||
1136 (best_address->connected == GNUNET_NO) ) &&
1137 (addresses->in_transmit == GNUNET_NO) &&
1138 ( (best_address == NULL) ||
1139 (addresses->latency.value < best_address->latency.value)) )
1140 best_address = addresses;
1141 /* FIXME: also give lower-latency addresses that are not
1142 connected a chance some times... */
1143 addresses = addresses->next;
1148 if (best_address != NULL)
1150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151 "Best address found has latency of %llu ms.\n",
1152 best_address->latency.value);
1155 return best_address;
1161 * We should re-try transmitting to the given peer,
1162 * hopefully we've learned something in the meantime.
1165 retry_transmission_task (void *cls,
1166 const struct GNUNET_SCHEDULER_TaskContext *tc)
1168 struct NeighbourList *n = cls;
1170 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1171 try_transmission_to_peer (n);
1176 * Check the ready list for the given neighbour and if a plugin is
1177 * ready for transmission (and if we have a message), do so!
1179 * @param neighbour target peer for which to transmit
1182 try_transmission_to_peer (struct NeighbourList *neighbour)
1184 struct GNUNET_TIME_Relative min_latency;
1185 struct ReadyList *rl;
1186 struct MessageQueue *mq;
1187 struct GNUNET_TIME_Relative timeout;
1189 if (neighbour->messages_head == NULL)
1190 return; /* nothing to do */
1191 min_latency = GNUNET_TIME_UNIT_FOREVER_REL;
1193 mq = neighbour->messages_head;
1194 /* FIXME: support bi-directional use of TCP */
1195 if (mq->specific_address == NULL)
1196 mq->specific_address = find_ready_address(neighbour);
1197 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1198 neighbour->messages_tail,
1200 if (mq->specific_address == NULL)
1202 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1203 if (timeout.value == 0)
1206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1207 "No destination address available to transmit message of size %u to peer `%4s'\n",
1208 mq->message_buf_size,
1209 GNUNET_i2s (&mq->neighbour_id));
1211 if (mq->client != NULL)
1212 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1214 return; /* nobody ready */
1216 if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1217 GNUNET_SCHEDULER_cancel (sched,
1218 neighbour->retry_task);
1219 neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1221 &retry_transmission_task,
1225 if (mq->specific_address->connected == GNUNET_NO)
1226 mq->specific_address->connect_attempts++;
1227 rl = mq->specific_address->ready_list;
1228 mq->plugin = rl->plugin;
1229 if (!mq->internal_msg)
1230 mq->specific_address->in_transmit = GNUNET_YES;
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1234 mq->message_buf_size,
1235 GNUNET_i2s (&neighbour->id),
1236 GNUNET_a2s (mq->specific_address->addr,
1237 mq->specific_address->addrlen),
1238 rl->plugin->short_name);
1240 rl->plugin->api->send (rl->plugin->api->cls,
1243 mq->message_buf_size,
1245 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1246 mq->specific_address->addr,
1247 mq->specific_address->addrlen,
1248 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1249 &transmit_send_continuation, mq);
1254 * Send the specified message to the specified peer.
1256 * @param client source of the transmission request (can be NULL)
1257 * @param peer_address ForeignAddressList where we should send this message
1258 * @param priority how important is the message
1259 * @param timeout how long do we have to transmit?
1260 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1261 * @param message_buf_size total size of all messages in message_buf
1262 * @param is_internal is this an internal message; these are pre-pended and
1263 * also do not count for plugins being "ready" to transmit
1264 * @param neighbour handle to the neighbour for transmission
1267 transmit_to_peer (struct TransportClient *client,
1268 struct ForeignAddressList *peer_address,
1269 unsigned int priority,
1270 struct GNUNET_TIME_Relative timeout,
1271 const char *message_buf,
1272 size_t message_buf_size,
1273 int is_internal, struct NeighbourList *neighbour)
1275 struct MessageQueue *mq;
1280 /* check for duplicate submission */
1281 mq = neighbour->messages_head;
1284 if (mq->client == client)
1286 /* client transmitted to same peer twice
1287 before getting SendOk! */
1295 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1296 mq->specific_address = peer_address;
1297 mq->client = client;
1298 memcpy (&mq[1], message_buf, message_buf_size);
1299 mq->message_buf = (const char*) &mq[1];
1300 mq->message_buf_size = message_buf_size;
1301 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1302 mq->internal_msg = is_internal;
1303 mq->priority = priority;
1304 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1306 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1307 neighbour->messages_tail,
1310 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1311 neighbour->messages_tail,
1312 neighbour->messages_tail,
1314 try_transmission_to_peer (neighbour);
1321 struct GeneratorContext
1323 struct TransportPlugin *plug_pos;
1324 struct OwnAddressList *addr_pos;
1325 struct GNUNET_TIME_Absolute expiration;
1333 address_generator (void *cls, size_t max, void *buf)
1335 struct GeneratorContext *gc = cls;
1338 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1340 gc->plug_pos = gc->plug_pos->next;
1341 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1343 if (NULL == gc->plug_pos)
1348 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1351 gc->addr_pos->addrlen, buf, max);
1352 gc->addr_pos = gc->addr_pos->next;
1358 * Construct our HELLO message from all of the addresses of
1359 * all of the transports.
1364 struct GNUNET_HELLO_Message *hello;
1365 struct TransportClient *cpos;
1366 struct NeighbourList *npos;
1367 struct GeneratorContext gc;
1369 gc.plug_pos = plugins;
1370 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1371 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1372 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1375 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1378 while (cpos != NULL)
1380 transmit_to_client (cpos,
1381 (const struct GNUNET_MessageHeader *) hello,
1386 GNUNET_free_non_null (our_hello);
1388 our_hello_version++;
1389 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1391 while (npos != NULL)
1394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1395 "Transmitting updated `%s' to neighbour `%4s'\n",
1396 "HELLO", GNUNET_i2s (&npos->id));
1398 transmit_to_peer (NULL, NULL, 0,
1399 HELLO_ADDRESS_EXPIRATION,
1400 (const char *) our_hello,
1401 GNUNET_HELLO_size(our_hello),
1409 * Task used to clean up expired addresses for a plugin.
1411 * @param cls closure
1415 expire_address_task (void *cls,
1416 const struct GNUNET_SCHEDULER_TaskContext *tc);
1420 * Update the list of addresses for this plugin,
1421 * expiring those that are past their expiration date.
1423 * @param plugin addresses of which plugin should be recomputed?
1424 * @param fresh set to GNUNET_YES if a new address was added
1425 * and we need to regenerate the HELLO even if nobody
1429 update_addresses (struct TransportPlugin *plugin, int fresh)
1431 struct GNUNET_TIME_Relative min_remaining;
1432 struct GNUNET_TIME_Relative remaining;
1433 struct GNUNET_TIME_Absolute now;
1434 struct OwnAddressList *pos;
1435 struct OwnAddressList *prev;
1436 struct OwnAddressList *next;
1439 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1440 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1441 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1442 now = GNUNET_TIME_absolute_get ();
1443 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1444 expired = GNUNET_NO;
1446 pos = plugin->addresses;
1450 if (pos->expires.value < now.value)
1452 expired = GNUNET_YES;
1454 plugin->addresses = pos->next;
1456 prev->next = pos->next;
1461 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1462 if (remaining.value < min_remaining.value)
1463 min_remaining = remaining;
1469 if (expired || fresh)
1471 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1472 plugin->address_update_task
1473 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1475 &expire_address_task, plugin);
1481 * Task used to clean up expired addresses for a plugin.
1483 * @param cls closure
1487 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1489 struct TransportPlugin *plugin = cls;
1490 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1491 update_addresses (plugin, GNUNET_NO);
1496 * Function that must be called by each plugin to notify the
1497 * transport service about the addresses under which the transport
1498 * provided by the plugin can be reached.
1500 * @param cls closure
1501 * @param name name of the transport that generated the address
1502 * @param addr one of the addresses of the host, NULL for the last address
1503 * the specific address format depends on the transport
1504 * @param addrlen length of the address
1505 * @param expires when should this address automatically expire?
1508 plugin_env_notify_address (void *cls,
1512 struct GNUNET_TIME_Relative expires)
1514 struct TransportPlugin *p = cls;
1515 struct OwnAddressList *al;
1516 struct GNUNET_TIME_Absolute abex;
1518 abex = GNUNET_TIME_relative_to_absolute (expires);
1519 GNUNET_assert (p == find_transport (name));
1524 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1526 if (al->expires.value < abex.value)
1533 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1535 al->next = p->addresses;
1538 al->addrlen = addrlen;
1539 memcpy (&al[1], addr, addrlen);
1540 update_addresses (p, GNUNET_YES);
1545 * Notify all of our clients about a peer connecting.
1548 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1549 struct GNUNET_TIME_Relative latency,
1552 struct ConnectInfoMessage cim;
1553 struct TransportClient *cpos;
1556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1557 "Notifying clients about connection from `%s'\n",
1560 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1561 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1562 cim.distance = htonl (distance);
1563 cim.latency = GNUNET_TIME_relative_hton (latency);
1564 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1566 while (cpos != NULL)
1568 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1575 * Notify all of our clients about a peer disconnecting.
1578 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1580 struct DisconnectInfoMessage dim;
1581 struct TransportClient *cpos;
1584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1585 "Notifying clients about lost connection to `%s'\n",
1588 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1589 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1590 dim.reserved = htonl (0);
1591 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1593 while (cpos != NULL)
1595 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1602 * Find a ForeignAddressList entry for the given neighbour
1603 * that matches the given address and transport.
1605 * @param neighbour which peer we care about
1606 * @param tname name of the transport plugin
1607 * @param addr binary address
1608 * @param addrlen length of addr
1609 * @return NULL if no such entry exists
1611 static struct ForeignAddressList *
1612 find_peer_address(struct NeighbourList *neighbour,
1617 struct ReadyList *head;
1618 struct ForeignAddressList *address_head;
1620 head = neighbour->plugins;
1621 while (head != NULL)
1623 if (0 == strcmp (tname, head->plugin->short_name))
1630 address_head = head->addresses;
1631 while ( (address_head != NULL) &&
1632 ( (address_head->addrlen != addrlen) ||
1633 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1634 address_head = address_head->next;
1635 return address_head;
1640 * Get the peer address struct for the given neighbour and
1641 * address. If it doesn't yet exist, create it.
1643 * @param neighbour which peer we care about
1644 * @param tname name of the transport plugin
1645 * @param addr binary address
1646 * @param addrlen length of addr
1647 * @return NULL if we do not have a transport plugin for 'tname'
1649 static struct ForeignAddressList *
1650 add_peer_address(struct NeighbourList *neighbour,
1655 struct ReadyList *head;
1656 struct ForeignAddressList *ret;
1658 ret = find_peer_address (neighbour, tname, addr, addrlen);
1661 head = neighbour->plugins;
1662 while (head != NULL)
1664 if (0 == strcmp (tname, head->plugin->short_name))
1670 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1671 ret->addr = (const char*) &ret[1];
1672 memcpy (&ret[1], addr, addrlen);
1673 ret->addrlen = addrlen;
1674 ret->expires = GNUNET_TIME_relative_to_absolute
1675 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1676 ret->latency = GNUNET_TIME_relative_get_forever();
1678 ret->timeout = GNUNET_TIME_relative_to_absolute
1679 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1680 ret->ready_list = head;
1681 ret->next = head->addresses;
1682 head->addresses = ret;
1688 * Closure for 'add_validated_address'.
1690 struct AddValidatedAddressContext
1693 * Entry that has been validated.
1695 const struct ValidationEntry *ve;
1698 * Flag set after we have added the address so
1699 * that we terminate the iteration next time.
1706 * Callback function used to fill a buffer of max bytes with a list of
1707 * addresses in the format used by HELLOs. Should use
1708 * "GNUNET_HELLO_add_address" as a helper function.
1710 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1711 * @param max maximum number of bytes that can be written to buf
1712 * @param buf where to write the address information
1713 * @return number of bytes written, 0 to signal the
1714 * end of the iteration.
1717 add_validated_address (void *cls,
1718 size_t max, void *buf)
1720 struct AddValidatedAddressContext *avac = cls;
1721 const struct ValidationEntry *ve = avac->ve;
1723 if (GNUNET_YES == avac->done)
1725 avac->done = GNUNET_YES;
1726 return GNUNET_HELLO_add_address (ve->transport_name,
1727 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1736 * Iterator over hash map entries. Checks if the given
1737 * validation entry is for the same challenge as what
1738 * is given in the PONG.
1740 * @param cls the 'struct TransportPongMessage*'
1741 * @param key peer identity
1742 * @param value value in the hash map ('struct ValidationEntry')
1743 * @return GNUNET_YES if we should continue to
1744 * iterate (mismatch), GNUNET_NO if not (entry matched)
1747 check_pending_validation (void *cls,
1748 const GNUNET_HashCode * key,
1751 const struct TransportPongMessage *pong = cls;
1752 struct ValidationEntry *ve = value;
1753 struct AddValidatedAddressContext avac;
1754 unsigned int challenge = ntohl(pong->challenge);
1755 struct GNUNET_HELLO_Message *hello;
1756 struct GNUNET_PeerIdentity target;
1757 struct NeighbourList *n;
1758 struct ForeignAddressList *fal;
1760 if (ve->challenge != challenge)
1764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1765 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1767 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1769 ve->transport_name);
1771 /* create the updated HELLO */
1772 GNUNET_CRYPTO_hash (&ve->publicKey,
1773 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1774 &target.hashPubKey);
1775 avac.done = GNUNET_NO;
1777 hello = GNUNET_HELLO_create (&ve->publicKey,
1778 &add_validated_address,
1780 GNUNET_PEERINFO_add_peer (cfg, sched,
1783 GNUNET_free (hello);
1784 n = find_neighbour (&target);
1787 fal = add_peer_address (n, ve->transport_name,
1790 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1791 fal->validated = GNUNET_YES;
1792 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1793 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1794 n->latency = fal->latency;
1796 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1797 n->distance = fal->distance;
1798 if (GNUNET_NO == n->received_pong)
1800 notify_clients_connect (&target, n->latency, n->distance);
1801 n->received_pong = GNUNET_YES;
1803 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1805 GNUNET_SCHEDULER_cancel (sched,
1807 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1808 try_transmission_to_peer (n);
1812 /* clean up validation entry */
1813 GNUNET_assert (GNUNET_YES ==
1814 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1817 GNUNET_SCHEDULER_cancel (sched,
1819 GNUNET_free (ve->transport_name);
1826 * Function that will be called if we receive a validation
1827 * of an address challenge that we transmitted to another
1828 * peer. Note that the validation should only be considered
1829 * acceptable if the challenge matches AND if the sender
1830 * address is at least a plausible address for this peer
1831 * (otherwise we may be seeing a MiM attack).
1833 * @param cls closure
1834 * @param name name of the transport that generated the address
1835 * @param peer who responded to our challenge
1836 * @param challenge the challenge number we presumably used
1837 * @param sender_addr string describing our sender address (as observed
1838 * by the other peer in human-readable format)
1841 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1842 const struct GNUNET_PeerIdentity *peer,
1843 const char *sender_address,
1844 size_t sender_address_len)
1846 #if DEBUG_TRANSPORT > 1
1847 /* we get tons of these that just get discarded, only log
1848 if we are quite verbose */
1849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1850 "Receiving `%s' message from `%4s'.\n", "PONG",
1853 if (GNUNET_SYSERR !=
1854 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1856 &check_pending_validation,
1859 /* This is *expected* to happen a lot since we send
1860 PONGs to *all* known addresses of the sender of
1861 the PING, so most likely we get multiple PONGs
1862 per PING, and all but the first PONG will end up
1863 here. So really we should not print anything here
1864 unless we want to be very, very verbose... */
1865 #if DEBUG_TRANSPORT > 2
1866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1867 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1876 /* FIXME: add given address to potential pool of our addresses
1878 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1879 _("Another peer saw us using the address `%s' via `%s'.\n"),
1880 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1881 ntohs(pong->addrlen)),
1882 va->transport_name);
1888 neighbour_timeout_task (void *cls,
1889 const struct GNUNET_SCHEDULER_TaskContext *tc)
1891 struct NeighbourList *n = cls;
1894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1895 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1897 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1898 disconnect_neighbour (n, GNUNET_NO);
1903 * Create a fresh entry in our neighbour list for the given peer.
1904 * Will try to transmit our current HELLO to the new neighbour. Also
1905 * notifies our clients about the new "connection".
1907 * @param peer the peer for which we create the entry
1908 * @return the new neighbour list entry
1910 static struct NeighbourList *
1911 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1913 struct NeighbourList *n;
1914 struct TransportPlugin *tp;
1915 struct ReadyList *rl;
1917 GNUNET_assert (our_hello != NULL);
1918 n = GNUNET_malloc (sizeof (struct NeighbourList));
1919 n->next = neighbours;
1922 n->last_quota_update = GNUNET_TIME_absolute_get ();
1924 GNUNET_TIME_relative_to_absolute
1925 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1926 n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1930 if (tp->api->send != NULL)
1932 rl = GNUNET_malloc (sizeof (struct ReadyList));
1933 rl->next = n->plugins;
1936 rl->addresses = NULL;
1940 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1942 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1943 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1944 &neighbour_timeout_task, n);
1945 transmit_to_peer (NULL, NULL, 0,
1946 HELLO_ADDRESS_EXPIRATION,
1947 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1954 * Closure for 'check_address_exists'.
1956 struct CheckAddressExistsClosure
1959 * Address to check for.
1964 * Name of the transport.
1974 * Set to GNUNET_YES if the address exists.
1981 * Iterator over hash map entries. Checks if the given
1982 * validation entry is for the same address as what is given
1985 * @param cls the 'struct CheckAddressExistsClosure*'
1986 * @param key current key code (ignored)
1987 * @param value value in the hash map ('struct ValidationEntry')
1988 * @return GNUNET_YES if we should continue to
1989 * iterate (mismatch), GNUNET_NO if not (entry matched)
1992 check_address_exists (void *cls,
1993 const GNUNET_HashCode * key,
1996 struct CheckAddressExistsClosure *caec = cls;
1997 struct ValidationEntry *ve = value;
1998 if ( (0 == strcmp (caec->tname,
1999 ve->transport_name)) &&
2000 (caec->addrlen == ve->addrlen) &&
2001 (0 == memcmp (caec->addr,
2005 caec->exists = GNUNET_YES;
2013 * HELLO validation cleanup task (validation failed).
2015 * @param cls the 'struct ValidationEntry' that failed
2016 * @param tc scheduler context (unused)
2019 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2021 struct ValidationEntry *va = cls;
2022 struct GNUNET_PeerIdentity pid;
2024 GNUNET_CRYPTO_hash (&va->publicKey,
2026 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2028 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2031 GNUNET_free (va->transport_name);
2037 * Check if the given address is already being validated; if not,
2038 * append the given address to the list of entries that are being be
2039 * validated and initiate validation.
2041 * @param cls closure ('struct CheckHelloValidatedContext *')
2042 * @param tname name of the transport
2043 * @param expiration expiration time
2044 * @param addr the address
2045 * @param addrlen length of the address
2046 * @return GNUNET_OK (always)
2049 run_validation (void *cls,
2051 struct GNUNET_TIME_Absolute expiration,
2052 const void *addr, size_t addrlen)
2054 struct CheckHelloValidatedContext *chvc = cls;
2055 struct GNUNET_PeerIdentity id;
2056 struct TransportPlugin *tp;
2057 struct ValidationEntry *va;
2058 struct NeighbourList *neighbour;
2059 struct ForeignAddressList *peer_address;
2060 struct TransportPingMessage ping;
2061 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2062 struct CheckAddressExistsClosure caec;
2064 uint16_t hello_size;
2067 tp = find_transport (tname);
2070 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2071 GNUNET_ERROR_TYPE_BULK,
2073 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2077 GNUNET_HELLO_get_key (chvc->hello, &pk);
2078 GNUNET_CRYPTO_hash (&pk,
2080 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2083 caec.addrlen = addrlen;
2085 caec.exists = GNUNET_NO;
2086 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2087 &check_address_exists,
2089 if (caec.exists == GNUNET_YES)
2091 /* During validation attempts we will likely trigger the other
2092 peer trying to validate our address which in turn will cause
2093 it to send us its HELLO, so we expect to hit this case rather
2094 frequently. Only print something if we are very verbose. */
2095 #if DEBUG_TRANSPORT > 1
2096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2097 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2098 GNUNET_a2s (addr, addrlen),
2104 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2105 va->transport_name = GNUNET_strdup (tname);
2106 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2108 va->send_time = GNUNET_TIME_absolute_get();
2109 va->addr = (const void*) &va[1];
2110 memcpy (&va[1], addr, addrlen);
2111 va->addrlen = addrlen;
2112 GNUNET_HELLO_get_key (chvc->hello,
2114 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2115 HELLO_VERIFICATION_TIMEOUT,
2116 &timeout_hello_validation,
2118 GNUNET_CONTAINER_multihashmap_put (validation_map,
2121 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2122 neighbour = find_neighbour(&id);
2123 if (neighbour == NULL)
2124 neighbour = setup_new_neighbour(&id);
2125 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2126 GNUNET_assert(peer_address != NULL);
2127 hello_size = GNUNET_HELLO_size(our_hello);
2128 tsize = sizeof(struct TransportPingMessage) + hello_size;
2129 message_buf = GNUNET_malloc(tsize);
2130 ping.challenge = htonl(va->challenge);
2131 ping.header.size = htons(sizeof(struct TransportPingMessage));
2132 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2133 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2134 memcpy(message_buf, our_hello, hello_size);
2135 memcpy(&message_buf[hello_size],
2137 sizeof(struct TransportPingMessage));
2139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2141 GNUNET_a2s (addr, addrlen),
2144 "HELLO", hello_size,
2145 "PING", sizeof (struct TransportPingMessage));
2147 transmit_to_peer (NULL, peer_address,
2148 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2149 HELLO_VERIFICATION_TIMEOUT,
2151 GNUNET_YES, neighbour);
2152 GNUNET_free(message_buf);
2158 * Add the given address to the list of foreign addresses
2159 * available for the given peer (check for duplicates).
2161 * @param cls the respective 'struct NeighbourList' to update
2162 * @param tname name of the transport
2163 * @param expiration expiration time
2164 * @param addr the address
2165 * @param addrlen length of the address
2166 * @return GNUNET_OK (always)
2169 add_to_foreign_address_list (void *cls,
2171 struct GNUNET_TIME_Absolute expiration,
2172 const void *addr, size_t addrlen)
2174 struct NeighbourList *n = cls;
2175 struct ForeignAddressList *fal;
2177 fal = find_peer_address (n, tname, addr, addrlen);
2181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data.\n",
2183 GNUNET_a2s (addr, addrlen),
2185 GNUNET_i2s (&n->id));
2187 fal = add_peer_address (n, tname, addr, addrlen);
2191 fal->expires = GNUNET_TIME_absolute_max (expiration,
2193 fal->validated = GNUNET_YES;
2199 * Check if addresses in validated hello "h" overlap with
2200 * those in "chvc->hello" and validate the rest.
2202 * @param cls closure
2203 * @param peer id of the peer, NULL for last call
2204 * @param hello hello message for the peer (can be NULL)
2205 * @param trust amount of trust we have in the peer (not used)
2208 check_hello_validated (void *cls,
2209 const struct GNUNET_PeerIdentity *peer,
2210 const struct GNUNET_HELLO_Message *h,
2213 struct CheckHelloValidatedContext *chvc = cls;
2214 struct GNUNET_HELLO_Message *plain_hello;
2215 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2216 struct GNUNET_PeerIdentity target;
2217 struct NeighbourList *n;
2222 GNUNET_CONTAINER_DLL_remove (chvc_head,
2225 if (GNUNET_NO == chvc->hello_known)
2227 /* notify PEERINFO about the peer now, so that we at least
2228 have the public key if some other component needs it */
2229 GNUNET_HELLO_get_key (chvc->hello, &pk);
2230 GNUNET_CRYPTO_hash (&pk,
2231 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2232 &target.hashPubKey);
2233 plain_hello = GNUNET_HELLO_create (&pk,
2236 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2237 GNUNET_free (plain_hello);
2239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2240 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2242 GNUNET_i2s (&target));
2244 GNUNET_HELLO_iterate_addresses (chvc->hello,
2254 chvc->hello_known = GNUNET_YES;
2255 n = find_neighbour (peer);
2257 GNUNET_HELLO_iterate_addresses (h,
2259 &add_to_foreign_address_list,
2261 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2263 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2269 * Process HELLO-message.
2271 * @param plugin transport involved, may be NULL
2272 * @param message the actual message
2273 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2276 process_hello (struct TransportPlugin *plugin,
2277 const struct GNUNET_MessageHeader *message)
2280 struct GNUNET_PeerIdentity target;
2281 const struct GNUNET_HELLO_Message *hello;
2282 struct CheckHelloValidatedContext *chvc;
2283 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2285 hsize = ntohs (message->size);
2286 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2287 (hsize < sizeof (struct GNUNET_MessageHeader)))
2290 return GNUNET_SYSERR;
2292 /* first, check if load is too high */
2293 if (GNUNET_SCHEDULER_get_load (sched,
2294 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2296 /* TODO: call to stats? */
2299 hello = (const struct GNUNET_HELLO_Message *) message;
2300 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2302 GNUNET_break_op (0);
2303 return GNUNET_SYSERR;
2305 GNUNET_CRYPTO_hash (&publicKey,
2306 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2307 &target.hashPubKey);
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "Processing `%s' message for `%4s' of size %u\n",
2312 GNUNET_i2s (&target),
2313 GNUNET_HELLO_size(hello));
2316 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2317 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2318 memcpy (&chvc[1], hello, hsize);
2319 GNUNET_CONTAINER_DLL_insert (chvc_head,
2322 /* finally, check if HELLO was previously validated
2323 (continuation will then schedule actual validation) */
2324 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2328 HELLO_VERIFICATION_TIMEOUT,
2329 &check_hello_validated, chvc);
2335 * The peer specified by the given neighbour has timed-out or a plugin
2336 * has disconnected. We may either need to do nothing (other plugins
2337 * still up), or trigger a full disconnect and clean up. This
2338 * function updates our state and does the necessary notifications.
2339 * Also notifies our clients that the neighbour is now officially
2342 * @param n the neighbour list entry for the peer
2343 * @param check should we just check if all plugins
2344 * disconnected or must we ask all plugins to
2348 disconnect_neighbour (struct NeighbourList *n, int check)
2350 struct ReadyList *rpos;
2351 struct NeighbourList *npos;
2352 struct NeighbourList *nprev;
2353 struct MessageQueue *mq;
2354 struct ForeignAddressList *peer_addresses;
2355 struct ForeignAddressList *peer_pos;
2357 if (GNUNET_YES == check)
2360 while (NULL != rpos)
2362 peer_addresses = rpos->addresses;
2363 while (peer_addresses != NULL)
2365 if (GNUNET_YES == peer_addresses->connected)
2366 return; /* still connected */
2367 peer_addresses = peer_addresses->next;
2373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2374 "Disconnecting from `%4s'\n",
2375 GNUNET_i2s (&n->id));
2377 /* remove n from neighbours list */
2380 while ((npos != NULL) && (npos != n))
2385 GNUNET_assert (npos != NULL);
2387 neighbours = n->next;
2389 nprev->next = n->next;
2391 /* notify all clients about disconnect */
2392 if (GNUNET_YES == n->received_pong)
2393 notify_clients_disconnect (&n->id);
2395 /* clean up all plugins, cancel connections and pending transmissions */
2396 while (NULL != (rpos = n->plugins))
2398 n->plugins = rpos->next;
2399 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2401 while (rpos->addresses != NULL)
2403 peer_pos = rpos->addresses;
2404 rpos->addresses = peer_pos->next;
2405 GNUNET_free(peer_pos);
2410 /* free all messages on the queue */
2411 while (NULL != (mq = n->messages_head))
2413 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2416 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2418 sizeof(struct GNUNET_PeerIdentity)));
2421 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2423 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2424 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2426 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2428 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2429 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2431 /* finally, free n itself */
2437 * We have received a PING message from someone. Need to send a PONG message
2438 * in response to the peer by any means necessary.
2440 * FIXME: With something like TCP where a connection exists, we may
2441 * want to send it that way. But the current API does not seem to
2442 * allow us to do so (can't tell this to the transport!)
2445 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2446 const struct GNUNET_PeerIdentity *peer,
2447 const char *sender_address,
2448 size_t sender_address_len)
2450 struct TransportPlugin *plugin = cls;
2451 struct TransportPingMessage *ping;
2452 struct TransportPongMessage *pong;
2454 struct NeighbourList *n;
2455 struct ReadyList *rl;
2456 struct ForeignAddressList *fal;
2458 msize = ntohs (message->size);
2459 if (msize < sizeof (struct TransportPingMessage))
2461 GNUNET_break_op (0);
2462 return GNUNET_SYSERR;
2464 ping = (struct TransportPingMessage *) message;
2465 if (0 != memcmp (&ping->target,
2466 plugin->env.my_identity,
2467 sizeof (struct GNUNET_PeerIdentity)))
2469 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2470 _("Received `%s' message not destined for me!\n"),
2472 return GNUNET_SYSERR;
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2476 "Processing `%s' from `%s'\n",
2478 GNUNET_a2s ((const struct sockaddr *)sender_address,
2479 sender_address_len));
2481 msize -= sizeof (struct TransportPingMessage);
2482 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2483 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2484 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2485 pong->purpose.size =
2486 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2488 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2489 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2490 pong->challenge = ping->challenge;
2491 pong->addrlen = htons(sender_address_len);
2492 memcpy(&pong->signer,
2494 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2495 memcpy (&pong[1], sender_address, sender_address_len);
2496 GNUNET_assert (GNUNET_OK ==
2497 GNUNET_CRYPTO_rsa_sign (my_private_key,
2498 &pong->purpose, &pong->signature));
2500 n = find_neighbour(peer);
2502 n = setup_new_neighbour(peer);
2503 /* broadcast 'PONG' to all available addresses */
2507 fal = rl->addresses;
2510 transmit_to_peer(NULL, fal,
2511 TRANSPORT_PONG_PRIORITY,
2512 HELLO_VERIFICATION_TIMEOUT,
2514 ntohs(pong->header.size),
2527 * Function called by the plugin for each received message.
2528 * Update data volumes, possibly notify plugins about
2529 * reducing the rate at which they read from the socket
2530 * and generally forward to our receive callback.
2532 * @param cls the "struct TransportPlugin *" we gave to the plugin
2533 * @param message the message, NULL if peer was disconnected
2534 * @param distance the transport cost to this peer (not latency!)
2535 * @param sender_address the address that the sender reported
2536 * (opaque to transport service)
2537 * @param sender_address_len the length of the sender address
2538 * @param peer (claimed) identity of the other peer
2539 * @return the new service_context that the plugin should use
2540 * for future receive calls for messages from this
2545 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2546 const struct GNUNET_MessageHeader *message,
2547 unsigned int distance, const char *sender_address,
2548 size_t sender_address_len)
2550 struct ReadyList *service_context;
2551 struct TransportPlugin *plugin = cls;
2552 struct TransportClient *cpos;
2553 struct InboundMessage *im;
2554 struct ForeignAddressList *peer_address;
2556 struct NeighbourList *n;
2558 n = find_neighbour (peer);
2561 if (message == NULL)
2562 return; /* disconnect of peer already marked down */
2563 n = setup_new_neighbour (peer);
2565 service_context = n->plugins;
2566 while ((service_context != NULL) && (plugin != service_context->plugin))
2567 service_context = service_context->next;
2568 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2569 if (message == NULL)
2572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2573 "Receive failed from `%4s', triggering disconnect\n",
2574 GNUNET_i2s (&n->id));
2576 /* TODO: call stats */
2577 disconnect_neighbour (n, GNUNET_YES);
2580 peer_address = add_peer_address(n,
2583 sender_address_len);
2584 if (peer_address != NULL)
2586 peer_address->distance = distance;
2587 if (peer_address->connected == GNUNET_NO)
2589 peer_address->connected = GNUNET_YES;
2590 peer_address->connect_attempts++;
2592 peer_address->timeout
2594 GNUNET_TIME_relative_to_absolute
2595 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2597 /* update traffic received amount ... */
2598 msize = ntohs (message->size);
2599 n->last_received += msize;
2600 n->distance = distance;
2602 GNUNET_TIME_relative_to_absolute
2603 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2604 GNUNET_SCHEDULER_cancel (sched,
2607 GNUNET_SCHEDULER_add_delayed (sched,
2608 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2609 &neighbour_timeout_task, n);
2611 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2613 /* dropping message due to frequent inbound volume violations! */
2614 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2615 GNUNET_ERROR_TYPE_BULK,
2617 ("Dropping incoming message due to repeated bandwidth quota violations (total of %u).\n"), n->quota_violation_count);
2618 /* TODO: call stats */
2621 switch (ntohs (message->type))
2623 case GNUNET_MESSAGE_TYPE_HELLO:
2624 process_hello (plugin, message);
2626 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2627 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2629 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2630 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2633 if (! n->received_pong)
2635 GNUNET_break_op (0);
2636 #if DEBUG_TRANSPORT || 1
2637 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2638 "Received message of type %u from `%4s', prior to key confirmation (dropped).\n",
2639 ntohs (message->type), GNUNET_i2s (peer));
2644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645 "Received message of type %u from `%4s', sending to all clients.\n",
2646 ntohs (message->type), GNUNET_i2s (peer));
2648 /* transmit message to all clients */
2649 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2650 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2651 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2652 im->latency = GNUNET_TIME_relative_hton (n->latency);
2654 memcpy (&im[1], message, msize);
2657 while (cpos != NULL)
2659 transmit_to_client (cpos, &im->header, GNUNET_YES);
2668 * Handle START-message. This is the first message sent to us
2669 * by any client which causes us to add it to our list.
2671 * @param cls closure (always NULL)
2672 * @param client identification of the client
2673 * @param message the actual message
2676 handle_start (void *cls,
2677 struct GNUNET_SERVER_Client *client,
2678 const struct GNUNET_MessageHeader *message)
2680 struct TransportClient *c;
2681 struct ConnectInfoMessage cim;
2682 struct NeighbourList *n;
2685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686 "Received `%s' request from client\n", "START");
2691 if (c->client == client)
2693 /* client already on our list! */
2695 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2700 c = GNUNET_malloc (sizeof (struct TransportClient));
2704 if (our_hello != NULL)
2707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2708 "Sending our own `%s' to new client\n", "HELLO");
2710 transmit_to_client (c,
2711 (const struct GNUNET_MessageHeader *) our_hello,
2713 /* tell new client about all existing connections */
2714 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2715 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2719 if (GNUNET_YES == n->received_pong)
2722 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2723 cim.distance = htonl (n->distance);
2724 transmit_to_client (c, &cim.header, GNUNET_NO);
2729 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2734 * Handle HELLO-message.
2736 * @param cls closure (always NULL)
2737 * @param client identification of the client
2738 * @param message the actual message
2741 handle_hello (void *cls,
2742 struct GNUNET_SERVER_Client *client,
2743 const struct GNUNET_MessageHeader *message)
2748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749 "Received `%s' request from client\n", "HELLO");
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 pos->message_queue_head = mqe->next;
3049 pos->message_queue_head = NULL;
3051 clients = pos->next;
3053 prev->next = pos->next;
3054 if (GNUNET_YES == pos->tcs_pending)
3064 * Iterator to free entries in the validation_map.
3066 * @param cls closure (unused)
3067 * @param key current key code
3068 * @param value value in the hash map (validation to abort)
3069 * @return GNUNET_YES (always)
3072 abort_validation (void *cls,
3073 const GNUNET_HashCode * key,
3076 struct ValidationEntry *va = value;
3078 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3079 GNUNET_free (va->transport_name);
3086 * Function called when the service shuts down. Unloads our plugins
3087 * and cancels pending validations.
3089 * @param cls closure, unused
3090 * @param tc task context (unused)
3093 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3095 struct TransportPlugin *plug;
3096 struct OwnAddressList *al;
3097 struct CheckHelloValidatedContext *chvc;
3100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3101 "Transport service is unloading plugins...\n");
3103 while (NULL != (plug = plugins))
3105 plugins = plug->next;
3106 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3107 GNUNET_free (plug->lib_name);
3108 GNUNET_free (plug->short_name);
3109 while (NULL != (al = plug->addresses))
3111 plug->addresses = al->next;
3116 if (my_private_key != NULL)
3117 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3118 GNUNET_free_non_null (our_hello);
3120 /* free 'chvc' data structure */
3121 while (NULL != (chvc = chvc_head))
3123 chvc_head = chvc->next;
3124 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3129 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3132 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3137 * Initiate transport service.
3139 * @param cls closure
3140 * @param s scheduler to use
3141 * @param serv the initialized server
3142 * @param c configuration to use
3146 struct GNUNET_SCHEDULER_Handle *s,
3147 struct GNUNET_SERVER_Handle *serv,
3148 const struct GNUNET_CONFIGURATION_Handle *c)
3153 unsigned long long tneigh;
3158 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3159 /* parse configuration */
3161 GNUNET_CONFIGURATION_get_value_number (c,
3166 GNUNET_CONFIGURATION_get_value_filename (c,
3168 "HOSTKEY", &keyfile)))
3170 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3172 ("Transport service is lacking key configuration settings. Exiting.\n"));
3173 GNUNET_SCHEDULER_shutdown (s);
3176 max_connect_per_transport = (uint32_t) tneigh;
3177 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3178 GNUNET_free (keyfile);
3179 if (my_private_key == NULL)
3181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3183 ("Transport service could not access hostkey. Exiting.\n"));
3184 GNUNET_SCHEDULER_shutdown (s);
3187 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3188 GNUNET_CRYPTO_hash (&my_public_key,
3189 sizeof (my_public_key), &my_identity.hashPubKey);
3190 /* setup notification */
3192 GNUNET_SERVER_disconnect_notify (server,
3193 &client_disconnect_notification, NULL);
3194 /* load plugins... */
3197 GNUNET_CONFIGURATION_get_value_string (c,
3198 "TRANSPORT", "PLUGINS", &plugs))
3200 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3201 _("Starting transport plugins `%s'\n"), plugs);
3202 pos = strtok (plugs, " ");
3205 start_transport (server, pos);
3207 pos = strtok (NULL, " ");
3209 GNUNET_free (plugs);
3211 GNUNET_SCHEDULER_add_delayed (sched,
3212 GNUNET_TIME_UNIT_FOREVER_REL,
3213 &shutdown_task, NULL);
3218 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3220 /* process client requests */
3221 GNUNET_SERVER_add_handlers (server, handlers);
3226 * The main function for the transport service.
3228 * @param argc number of arguments from the command line
3229 * @param argv command line arguments
3230 * @return 0 ok, 1 on error
3233 main (int argc, char *const *argv)
3235 return (GNUNET_OK ==
3236 GNUNET_SERVICE_run (argc,
3239 GNUNET_SERVICE_OPTION_NONE,
3240 &run, NULL)) ? 0 : 1;
3243 /* end of gnunet-service-transport.c */