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 if (mq->specific_address == NULL)
1199 timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1200 if (timeout.value == 0)
1203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204 "No destination address available to transmit message of size %u to peer `%4s'\n",
1205 mq->message_buf_size,
1206 GNUNET_i2s (&mq->neighbour_id));
1208 if (mq->client != NULL)
1209 transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1210 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1211 neighbour->messages_tail,
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,
1224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1225 "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1226 mq->message_buf_size,
1227 GNUNET_i2s (&mq->neighbour_id),
1232 GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1233 neighbour->messages_tail,
1235 if (mq->specific_address->connected == GNUNET_NO)
1236 mq->specific_address->connect_attempts++;
1237 rl = mq->specific_address->ready_list;
1238 mq->plugin = rl->plugin;
1239 if (!mq->internal_msg)
1240 mq->specific_address->in_transmit = GNUNET_YES;
1242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1243 "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1244 mq->message_buf_size,
1245 GNUNET_i2s (&neighbour->id),
1246 GNUNET_a2s (mq->specific_address->addr,
1247 mq->specific_address->addrlen),
1248 rl->plugin->short_name);
1250 rl->plugin->api->send (rl->plugin->api->cls,
1253 mq->message_buf_size,
1255 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1256 mq->specific_address->addr,
1257 mq->specific_address->addrlen,
1258 GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1259 &transmit_send_continuation, mq);
1264 * Send the specified message to the specified peer.
1266 * @param client source of the transmission request (can be NULL)
1267 * @param peer_address ForeignAddressList where we should send this message
1268 * @param priority how important is the message
1269 * @param timeout how long do we have to transmit?
1270 * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1271 * @param message_buf_size total size of all messages in message_buf
1272 * @param is_internal is this an internal message; these are pre-pended and
1273 * also do not count for plugins being "ready" to transmit
1274 * @param neighbour handle to the neighbour for transmission
1277 transmit_to_peer (struct TransportClient *client,
1278 struct ForeignAddressList *peer_address,
1279 unsigned int priority,
1280 struct GNUNET_TIME_Relative timeout,
1281 const char *message_buf,
1282 size_t message_buf_size,
1283 int is_internal, struct NeighbourList *neighbour)
1285 struct MessageQueue *mq;
1290 /* check for duplicate submission */
1291 mq = neighbour->messages_head;
1294 if (mq->client == client)
1296 /* client transmitted to same peer twice
1297 before getting SendOk! */
1305 mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1306 mq->specific_address = peer_address;
1307 mq->client = client;
1308 memcpy (&mq[1], message_buf, message_buf_size);
1309 mq->message_buf = (const char*) &mq[1];
1310 mq->message_buf_size = message_buf_size;
1311 memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1312 mq->internal_msg = is_internal;
1313 mq->priority = priority;
1314 mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1316 GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1317 neighbour->messages_tail,
1320 GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1321 neighbour->messages_tail,
1322 neighbour->messages_tail,
1324 try_transmission_to_peer (neighbour);
1331 struct GeneratorContext
1333 struct TransportPlugin *plug_pos;
1334 struct OwnAddressList *addr_pos;
1335 struct GNUNET_TIME_Absolute expiration;
1343 address_generator (void *cls, size_t max, void *buf)
1345 struct GeneratorContext *gc = cls;
1348 while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1350 gc->plug_pos = gc->plug_pos->next;
1351 gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1353 if (NULL == gc->plug_pos)
1358 ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1361 gc->addr_pos->addrlen, buf, max);
1362 gc->addr_pos = gc->addr_pos->next;
1368 * Construct our HELLO message from all of the addresses of
1369 * all of the transports.
1374 struct GNUNET_HELLO_Message *hello;
1375 struct TransportClient *cpos;
1376 struct NeighbourList *npos;
1377 struct GeneratorContext gc;
1379 gc.plug_pos = plugins;
1380 gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1381 gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1382 hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1385 "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1388 while (cpos != NULL)
1390 transmit_to_client (cpos,
1391 (const struct GNUNET_MessageHeader *) hello,
1396 GNUNET_free_non_null (our_hello);
1398 our_hello_version++;
1399 GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1401 while (npos != NULL)
1404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1405 "Transmitting updated `%s' to neighbour `%4s'\n",
1406 "HELLO", GNUNET_i2s (&npos->id));
1408 transmit_to_peer (NULL, NULL, 0,
1409 HELLO_ADDRESS_EXPIRATION,
1410 (const char *) our_hello,
1411 GNUNET_HELLO_size(our_hello),
1419 * Task used to clean up expired addresses for a plugin.
1421 * @param cls closure
1425 expire_address_task (void *cls,
1426 const struct GNUNET_SCHEDULER_TaskContext *tc);
1430 * Update the list of addresses for this plugin,
1431 * expiring those that are past their expiration date.
1433 * @param plugin addresses of which plugin should be recomputed?
1434 * @param fresh set to GNUNET_YES if a new address was added
1435 * and we need to regenerate the HELLO even if nobody
1439 update_addresses (struct TransportPlugin *plugin, int fresh)
1441 struct GNUNET_TIME_Relative min_remaining;
1442 struct GNUNET_TIME_Relative remaining;
1443 struct GNUNET_TIME_Absolute now;
1444 struct OwnAddressList *pos;
1445 struct OwnAddressList *prev;
1446 struct OwnAddressList *next;
1449 if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1450 GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1451 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1452 now = GNUNET_TIME_absolute_get ();
1453 min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1454 expired = GNUNET_NO;
1456 pos = plugin->addresses;
1460 if (pos->expires.value < now.value)
1462 expired = GNUNET_YES;
1464 plugin->addresses = pos->next;
1466 prev->next = pos->next;
1471 remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1472 if (remaining.value < min_remaining.value)
1473 min_remaining = remaining;
1479 if (expired || fresh)
1481 if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1482 plugin->address_update_task
1483 = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1485 &expire_address_task, plugin);
1491 * Task used to clean up expired addresses for a plugin.
1493 * @param cls closure
1497 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1499 struct TransportPlugin *plugin = cls;
1500 plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1501 update_addresses (plugin, GNUNET_NO);
1506 * Function that must be called by each plugin to notify the
1507 * transport service about the addresses under which the transport
1508 * provided by the plugin can be reached.
1510 * @param cls closure
1511 * @param name name of the transport that generated the address
1512 * @param addr one of the addresses of the host, NULL for the last address
1513 * the specific address format depends on the transport
1514 * @param addrlen length of the address
1515 * @param expires when should this address automatically expire?
1518 plugin_env_notify_address (void *cls,
1522 struct GNUNET_TIME_Relative expires)
1524 struct TransportPlugin *p = cls;
1525 struct OwnAddressList *al;
1526 struct GNUNET_TIME_Absolute abex;
1528 abex = GNUNET_TIME_relative_to_absolute (expires);
1529 GNUNET_assert (p == find_transport (name));
1534 if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1536 if (al->expires.value < abex.value)
1543 al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1545 al->next = p->addresses;
1548 al->addrlen = addrlen;
1549 memcpy (&al[1], addr, addrlen);
1550 update_addresses (p, GNUNET_YES);
1555 * Notify all of our clients about a peer connecting.
1558 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1559 struct GNUNET_TIME_Relative latency,
1562 struct ConnectInfoMessage cim;
1563 struct TransportClient *cpos;
1566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567 "Notifying clients about connection from `%s'\n",
1570 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1571 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1572 cim.distance = htonl (distance);
1573 cim.latency = GNUNET_TIME_relative_hton (latency);
1574 memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1576 while (cpos != NULL)
1578 transmit_to_client (cpos, &cim.header, GNUNET_NO);
1585 * Notify all of our clients about a peer disconnecting.
1588 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1590 struct DisconnectInfoMessage dim;
1591 struct TransportClient *cpos;
1594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595 "Notifying clients about lost connection to `%s'\n",
1598 dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1599 dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1600 dim.reserved = htonl (0);
1601 memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1603 while (cpos != NULL)
1605 transmit_to_client (cpos, &dim.header, GNUNET_NO);
1612 * Find a ForeignAddressList entry for the given neighbour
1613 * that matches the given address and transport.
1615 * @param neighbour which peer we care about
1616 * @param tname name of the transport plugin
1617 * @param addr binary address
1618 * @param addrlen length of addr
1619 * @return NULL if no such entry exists
1621 static struct ForeignAddressList *
1622 find_peer_address(struct NeighbourList *neighbour,
1627 struct ReadyList *head;
1628 struct ForeignAddressList *address_head;
1630 head = neighbour->plugins;
1631 while (head != NULL)
1633 if (0 == strcmp (tname, head->plugin->short_name))
1640 address_head = head->addresses;
1641 while ( (address_head != NULL) &&
1642 ( (address_head->addrlen != addrlen) ||
1643 (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1644 address_head = address_head->next;
1645 return address_head;
1650 * Get the peer address struct for the given neighbour and
1651 * address. If it doesn't yet exist, create it.
1653 * @param neighbour which peer we care about
1654 * @param tname name of the transport plugin
1655 * @param addr binary address
1656 * @param addrlen length of addr
1657 * @return NULL if we do not have a transport plugin for 'tname'
1659 static struct ForeignAddressList *
1660 add_peer_address(struct NeighbourList *neighbour,
1665 struct ReadyList *head;
1666 struct ForeignAddressList *ret;
1668 ret = find_peer_address (neighbour, tname, addr, addrlen);
1671 head = neighbour->plugins;
1672 while (head != NULL)
1674 if (0 == strcmp (tname, head->plugin->short_name))
1680 ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1681 ret->addr = (const char*) &ret[1];
1682 memcpy (&ret[1], addr, addrlen);
1683 ret->addrlen = addrlen;
1684 ret->expires = GNUNET_TIME_relative_to_absolute
1685 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1686 ret->latency = GNUNET_TIME_relative_get_forever();
1688 ret->timeout = GNUNET_TIME_relative_to_absolute
1689 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1690 ret->ready_list = head;
1691 ret->next = head->addresses;
1692 head->addresses = ret;
1698 * Closure for 'add_validated_address'.
1700 struct AddValidatedAddressContext
1703 * Entry that has been validated.
1705 const struct ValidationEntry *ve;
1708 * Flag set after we have added the address so
1709 * that we terminate the iteration next time.
1716 * Callback function used to fill a buffer of max bytes with a list of
1717 * addresses in the format used by HELLOs. Should use
1718 * "GNUNET_HELLO_add_address" as a helper function.
1720 * @param cls the 'struct AddValidatedAddressContext' with the validated address
1721 * @param max maximum number of bytes that can be written to buf
1722 * @param buf where to write the address information
1723 * @return number of bytes written, 0 to signal the
1724 * end of the iteration.
1727 add_validated_address (void *cls,
1728 size_t max, void *buf)
1730 struct AddValidatedAddressContext *avac = cls;
1731 const struct ValidationEntry *ve = avac->ve;
1733 if (GNUNET_YES == avac->done)
1735 avac->done = GNUNET_YES;
1736 return GNUNET_HELLO_add_address (ve->transport_name,
1737 GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1746 * Iterator over hash map entries. Checks if the given
1747 * validation entry is for the same challenge as what
1748 * is given in the PONG.
1750 * @param cls the 'struct TransportPongMessage*'
1751 * @param key peer identity
1752 * @param value value in the hash map ('struct ValidationEntry')
1753 * @return GNUNET_YES if we should continue to
1754 * iterate (mismatch), GNUNET_NO if not (entry matched)
1757 check_pending_validation (void *cls,
1758 const GNUNET_HashCode * key,
1761 const struct TransportPongMessage *pong = cls;
1762 struct ValidationEntry *ve = value;
1763 struct AddValidatedAddressContext avac;
1764 unsigned int challenge = ntohl(pong->challenge);
1765 struct GNUNET_HELLO_Message *hello;
1766 struct GNUNET_PeerIdentity target;
1767 struct NeighbourList *n;
1768 struct ForeignAddressList *fal;
1770 if (ve->challenge != challenge)
1774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775 "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1777 GNUNET_a2s ((const struct sockaddr *) ve->addr,
1779 ve->transport_name);
1781 /* create the updated HELLO */
1782 GNUNET_CRYPTO_hash (&ve->publicKey,
1783 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1784 &target.hashPubKey);
1785 avac.done = GNUNET_NO;
1787 hello = GNUNET_HELLO_create (&ve->publicKey,
1788 &add_validated_address,
1790 GNUNET_PEERINFO_add_peer (cfg, sched,
1793 GNUNET_free (hello);
1794 n = find_neighbour (&target);
1797 fal = add_peer_address (n, ve->transport_name,
1800 fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1801 fal->validated = GNUNET_YES;
1802 fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1803 if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1804 n->latency = fal->latency;
1806 n->latency.value = (fal->latency.value + n->latency.value) / 2;
1807 n->distance = fal->distance;
1808 if (GNUNET_NO == n->received_pong)
1810 notify_clients_connect (&target, n->latency, n->distance);
1811 n->received_pong = GNUNET_YES;
1813 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1815 GNUNET_SCHEDULER_cancel (sched,
1817 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1818 try_transmission_to_peer (n);
1822 /* clean up validation entry */
1823 GNUNET_assert (GNUNET_YES ==
1824 GNUNET_CONTAINER_multihashmap_remove (validation_map,
1827 GNUNET_SCHEDULER_cancel (sched,
1829 GNUNET_free (ve->transport_name);
1836 * Function that will be called if we receive a validation
1837 * of an address challenge that we transmitted to another
1838 * peer. Note that the validation should only be considered
1839 * acceptable if the challenge matches AND if the sender
1840 * address is at least a plausible address for this peer
1841 * (otherwise we may be seeing a MiM attack).
1843 * @param cls closure
1844 * @param name name of the transport that generated the address
1845 * @param peer who responded to our challenge
1846 * @param challenge the challenge number we presumably used
1847 * @param sender_addr string describing our sender address (as observed
1848 * by the other peer in human-readable format)
1851 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1852 const struct GNUNET_PeerIdentity *peer,
1853 const char *sender_address,
1854 size_t sender_address_len)
1856 #if DEBUG_TRANSPORT > 1
1857 /* we get tons of these that just get discarded, only log
1858 if we are quite verbose */
1859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1860 "Receiving `%s' message from `%4s'.\n", "PONG",
1863 if (GNUNET_SYSERR !=
1864 GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1866 &check_pending_validation,
1869 /* This is *expected* to happen a lot since we send
1870 PONGs to *all* known addresses of the sender of
1871 the PING, so most likely we get multiple PONGs
1872 per PING, and all but the first PONG will end up
1873 here. So really we should not print anything here
1874 unless we want to be very, very verbose... */
1875 #if DEBUG_TRANSPORT > 2
1876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1877 "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1886 /* FIXME: add given address to potential pool of our addresses
1888 GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1889 _("Another peer saw us using the address `%s' via `%s'.\n"),
1890 GNUNET_a2s ((const struct sockaddr *) &pong[1],
1891 ntohs(pong->addrlen)),
1892 va->transport_name);
1898 neighbour_timeout_task (void *cls,
1899 const struct GNUNET_SCHEDULER_TaskContext *tc)
1901 struct NeighbourList *n = cls;
1904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1905 "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1907 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1908 disconnect_neighbour (n, GNUNET_NO);
1913 * Create a fresh entry in our neighbour list for the given peer.
1914 * Will try to transmit our current HELLO to the new neighbour. Also
1915 * notifies our clients about the new "connection".
1917 * @param peer the peer for which we create the entry
1918 * @return the new neighbour list entry
1920 static struct NeighbourList *
1921 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1923 struct NeighbourList *n;
1924 struct TransportPlugin *tp;
1925 struct ReadyList *rl;
1927 GNUNET_assert (our_hello != NULL);
1928 n = GNUNET_malloc (sizeof (struct NeighbourList));
1929 n->next = neighbours;
1932 n->last_quota_update = GNUNET_TIME_absolute_get ();
1934 GNUNET_TIME_relative_to_absolute
1935 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1936 n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1940 if (tp->api->send != NULL)
1942 rl = GNUNET_malloc (sizeof (struct ReadyList));
1943 rl->next = n->plugins;
1946 rl->addresses = NULL;
1950 n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1952 n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1953 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1954 &neighbour_timeout_task, n);
1955 transmit_to_peer (NULL, NULL, 0,
1956 HELLO_ADDRESS_EXPIRATION,
1957 (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1964 * Closure for 'check_address_exists'.
1966 struct CheckAddressExistsClosure
1969 * Address to check for.
1974 * Name of the transport.
1984 * Set to GNUNET_YES if the address exists.
1991 * Iterator over hash map entries. Checks if the given
1992 * validation entry is for the same address as what is given
1995 * @param cls the 'struct CheckAddressExistsClosure*'
1996 * @param key current key code (ignored)
1997 * @param value value in the hash map ('struct ValidationEntry')
1998 * @return GNUNET_YES if we should continue to
1999 * iterate (mismatch), GNUNET_NO if not (entry matched)
2002 check_address_exists (void *cls,
2003 const GNUNET_HashCode * key,
2006 struct CheckAddressExistsClosure *caec = cls;
2007 struct ValidationEntry *ve = value;
2008 if ( (0 == strcmp (caec->tname,
2009 ve->transport_name)) &&
2010 (caec->addrlen == ve->addrlen) &&
2011 (0 == memcmp (caec->addr,
2015 caec->exists = GNUNET_YES;
2023 * HELLO validation cleanup task (validation failed).
2025 * @param cls the 'struct ValidationEntry' that failed
2026 * @param tc scheduler context (unused)
2029 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2031 struct ValidationEntry *va = cls;
2032 struct GNUNET_PeerIdentity pid;
2034 GNUNET_CRYPTO_hash (&va->publicKey,
2036 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2038 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2041 GNUNET_free (va->transport_name);
2047 * Check if the given address is already being validated; if not,
2048 * append the given address to the list of entries that are being be
2049 * validated and initiate validation.
2051 * @param cls closure ('struct CheckHelloValidatedContext *')
2052 * @param tname name of the transport
2053 * @param expiration expiration time
2054 * @param addr the address
2055 * @param addrlen length of the address
2056 * @return GNUNET_OK (always)
2059 run_validation (void *cls,
2061 struct GNUNET_TIME_Absolute expiration,
2062 const void *addr, size_t addrlen)
2064 struct CheckHelloValidatedContext *chvc = cls;
2065 struct GNUNET_PeerIdentity id;
2066 struct TransportPlugin *tp;
2067 struct ValidationEntry *va;
2068 struct NeighbourList *neighbour;
2069 struct ForeignAddressList *peer_address;
2070 struct TransportPingMessage ping;
2071 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2072 struct CheckAddressExistsClosure caec;
2074 uint16_t hello_size;
2077 tp = find_transport (tname);
2080 GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2081 GNUNET_ERROR_TYPE_BULK,
2083 ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2087 GNUNET_HELLO_get_key (chvc->hello, &pk);
2088 GNUNET_CRYPTO_hash (&pk,
2090 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2093 caec.addrlen = addrlen;
2095 caec.exists = GNUNET_NO;
2096 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2097 &check_address_exists,
2099 if (caec.exists == GNUNET_YES)
2101 /* During validation attempts we will likely trigger the other
2102 peer trying to validate our address which in turn will cause
2103 it to send us its HELLO, so we expect to hit this case rather
2104 frequently. Only print something if we are very verbose. */
2105 #if DEBUG_TRANSPORT > 1
2106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2107 "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2108 GNUNET_a2s (addr, addrlen),
2114 va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2115 va->transport_name = GNUNET_strdup (tname);
2116 va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2118 va->send_time = GNUNET_TIME_absolute_get();
2119 va->addr = (const void*) &va[1];
2120 memcpy (&va[1], addr, addrlen);
2121 va->addrlen = addrlen;
2122 GNUNET_HELLO_get_key (chvc->hello,
2124 va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2125 HELLO_VERIFICATION_TIMEOUT,
2126 &timeout_hello_validation,
2128 GNUNET_CONTAINER_multihashmap_put (validation_map,
2131 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2132 neighbour = find_neighbour(&id);
2133 if (neighbour == NULL)
2134 neighbour = setup_new_neighbour(&id);
2135 peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2136 GNUNET_assert(peer_address != NULL);
2137 hello_size = GNUNET_HELLO_size(our_hello);
2138 tsize = sizeof(struct TransportPingMessage) + hello_size;
2139 message_buf = GNUNET_malloc(tsize);
2140 ping.challenge = htonl(va->challenge);
2141 ping.header.size = htons(sizeof(struct TransportPingMessage));
2142 ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2143 memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2144 memcpy(message_buf, our_hello, hello_size);
2145 memcpy(&message_buf[hello_size],
2147 sizeof(struct TransportPingMessage));
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2151 GNUNET_a2s (addr, addrlen),
2154 "HELLO", hello_size,
2155 "PING", sizeof (struct TransportPingMessage));
2157 transmit_to_peer (NULL, peer_address,
2158 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2159 HELLO_VERIFICATION_TIMEOUT,
2161 GNUNET_YES, neighbour);
2162 GNUNET_free(message_buf);
2168 * Add the given address to the list of foreign addresses
2169 * available for the given peer (check for duplicates).
2171 * @param cls the respective 'struct NeighbourList' to update
2172 * @param tname name of the transport
2173 * @param expiration expiration time
2174 * @param addr the address
2175 * @param addrlen length of the address
2176 * @return GNUNET_OK (always)
2179 add_to_foreign_address_list (void *cls,
2181 struct GNUNET_TIME_Absolute expiration,
2182 const void *addr, size_t addrlen)
2184 struct NeighbourList *n = cls;
2185 struct ForeignAddressList *fal;
2187 fal = find_peer_address (n, tname, addr, addrlen);
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2193 GNUNET_a2s (addr, addrlen),
2195 GNUNET_i2s (&n->id),
2198 fal = add_peer_address (n, tname, addr, addrlen);
2202 fal->expires = GNUNET_TIME_absolute_max (expiration,
2204 fal->validated = GNUNET_YES;
2210 * Check if addresses in validated hello "h" overlap with
2211 * those in "chvc->hello" and validate the rest.
2213 * @param cls closure
2214 * @param peer id of the peer, NULL for last call
2215 * @param hello hello message for the peer (can be NULL)
2216 * @param trust amount of trust we have in the peer (not used)
2219 check_hello_validated (void *cls,
2220 const struct GNUNET_PeerIdentity *peer,
2221 const struct GNUNET_HELLO_Message *h,
2224 struct CheckHelloValidatedContext *chvc = cls;
2225 struct GNUNET_HELLO_Message *plain_hello;
2226 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2227 struct GNUNET_PeerIdentity target;
2228 struct NeighbourList *n;
2233 GNUNET_CONTAINER_DLL_remove (chvc_head,
2236 if (GNUNET_NO == chvc->hello_known)
2238 /* notify PEERINFO about the peer now, so that we at least
2239 have the public key if some other component needs it */
2240 GNUNET_HELLO_get_key (chvc->hello, &pk);
2241 GNUNET_CRYPTO_hash (&pk,
2242 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2243 &target.hashPubKey);
2244 plain_hello = GNUNET_HELLO_create (&pk,
2247 GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2248 GNUNET_free (plain_hello);
2250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2251 "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2253 GNUNET_i2s (&target));
2255 GNUNET_HELLO_iterate_addresses (chvc->hello,
2265 chvc->hello_known = GNUNET_YES;
2266 n = find_neighbour (peer);
2269 GNUNET_HELLO_iterate_addresses (h,
2271 &add_to_foreign_address_list,
2273 try_transmission_to_peer (n);
2275 GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2277 GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2283 * Process HELLO-message.
2285 * @param plugin transport involved, may be NULL
2286 * @param message the actual message
2287 * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2290 process_hello (struct TransportPlugin *plugin,
2291 const struct GNUNET_MessageHeader *message)
2294 struct GNUNET_PeerIdentity target;
2295 const struct GNUNET_HELLO_Message *hello;
2296 struct CheckHelloValidatedContext *chvc;
2297 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2299 hsize = ntohs (message->size);
2300 if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2301 (hsize < sizeof (struct GNUNET_MessageHeader)))
2304 return GNUNET_SYSERR;
2306 /* first, check if load is too high */
2307 if (GNUNET_SCHEDULER_get_load (sched,
2308 GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2310 /* TODO: call to stats? */
2313 hello = (const struct GNUNET_HELLO_Message *) message;
2314 if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2316 GNUNET_break_op (0);
2317 return GNUNET_SYSERR;
2319 GNUNET_CRYPTO_hash (&publicKey,
2320 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2321 &target.hashPubKey);
2323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324 "Processing `%s' message for `%4s' of size %u\n",
2326 GNUNET_i2s (&target),
2327 GNUNET_HELLO_size(hello));
2330 chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2331 chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2332 memcpy (&chvc[1], hello, hsize);
2333 GNUNET_CONTAINER_DLL_insert (chvc_head,
2336 /* finally, check if HELLO was previously validated
2337 (continuation will then schedule actual validation) */
2338 chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2342 HELLO_VERIFICATION_TIMEOUT,
2343 &check_hello_validated, chvc);
2349 * The peer specified by the given neighbour has timed-out or a plugin
2350 * has disconnected. We may either need to do nothing (other plugins
2351 * still up), or trigger a full disconnect and clean up. This
2352 * function updates our state and does the necessary notifications.
2353 * Also notifies our clients that the neighbour is now officially
2356 * @param n the neighbour list entry for the peer
2357 * @param check should we just check if all plugins
2358 * disconnected or must we ask all plugins to
2362 disconnect_neighbour (struct NeighbourList *n, int check)
2364 struct ReadyList *rpos;
2365 struct NeighbourList *npos;
2366 struct NeighbourList *nprev;
2367 struct MessageQueue *mq;
2368 struct ForeignAddressList *peer_addresses;
2369 struct ForeignAddressList *peer_pos;
2371 if (GNUNET_YES == check)
2374 while (NULL != rpos)
2376 peer_addresses = rpos->addresses;
2377 while (peer_addresses != NULL)
2379 if (GNUNET_YES == peer_addresses->connected)
2380 return; /* still connected */
2381 peer_addresses = peer_addresses->next;
2387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2388 "Disconnecting from `%4s'\n",
2389 GNUNET_i2s (&n->id));
2391 /* remove n from neighbours list */
2394 while ((npos != NULL) && (npos != n))
2399 GNUNET_assert (npos != NULL);
2401 neighbours = n->next;
2403 nprev->next = n->next;
2405 /* notify all clients about disconnect */
2406 if (GNUNET_YES == n->received_pong)
2407 notify_clients_disconnect (&n->id);
2409 /* clean up all plugins, cancel connections and pending transmissions */
2410 while (NULL != (rpos = n->plugins))
2412 n->plugins = rpos->next;
2413 rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2415 while (rpos->addresses != NULL)
2417 peer_pos = rpos->addresses;
2418 rpos->addresses = peer_pos->next;
2419 GNUNET_free(peer_pos);
2424 /* free all messages on the queue */
2425 while (NULL != (mq = n->messages_head))
2427 GNUNET_CONTAINER_DLL_remove (n->messages_head,
2430 GNUNET_assert (0 == memcmp(&mq->neighbour_id,
2432 sizeof(struct GNUNET_PeerIdentity)));
2435 if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2437 GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2438 n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2440 if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2442 GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2443 n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2445 /* finally, free n itself */
2451 * We have received a PING message from someone. Need to send a PONG message
2452 * in response to the peer by any means necessary.
2454 * FIXME: With something like TCP where a connection exists, we may
2455 * want to send it that way. But the current API does not seem to
2456 * allow us to do so (can't tell this to the transport!)
2459 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2460 const struct GNUNET_PeerIdentity *peer,
2461 const char *sender_address,
2462 size_t sender_address_len)
2464 struct TransportPlugin *plugin = cls;
2465 struct TransportPingMessage *ping;
2466 struct TransportPongMessage *pong;
2468 struct NeighbourList *n;
2469 struct ReadyList *rl;
2470 struct ForeignAddressList *fal;
2472 msize = ntohs (message->size);
2473 if (msize < sizeof (struct TransportPingMessage))
2475 GNUNET_break_op (0);
2476 return GNUNET_SYSERR;
2478 ping = (struct TransportPingMessage *) message;
2479 if (0 != memcmp (&ping->target,
2480 plugin->env.my_identity,
2481 sizeof (struct GNUNET_PeerIdentity)))
2483 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2484 _("Received `%s' message not destined for me!\n"),
2486 return GNUNET_SYSERR;
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2490 "Processing `%s' from `%s'\n",
2492 GNUNET_a2s ((const struct sockaddr *)sender_address,
2493 sender_address_len));
2495 msize -= sizeof (struct TransportPingMessage);
2496 pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2497 pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2498 pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2499 pong->purpose.size =
2500 htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2502 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2503 pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2504 pong->challenge = ping->challenge;
2505 pong->addrlen = htons(sender_address_len);
2506 memcpy(&pong->signer,
2508 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2509 memcpy (&pong[1], sender_address, sender_address_len);
2510 GNUNET_assert (GNUNET_OK ==
2511 GNUNET_CRYPTO_rsa_sign (my_private_key,
2512 &pong->purpose, &pong->signature));
2514 n = find_neighbour(peer);
2516 n = setup_new_neighbour(peer);
2517 /* broadcast 'PONG' to all available addresses */
2521 fal = rl->addresses;
2524 transmit_to_peer(NULL, fal,
2525 TRANSPORT_PONG_PRIORITY,
2526 HELLO_VERIFICATION_TIMEOUT,
2528 ntohs(pong->header.size),
2541 * Function called by the plugin for each received message.
2542 * Update data volumes, possibly notify plugins about
2543 * reducing the rate at which they read from the socket
2544 * and generally forward to our receive callback.
2546 * @param cls the "struct TransportPlugin *" we gave to the plugin
2547 * @param message the message, NULL if peer was disconnected
2548 * @param distance the transport cost to this peer (not latency!)
2549 * @param sender_address the address that the sender reported
2550 * (opaque to transport service)
2551 * @param sender_address_len the length of the sender address
2552 * @param peer (claimed) identity of the other peer
2553 * @return the new service_context that the plugin should use
2554 * for future receive calls for messages from this
2559 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2560 const struct GNUNET_MessageHeader *message,
2561 unsigned int distance, const char *sender_address,
2562 size_t sender_address_len)
2564 struct ReadyList *service_context;
2565 struct TransportPlugin *plugin = cls;
2566 struct TransportClient *cpos;
2567 struct InboundMessage *im;
2568 struct ForeignAddressList *peer_address;
2570 struct NeighbourList *n;
2572 n = find_neighbour (peer);
2575 if (message == NULL)
2576 return; /* disconnect of peer already marked down */
2577 n = setup_new_neighbour (peer);
2579 service_context = n->plugins;
2580 while ((service_context != NULL) && (plugin != service_context->plugin))
2581 service_context = service_context->next;
2582 GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2583 if (message == NULL)
2586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2587 "Receive failed from `%4s', triggering disconnect\n",
2588 GNUNET_i2s (&n->id));
2590 /* TODO: call stats */
2591 disconnect_neighbour (n, GNUNET_YES);
2594 peer_address = add_peer_address(n,
2597 sender_address_len);
2598 if (peer_address != NULL)
2600 peer_address->distance = distance;
2601 if (peer_address->connected == GNUNET_NO)
2603 peer_address->connected = GNUNET_YES;
2604 peer_address->connect_attempts++;
2606 peer_address->timeout
2608 GNUNET_TIME_relative_to_absolute
2609 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2611 /* update traffic received amount ... */
2612 msize = ntohs (message->size);
2613 n->last_received += msize;
2614 n->distance = distance;
2616 GNUNET_TIME_relative_to_absolute
2617 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2618 GNUNET_SCHEDULER_cancel (sched,
2621 GNUNET_SCHEDULER_add_delayed (sched,
2622 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2623 &neighbour_timeout_task, n);
2625 if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2627 /* dropping message due to frequent inbound volume violations! */
2628 GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2629 GNUNET_ERROR_TYPE_BULK,
2631 ("Dropping incoming message due to repeated bandwidth quota violations (total of %u).\n"), n->quota_violation_count);
2632 /* TODO: call stats */
2635 switch (ntohs (message->type))
2637 case GNUNET_MESSAGE_TYPE_HELLO:
2638 process_hello (plugin, message);
2640 case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2641 handle_ping(plugin, message, peer, sender_address, sender_address_len);
2643 case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2644 handle_pong(plugin, message, peer, sender_address, sender_address_len);
2648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649 "Received message of type %u from `%4s', sending to all clients.\n",
2650 ntohs (message->type), GNUNET_i2s (peer));
2652 /* transmit message to all clients */
2653 im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2654 im->header.size = htons (sizeof (struct InboundMessage) + msize);
2655 im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2656 im->latency = GNUNET_TIME_relative_hton (n->latency);
2658 memcpy (&im[1], message, msize);
2660 while (cpos != NULL)
2662 transmit_to_client (cpos, &im->header, GNUNET_YES);
2671 * Handle START-message. This is the first message sent to us
2672 * by any client which causes us to add it to our list.
2674 * @param cls closure (always NULL)
2675 * @param client identification of the client
2676 * @param message the actual message
2679 handle_start (void *cls,
2680 struct GNUNET_SERVER_Client *client,
2681 const struct GNUNET_MessageHeader *message)
2683 struct TransportClient *c;
2684 struct ConnectInfoMessage cim;
2685 struct NeighbourList *n;
2688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689 "Received `%s' request from client\n", "START");
2694 if (c->client == client)
2696 /* client already on our list! */
2698 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2703 c = GNUNET_malloc (sizeof (struct TransportClient));
2707 if (our_hello != NULL)
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711 "Sending our own `%s' to new client\n", "HELLO");
2713 transmit_to_client (c,
2714 (const struct GNUNET_MessageHeader *) our_hello,
2716 /* tell new client about all existing connections */
2717 cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2718 cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2722 if (GNUNET_YES == n->received_pong)
2725 cim.latency = GNUNET_TIME_relative_hton (n->latency);
2726 cim.distance = htonl (n->distance);
2727 transmit_to_client (c, &cim.header, GNUNET_NO);
2732 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2737 * Handle HELLO-message.
2739 * @param cls closure (always NULL)
2740 * @param client identification of the client
2741 * @param message the actual message
2744 handle_hello (void *cls,
2745 struct GNUNET_SERVER_Client *client,
2746 const struct GNUNET_MessageHeader *message)
2751 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2752 "Received `%s' request from client\n", "HELLO");
2754 ret = process_hello (NULL, message);
2755 GNUNET_SERVER_receive_done (client, ret);
2760 * Handle SEND-message.
2762 * @param cls closure (always NULL)
2763 * @param client identification of the client
2764 * @param message the actual message
2767 handle_send (void *cls,
2768 struct GNUNET_SERVER_Client *client,
2769 const struct GNUNET_MessageHeader *message)
2771 struct TransportClient *tc;
2772 struct NeighbourList *n;
2773 const struct OutboundMessage *obm;
2774 const struct GNUNET_MessageHeader *obmm;
2778 size = ntohs (message->size);
2780 sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2783 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2786 obm = (const struct OutboundMessage *) message;
2788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789 "Received `%s' request from client with target `%4s'\n",
2790 "SEND", GNUNET_i2s (&obm->peer));
2792 obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2793 msize = ntohs (obmm->size);
2794 if (size != msize + sizeof (struct OutboundMessage))
2797 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2800 n = find_neighbour (&obm->peer);
2802 n = setup_new_neighbour (&obm->peer);
2804 while ((tc != NULL) && (tc->client != client))
2808 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809 "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2811 ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2813 transmit_to_peer (tc, NULL, ntohl (obm->priority),
2814 GNUNET_TIME_relative_ntoh (obm->timeout),
2816 ntohs (obmm->size), GNUNET_NO, n);
2817 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2822 * Handle SET_QUOTA-message.
2824 * @param cls closure (always NULL)
2825 * @param client identification of the client
2826 * @param message the actual message
2829 handle_set_quota (void *cls,
2830 struct GNUNET_SERVER_Client *client,
2831 const struct GNUNET_MessageHeader *message)
2833 const struct QuotaSetMessage *qsm =
2834 (const struct QuotaSetMessage *) message;
2835 struct NeighbourList *n;
2836 struct TransportPlugin *p;
2837 struct ReadyList *rl;
2839 n = find_neighbour (&qsm->peer);
2842 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2848 "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
2849 "SET_QUOTA", ntohl(qsm->quota_in), n->quota_in, GNUNET_i2s (&qsm->peer));
2853 if (n->quota_in < ntohl (qsm->quota_in))
2854 n->last_quota_update = GNUNET_TIME_absolute_get ();
2855 n->quota_in = ntohl (qsm->quota_in);
2860 p->api->set_receive_quota (p->api->cls,
2861 &qsm->peer, ntohl (qsm->quota_in));
2864 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2869 transmit_address_to_client (void *cls, const char *address)
2871 struct GNUNET_SERVER_TransmitContext *tc = cls;
2874 if (NULL == address)
2877 slen = strlen (address) + 1;
2878 GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
2879 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2880 if (NULL == address)
2881 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
2886 * Handle AddressLookup-message.
2888 * @param cls closure (always NULL)
2889 * @param client identification of the client
2890 * @param message the actual message
2893 handle_address_lookup (void *cls,
2894 struct GNUNET_SERVER_Client *client,
2895 const struct GNUNET_MessageHeader *message)
2897 const struct AddressLookupMessage *alum;
2898 struct TransportPlugin *lsPlugin;
2899 const char *nameTransport;
2900 const char *address;
2902 struct GNUNET_SERVER_TransmitContext *tc;
2904 size = ntohs (message->size);
2905 if (size < sizeof (struct AddressLookupMessage))
2907 GNUNET_break_op (0);
2908 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2911 alum = (const struct AddressLookupMessage *) message;
2912 uint32_t addressLen = ntohl (alum->addrlen);
2913 if (size <= sizeof (struct AddressLookupMessage) + addressLen)
2915 GNUNET_break_op (0);
2916 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2919 address = (const char *) &alum[1];
2920 nameTransport = (const char *) &address[addressLen];
2922 [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
2924 GNUNET_break_op (0);
2925 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2928 struct GNUNET_TIME_Absolute timeout =
2929 GNUNET_TIME_absolute_ntoh (alum->timeout);
2930 struct GNUNET_TIME_Relative rtimeout =
2931 GNUNET_TIME_absolute_get_remaining (timeout);
2932 lsPlugin = find_transport (nameTransport);
2933 if (NULL == lsPlugin)
2935 tc = GNUNET_SERVER_transmit_context_create (client);
2936 GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
2937 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2938 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2941 tc = GNUNET_SERVER_transmit_context_create (client);
2942 lsPlugin->api->address_pretty_printer (cls, nameTransport,
2943 address, addressLen, GNUNET_YES,
2945 &transmit_address_to_client, tc);
2949 * List of handlers for the messages understood by this
2952 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2953 {&handle_start, NULL,
2954 GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2955 {&handle_hello, NULL,
2956 GNUNET_MESSAGE_TYPE_HELLO, 0},
2957 {&handle_send, NULL,
2958 GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2959 {&handle_set_quota, NULL,
2960 GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2961 {&handle_address_lookup, NULL,
2962 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2969 * Setup the environment for this plugin.
2972 create_environment (struct TransportPlugin *plug)
2974 plug->env.cfg = cfg;
2975 plug->env.sched = sched;
2976 plug->env.my_identity = &my_identity;
2977 plug->env.cls = plug;
2978 plug->env.receive = &plugin_env_receive;
2979 plug->env.notify_address = &plugin_env_notify_address;
2980 plug->env.default_quota_in =
2981 (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2982 plug->env.max_connections = max_connect_per_transport;
2987 * Start the specified transport (load the plugin).
2990 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2992 struct TransportPlugin *plug;
2995 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2996 _("Loading `%s' transport plugin\n"), name);
2997 GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2998 plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2999 create_environment (plug);
3000 plug->short_name = GNUNET_strdup (name);
3001 plug->lib_name = libname;
3002 plug->next = plugins;
3004 plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3005 if (plug->api == NULL)
3007 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3008 _("Failed to load transport plugin for `%s'\n"), name);
3009 GNUNET_free (plug->short_name);
3010 plugins = plug->next;
3011 GNUNET_free (libname);
3018 * Called whenever a client is disconnected. Frees our
3019 * resources associated with that client.
3021 * @param cls closure
3022 * @param client identification of the client
3025 client_disconnect_notification (void *cls,
3026 struct GNUNET_SERVER_Client *client)
3028 struct TransportClient *pos;
3029 struct TransportClient *prev;
3030 struct ClientMessageQueueEntry *mqe;
3035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3036 "Client disconnected, cleaning up.\n");
3040 while ((pos != NULL) && (pos->client != client))
3047 while (NULL != (mqe = pos->message_queue_head))
3049 pos->message_queue_head = mqe->next;
3052 pos->message_queue_head = NULL;
3054 clients = pos->next;
3056 prev->next = pos->next;
3057 if (GNUNET_YES == pos->tcs_pending)
3067 * Iterator to free entries in the validation_map.
3069 * @param cls closure (unused)
3070 * @param key current key code
3071 * @param value value in the hash map (validation to abort)
3072 * @return GNUNET_YES (always)
3075 abort_validation (void *cls,
3076 const GNUNET_HashCode * key,
3079 struct ValidationEntry *va = value;
3081 GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3082 GNUNET_free (va->transport_name);
3089 * Function called when the service shuts down. Unloads our plugins
3090 * and cancels pending validations.
3092 * @param cls closure, unused
3093 * @param tc task context (unused)
3096 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3098 struct TransportPlugin *plug;
3099 struct OwnAddressList *al;
3100 struct CheckHelloValidatedContext *chvc;
3102 while (neighbours != NULL)
3103 disconnect_neighbour (neighbours, GNUNET_NO);
3105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3106 "Transport service is unloading plugins...\n");
3108 while (NULL != (plug = plugins))
3110 plugins = plug->next;
3111 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3112 GNUNET_free (plug->lib_name);
3113 GNUNET_free (plug->short_name);
3114 while (NULL != (al = plug->addresses))
3116 plug->addresses = al->next;
3121 if (my_private_key != NULL)
3122 GNUNET_CRYPTO_rsa_key_free (my_private_key);
3123 GNUNET_free_non_null (our_hello);
3125 /* free 'chvc' data structure */
3126 while (NULL != (chvc = chvc_head))
3128 chvc_head = chvc->next;
3129 GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3134 GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3137 GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3142 * Initiate transport service.
3144 * @param cls closure
3145 * @param s scheduler to use
3146 * @param serv the initialized server
3147 * @param c configuration to use
3151 struct GNUNET_SCHEDULER_Handle *s,
3152 struct GNUNET_SERVER_Handle *serv,
3153 const struct GNUNET_CONFIGURATION_Handle *c)
3158 unsigned long long tneigh;
3163 validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3164 /* parse configuration */
3166 GNUNET_CONFIGURATION_get_value_number (c,
3171 GNUNET_CONFIGURATION_get_value_filename (c,
3173 "HOSTKEY", &keyfile)))
3175 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3177 ("Transport service is lacking key configuration settings. Exiting.\n"));
3178 GNUNET_SCHEDULER_shutdown (s);
3181 max_connect_per_transport = (uint32_t) tneigh;
3182 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3183 GNUNET_free (keyfile);
3184 if (my_private_key == NULL)
3186 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3188 ("Transport service could not access hostkey. Exiting.\n"));
3189 GNUNET_SCHEDULER_shutdown (s);
3192 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3193 GNUNET_CRYPTO_hash (&my_public_key,
3194 sizeof (my_public_key), &my_identity.hashPubKey);
3195 /* setup notification */
3197 GNUNET_SERVER_disconnect_notify (server,
3198 &client_disconnect_notification, NULL);
3199 /* load plugins... */
3202 GNUNET_CONFIGURATION_get_value_string (c,
3203 "TRANSPORT", "PLUGINS", &plugs))
3205 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3206 _("Starting transport plugins `%s'\n"), plugs);
3207 pos = strtok (plugs, " ");
3210 start_transport (server, pos);
3212 pos = strtok (NULL, " ");
3214 GNUNET_free (plugs);
3216 GNUNET_SCHEDULER_add_delayed (sched,
3217 GNUNET_TIME_UNIT_FOREVER_REL,
3218 &shutdown_task, NULL);
3223 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3225 /* process client requests */
3226 GNUNET_SERVER_add_handlers (server, handlers);
3231 * The main function for the transport service.
3233 * @param argc number of arguments from the command line
3234 * @param argv command line arguments
3235 * @return 0 ok, 1 on error
3238 main (int argc, char *const *argv)
3240 return (GNUNET_OK ==
3241 GNUNET_SERVICE_run (argc,
3244 GNUNET_SERVICE_OPTION_NONE,
3245 &run, NULL)) ? 0 : 1;
3248 /* end of gnunet-service-transport.c */