better session selection
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 /**
22  * @file transport/gnunet-service-transport.c
23  * @brief low-level P2P messaging
24  * @author Christian Grothoff
25  *
26  * BUGS:
27  * - bi-directional nature of TCP is not exploited
28  *
29  * NOTE:
30  * - This code uses 'GNUNET_a2s' for debug printing in many places,
31  *   which is technically wrong since it assumes we have IP+Port 
32  *   (v4/v6) addresses.  Once we add transports like http or smtp
33  *   this will have to be changed!
34  */
35 #include "platform.h"
36 #include "gnunet_client_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "gnunet_constants.h"
39 #include "gnunet_getopt_lib.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_os_lib.h"
42 #include "gnunet_peerinfo_service.h"
43 #include "gnunet_plugin_lib.h"
44 #include "gnunet_protocols.h"
45 #include "gnunet_service_lib.h"
46 #include "gnunet_signatures.h"
47 #include "plugin_transport.h"
48 #include "transport.h"
49
50 /**
51  * Should we do some additional checks (to validate behavior
52  * of clients)?
53  */
54 #define EXTRA_CHECKS GNUNET_YES
55
56 /**
57  * How many messages can we have pending for a given client process
58  * before we start to drop incoming messages?  We typically should
59  * have only one client and so this would be the primary buffer for
60  * messages, so the number should be chosen rather generously.
61  *
62  * The expectation here is that most of the time the queue is large
63  * enough so that a drop is virtually never required.
64  */
65 #define MAX_PENDING 128
66
67 /**
68  * How often should we try to reconnect to a peer using a particular
69  * transport plugin before giving up?  Note that the plugin may be
70  * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
71  */
72 #define MAX_CONNECT_RETRY 3
73
74 /**
75  * Limit on the number of ready-to-run tasks when validating 
76  * HELLOs.  If more tasks are ready to run, we will drop 
77  * HELLOs instead of validating them.
78  */
79 #define MAX_HELLO_LOAD 4
80
81 /**
82  * How often must a peer violate bandwidth quotas before we start
83  * to simply drop its messages?
84  */
85 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
86
87 /**
88  * How long until a HELLO verification attempt should time out?
89  * Must be rather small, otherwise a partially successful HELLO
90  * validation (some addresses working) might not be available
91  * before a client's request for a connection fails for good.
92  * Besides, if a single request to an address takes a long time,
93  * then the peer is unlikely worthwhile anyway.
94  */
95 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
96
97 /**
98  * How long will we allow sending of a ping to be delayed?
99  */
100 #define TRANSPORT_DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
101
102 /**
103  * Priority to use for PONG messages.
104  */
105 #define TRANSPORT_PONG_PRIORITY 4
106
107 /**
108  * How often do we re-add (cheaper) plugins to our list of plugins
109  * to try for a given connected peer?
110  */
111 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
112
113 /**
114  * After how long do we expire an address in a HELLO that we just
115  * validated?  This value is also used for our own addresses when we
116  * create a HELLO.
117  */
118 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
119
120
121 /**
122  * How long before an existing address expires should we again try to
123  * validate it?  Must be (significantly) smaller than
124  * HELLO_ADDRESS_EXPIRATION.
125  */
126 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
127
128 /**
129  * Maximum frequency for re-evaluating latencies for all transport addresses.
130  */
131 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
132
133 /**
134  * Maximum frequency for re-evaluating latencies for connected addresses.
135  */
136 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
137
138
139 /**
140  * List of addresses of other peers
141  */
142 struct ForeignAddressList
143 {
144   /**
145    * This is a linked list.
146    */
147   struct ForeignAddressList *next;
148
149   /**
150    * Which ready list does this entry belong to.
151    */
152   struct ReadyList *ready_list;
153
154   /**
155    * How long until we auto-expire this address (unless it is
156    * re-confirmed by the transport)?
157    */
158   struct GNUNET_TIME_Absolute expires;
159
160   /**
161    * Task used to re-validate addresses, updates latencies and
162    * verifies liveness.
163    */
164   GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
165
166   /**
167    * Length of addr.
168    */
169   size_t addrlen;
170
171   /**
172    * The address.
173    */
174   const void *addr;
175
176   /**
177    * What was the last latency observed for this address, plugin and peer?
178    */
179   struct GNUNET_TIME_Relative latency;
180
181   /**
182    * If we did not successfully transmit a message to the given peer
183    * via this connection during the specified time, we should consider
184    * the connection to be dead.  This is used in the case that a TCP
185    * transport simply stalls writing to the stream but does not
186    * formerly get a signal that the other peer died.
187    */
188   struct GNUNET_TIME_Absolute timeout;
189
190   /**
191    * How often have we tried to connect using this plugin?  Used to
192    * discriminate against addresses that do not work well.
193    * FIXME: not yet used, but should be!
194    */
195   unsigned int connect_attempts;
196
197   /**
198    * DV distance to this peer (1 if no DV is used). 
199    * FIXME: need to set this from transport plugins!
200    */
201   uint32_t distance;
202
203   /**
204    * Have we ever estimated the latency of this address?  Used to
205    * ensure that the first time we add an address, we immediately
206    * probe its latency.
207    */
208   int8_t estimated;
209
210   /**
211    * Are we currently connected via this address?  The first time we
212    * successfully transmit or receive data to a peer via a particular
213    * address, we set this to GNUNET_YES.  If we later get an error
214    * (disconnect notification, transmission failure, timeout), we set
215    * it back to GNUNET_NO.  
216    */
217   int8_t connected;
218
219   /**
220    * Is this plugin currently busy transmitting to the specific target?
221    * GNUNET_NO if not (initial, default state is GNUNET_NO).   Internal
222    * messages do not count as 'in transmit'.
223    */
224   int8_t in_transmit;
225
226   /**
227    * Has this address been validated yet?
228    */
229   int8_t validated;
230
231 };
232
233
234 /**
235  * Entry in linked list of network addresses for ourselves.
236  */
237 struct OwnAddressList
238 {
239   /**
240    * This is a linked list.
241    */
242   struct OwnAddressList *next;
243
244   /**
245    * The address, actually a pointer to the end
246    * of this struct.  Do not free!
247    */
248   const void *addr;
249   
250   /**
251    * How long until we auto-expire this address (unless it is
252    * re-confirmed by the transport)?
253    */
254   struct GNUNET_TIME_Absolute expires;
255
256   /**
257    * Length of addr.
258    */
259   size_t addrlen;
260
261 };
262
263
264 /**
265  * Entry in linked list of all of our plugins.
266  */
267 struct TransportPlugin
268 {
269
270   /**
271    * This is a linked list.
272    */
273   struct TransportPlugin *next;
274
275   /**
276    * API of the transport as returned by the plugin's
277    * initialization function.
278    */
279   struct GNUNET_TRANSPORT_PluginFunctions *api;
280
281   /**
282    * Short name for the plugin (i.e. "tcp").
283    */
284   char *short_name;
285
286   /**
287    * Name of the library (i.e. "gnunet_plugin_transport_tcp").
288    */
289   char *lib_name;
290
291   /**
292    * List of our known addresses for this transport.
293    */
294   struct OwnAddressList *addresses;
295
296   /**
297    * Environment this transport service is using
298    * for this plugin.
299    */
300   struct GNUNET_TRANSPORT_PluginEnvironment env;
301
302   /**
303    * ID of task that is used to clean up expired addresses.
304    */
305   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
306
307   /**
308    * Set to GNUNET_YES if we need to scrap the existing list of
309    * "addresses" and start fresh when we receive the next address
310    * update from a transport.  Set to GNUNET_NO if we should just add
311    * the new address to the list and wait for the commit call.
312    */
313   int rebuild;
314
315 };
316
317 struct NeighbourList;
318
319 /**
320  * For each neighbour we keep a list of messages
321  * that we still want to transmit to the neighbour.
322  */
323 struct MessageQueue
324 {
325
326   /**
327    * This is a doubly linked list.
328    */
329   struct MessageQueue *next;
330
331   /**
332    * This is a doubly linked list.
333    */
334   struct MessageQueue *prev;
335
336   /**
337    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
338    * stuck together in memory.  Allocated at the end of this struct.
339    */
340   const char *message_buf;
341
342   /**
343    * Size of the message buf
344    */
345   size_t message_buf_size;
346
347   /**
348    * Client responsible for queueing the message;
349    * used to check that a client has no two messages
350    * pending for the same target.  Can be NULL.
351    */
352   struct TransportClient *client;
353
354   /**
355    * Using which specific address should we send this message?
356    */
357   struct ForeignAddressList *specific_address;
358
359   /**
360    * Peer ID of the Neighbour this entry belongs to.
361    */
362   struct GNUNET_PeerIdentity neighbour_id;
363
364   /**
365    * Plugin that we used for the transmission.
366    * NULL until we scheduled a transmission.
367    */
368   struct TransportPlugin *plugin;
369
370   /**
371    * At what time should we fail?
372    */
373   struct GNUNET_TIME_Absolute timeout;
374
375   /**
376    * Internal message of the transport system that should not be
377    * included in the usual SEND-SEND_OK transmission confirmation
378    * traffic management scheme.  Typically, "internal_msg" will
379    * be set whenever "client" is NULL (but it is not strictly
380    * required).
381    */
382   int internal_msg;
383
384   /**
385    * How important is the message?
386    */
387   unsigned int priority;
388
389 };
390
391
392 /**
393  * For a given Neighbour, which plugins are available
394  * to talk to this peer and what are their costs?
395  */
396 struct ReadyList
397 {
398   /**
399    * This is a linked list.
400    */
401   struct ReadyList *next;
402
403   /**
404    * Which of our transport plugins does this entry
405    * represent?
406    */
407   struct TransportPlugin *plugin;
408
409   /**
410    * Transport addresses, latency, and readiness for
411    * this particular plugin.
412    */
413   struct ForeignAddressList *addresses;
414
415   /**
416    * To which neighbour does this ready list belong to?
417    */
418   struct NeighbourList *neighbour;
419
420 };
421
422
423 /**
424  * Entry in linked list of all of our current neighbours.
425  */
426 struct NeighbourList
427 {
428
429   /**
430    * This is a linked list.
431    */
432   struct NeighbourList *next;
433
434   /**
435    * Which of our transports is connected to this peer
436    * and what is their status?
437    */
438   struct ReadyList *plugins;
439
440   /**
441    * Head of list of messages we would like to send to this peer;
442    * must contain at most one message per client.
443    */
444   struct MessageQueue *messages_head;
445
446   /**
447    * Tail of list of messages we would like to send to this peer; must
448    * contain at most one message per client.
449    */
450   struct MessageQueue *messages_tail;
451
452   /**
453    * Context for peerinfo iteration.
454    * NULL after we are done processing peerinfo's information.
455    */
456   struct GNUNET_PEERINFO_IteratorContext *piter;
457
458   /**
459    * Public key for this peer.   Valid only if the respective flag is set below.
460    */
461   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
462
463   /**
464    * Identity of this neighbour.
465    */
466   struct GNUNET_PeerIdentity id;
467
468   /**
469    * ID of task scheduled to run when this peer is about to
470    * time out (will free resources associated with the peer).
471    */
472   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
473
474   /**
475    * ID of task scheduled to run when we should retry transmitting
476    * the head of the message queue.  Actually triggered when the
477    * transmission is timing out (we trigger instantly when we have
478    * a chance of success).
479    */
480   GNUNET_SCHEDULER_TaskIdentifier retry_task;
481
482   /**
483    * How long until we should consider this peer dead
484    * (if we don't receive another message in the
485    * meantime)?
486    */
487   struct GNUNET_TIME_Absolute peer_timeout;
488
489   /**
490    * Tracker for inbound bandwidth.
491    */
492   struct GNUNET_BANDWIDTH_Tracker in_tracker;
493
494   /**
495    * The latency we have seen for this particular address for
496    * this particular peer.  This latency may have been calculated
497    * over multiple transports.  This value reflects how long it took
498    * us to receive a response when SENDING via this particular
499    * transport/neighbour/address combination!
500    *
501    * FIXME: we need to periodically send PINGs to update this
502    * latency (at least more often than the current "huge" (11h?)
503    * update interval).
504    */
505   struct GNUNET_TIME_Relative latency;
506
507   /**
508    * How often has the other peer (recently) violated the
509    * inbound traffic limit?  Incremented by 10 per violation,
510    * decremented by 1 per non-violation (for each
511    * time interval).
512    */
513   unsigned int quota_violation_count;
514
515   /**
516    * DV distance to this peer (1 if no DV is used). 
517    */
518   uint32_t distance;
519
520   /**
521    * Have we seen an PONG from this neighbour in the past (and
522    * not had a disconnect since)?
523    */
524   int received_pong;
525
526   /**
527    * Do we have a valid public key for this neighbour?
528    */
529   int public_key_valid;
530
531 };
532
533 /**
534  * Message used to ask a peer to validate receipt (to check an address
535  * from a HELLO).  
536  */
537 struct TransportPingMessage
538 {
539
540   /**
541    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
542    */
543   struct GNUNET_MessageHeader header;
544
545   /**
546    * Random challenge number (in network byte order).
547    */
548   uint32_t challenge GNUNET_PACKED;
549
550   /**
551    * Who is the intended recipient?
552    */
553   struct GNUNET_PeerIdentity target;
554
555 };
556
557
558 /**
559  * Message used to validate a HELLO.  The challenge is included in the
560  * confirmation to make matching of replies to requests possible.  The
561  * signature signs the original challenge number, our public key, the
562  * sender's address (so that the sender can check that the address we
563  * saw is plausible for him and possibly detect a MiM attack) and a
564  * timestamp (to limit replay).<p>
565  *
566  * This message is followed by the address of the
567  * client that we are observing (which is part of what
568  * is being signed).
569  */
570 struct TransportPongMessage
571 {
572
573   /**
574    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
575    */
576   struct GNUNET_MessageHeader header;
577
578   /**
579    * For padding, always zero.
580    */
581   uint32_t reserved GNUNET_PACKED;
582
583   /**
584    * Signature.
585    */
586   struct GNUNET_CRYPTO_RsaSignature signature;
587
588   /**
589    * What are we signing and why?
590    */
591   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
592
593   /**
594    * Random challenge number (in network byte order).
595    */
596   uint32_t challenge GNUNET_PACKED;
597
598   /**
599    * Who signed this message?
600    */
601   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
602
603   /**
604    * Size of address appended to this message
605    */
606   size_t addrlen;
607
608 };
609
610
611 /**
612  * Linked list of messages to be transmitted to the client.  Each
613  * entry is followed by the actual message.
614  */
615 struct ClientMessageQueueEntry
616 {
617   /**
618    * This is a doubly-linked list.
619    */
620   struct ClientMessageQueueEntry *next;
621
622   /**
623    * This is a doubly-linked list.
624    */
625   struct ClientMessageQueueEntry *prev;
626 };
627
628
629 /**
630  * Client connected to the transport service.
631  */
632 struct TransportClient
633 {
634
635   /**
636    * This is a linked list.
637    */
638   struct TransportClient *next;
639
640   /**
641    * Handle to the client.
642    */
643   struct GNUNET_SERVER_Client *client;
644
645   /**
646    * Linked list of messages yet to be transmitted to
647    * the client.
648    */
649   struct ClientMessageQueueEntry *message_queue_head;
650
651   /**
652    * Tail of linked list of messages yet to be transmitted to the
653    * client.
654    */
655   struct ClientMessageQueueEntry *message_queue_tail;
656
657   /**
658    * Current transmit request handle.
659    */ 
660   struct GNUNET_CONNECTION_TransmitHandle *th;
661
662   /**
663    * Is a call to "transmit_send_continuation" pending?  If so, we
664    * must not free this struct (even if the corresponding client
665    * disconnects) and instead only remove it from the linked list and
666    * set the "client" field to NULL.
667    */
668   int tcs_pending;
669
670   /**
671    * Length of the list of messages pending for this client.
672    */
673   unsigned int message_count;
674
675 };
676
677
678 /**
679  * Entry in map of all HELLOs awaiting validation.
680  */
681 struct ValidationEntry
682 {
683
684   /**
685    * The address, actually a pointer to the end
686    * of this struct.  Do not free!
687    */
688   const void *addr;
689
690   /**
691    * Name of the transport.
692    */
693   char *transport_name;
694
695   /**
696    * The public key of the peer.
697    */
698   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
699
700   /**
701    * ID of task that will clean up this entry if we don't succeed
702    * with the validation first.
703    */
704   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
705
706   /**
707    * At what time did we send this validation?
708    */
709   struct GNUNET_TIME_Absolute send_time;
710
711   /**
712    * Length of addr.
713    */
714   size_t addrlen;
715
716   /**
717    * Challenge number we used.
718    */
719   uint32_t challenge;
720
721 };
722
723
724 /**
725  * Context of currently active requests to peerinfo
726  * for validation of HELLOs.
727  */
728 struct CheckHelloValidatedContext
729 {
730
731   /**
732    * This is a doubly-linked list.
733    */
734   struct CheckHelloValidatedContext *next;
735
736   /**
737    * This is a doubly-linked list.
738    */
739   struct CheckHelloValidatedContext *prev;
740
741   /**
742    * Hello that we are validating.
743    */
744   const struct GNUNET_HELLO_Message *hello;
745
746   /**
747    * Context for peerinfo iteration.
748    * NULL after we are done processing peerinfo's information.
749    */
750   struct GNUNET_PEERINFO_IteratorContext *piter;
751   
752   /**
753    * Was a HELLO known for this peer to peerinfo?
754    */
755   int hello_known;
756
757 };
758
759
760 /**
761  * Our HELLO message.
762  */
763 static struct GNUNET_HELLO_Message *our_hello;
764
765 /**
766  * "version" of "our_hello".  Used to see if a given neighbour has
767  * already been sent the latest version of our HELLO message.
768  */
769 static unsigned int our_hello_version;
770
771 /**
772  * Our public key.
773  */
774 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
775
776 /**
777  * Our identity.
778  */
779 static struct GNUNET_PeerIdentity my_identity;
780
781 /**
782  * Our private key.
783  */
784 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
785
786 /**
787  * Our scheduler.
788  */
789 struct GNUNET_SCHEDULER_Handle *sched;
790
791 /**
792  * Our configuration.
793  */
794 const struct GNUNET_CONFIGURATION_Handle *cfg;
795
796 /**
797  * Linked list of all clients to this service.
798  */
799 static struct TransportClient *clients;
800
801 /**
802  * All loaded plugins.
803  */
804 static struct TransportPlugin *plugins;
805
806 /**
807  * Our server.
808  */
809 static struct GNUNET_SERVER_Handle *server;
810
811 /**
812  * All known neighbours and their HELLOs.
813  */
814 static struct NeighbourList *neighbours;
815
816 /**
817  * Number of neighbours we'd like to have.
818  */
819 static uint32_t max_connect_per_transport;
820
821 /**
822  * Head of linked list.
823  */
824 static struct CheckHelloValidatedContext *chvc_head;
825
826 /**
827  * Tail of linked list.
828  */
829 static struct CheckHelloValidatedContext *chvc_tail;
830
831 /**
832  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
833  * of the given peer that we are currently validating).
834  */
835 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
836
837 /**
838  * Handle for reporting statistics.
839  */
840 static struct GNUNET_STATISTICS_Handle *stats;
841
842
843 /**
844  * The peer specified by the given neighbour has timed-out or a plugin
845  * has disconnected.  We may either need to do nothing (other plugins
846  * still up), or trigger a full disconnect and clean up.  This
847  * function updates our state and do the necessary notifications.
848  * Also notifies our clients that the neighbour is now officially
849  * gone.
850  *
851  * @param n the neighbour list entry for the peer
852  * @param check should we just check if all plugins
853  *        disconnected or must we ask all plugins to
854  *        disconnect?
855  */
856 static void disconnect_neighbour (struct NeighbourList *n, int check);
857
858 /**
859  * Check the ready list for the given neighbour and if a plugin is
860  * ready for transmission (and if we have a message), do so!
861  *
862  * @param neighbour target peer for which to transmit
863  */
864 static void try_transmission_to_peer (struct NeighbourList *neighbour);
865
866
867 /**
868  * Find an entry in the neighbour list for a particular peer.
869  *  
870  * @return NULL if not found.
871  */
872 static struct NeighbourList *
873 find_neighbour (const struct GNUNET_PeerIdentity *key)
874 {
875   struct NeighbourList *head = neighbours;
876
877   while ((head != NULL) &&
878         (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
879     head = head->next;
880   return head;
881 }
882
883
884 /**
885  * Find an entry in the transport list for a particular transport.
886  *
887  * @return NULL if not found.
888  */
889 static struct TransportPlugin *
890 find_transport (const char *short_name)
891 {
892   struct TransportPlugin *head = plugins;
893   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
894     head = head->next;
895   return head;
896 }
897
898
899 /**
900  * Function called to notify a client about the socket being ready to
901  * queue more data.  "buf" will be NULL and "size" zero if the socket
902  * was closed for writing in the meantime.
903  *
904  * @param cls closure
905  * @param size number of bytes available in buf
906  * @param buf where the callee should write the message
907  * @return number of bytes written to buf
908  */
909 static size_t
910 transmit_to_client_callback (void *cls, size_t size, void *buf)
911 {
912   struct TransportClient *client = cls;
913   struct ClientMessageQueueEntry *q;
914   uint16_t msize;
915   size_t tsize;
916   const struct GNUNET_MessageHeader *msg;
917   char *cbuf;
918
919   client->th = NULL;
920   if (buf == NULL)
921     {
922       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                   "Transmission to client failed, closing connection.\n");
924       /* fatal error with client, free message queue! */
925       while (NULL != (q = client->message_queue_head))
926         {
927           GNUNET_STATISTICS_update (stats,
928                                     gettext_noop ("# bytes discarded (could not transmit to client)"),
929                                     ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
930                                     GNUNET_NO);      
931           GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
932                                        client->message_queue_tail,
933                                        q);
934           GNUNET_free (q);
935         }
936       client->message_count = 0;
937       return 0;
938     }
939   cbuf = buf;
940   tsize = 0;
941   while (NULL != (q = client->message_queue_head))
942     {
943       msg = (const struct GNUNET_MessageHeader *) &q[1];
944       msize = ntohs (msg->size);
945       if (msize + tsize > size)
946         break;
947 #if DEBUG_TRANSPORT
948       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
949                   "Transmitting message of type %u to client.\n",
950                   ntohs (msg->type));
951 #endif
952       GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
953                                    client->message_queue_tail,
954                                    q);
955       memcpy (&cbuf[tsize], msg, msize);
956       tsize += msize;
957       GNUNET_free (q);
958       client->message_count--;
959     }
960   if (NULL != q)
961     {
962       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
963       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
964                                                         msize,
965                                                         GNUNET_TIME_UNIT_FOREVER_REL,
966                                                         &transmit_to_client_callback,
967                                                         client);
968       GNUNET_assert (client->th != NULL);
969     }
970   return tsize;
971 }
972
973
974 /**
975  * Send the specified message to the specified client.  Since multiple
976  * messages may be pending for the same client at a time, this code
977  * makes sure that no message is lost.
978  *
979  * @param client client to transmit the message to
980  * @param msg the message to send
981  * @param may_drop can this message be dropped if the
982  *        message queue for this client is getting far too large?
983  */
984 static void
985 transmit_to_client (struct TransportClient *client,
986                     const struct GNUNET_MessageHeader *msg, int may_drop)
987 {
988   struct ClientMessageQueueEntry *q;
989   uint16_t msize;
990
991   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
992     {
993       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
994                   _
995                   ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
996                   client->message_count, MAX_PENDING);
997       /* TODO: call to statistics... */
998       return;
999     }
1000   msize = ntohs (msg->size);
1001   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1002   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1003   memcpy (&q[1], msg, msize);
1004   GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1005                                      client->message_queue_tail,
1006                                      client->message_queue_tail,
1007                                      q);                                     
1008   client->message_count++;
1009   if (client->th == NULL)
1010     {
1011       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1012                                                         msize,
1013                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1014                                                         &transmit_to_client_callback,
1015                                                         client);
1016       GNUNET_assert (client->th != NULL);
1017     }
1018 }
1019
1020
1021 /**
1022  * Transmit a 'SEND_OK' notification to the given client for the
1023  * given neighbour.
1024  *
1025  * @param client who to notify
1026  * @param n neighbour to notify about
1027  * @param result status code for the transmission request
1028  */
1029 static void
1030 transmit_send_ok (struct TransportClient *client,
1031                   struct NeighbourList *n,
1032                   int result)
1033 {
1034   struct SendOkMessage send_ok_msg;
1035
1036   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1037   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1038   send_ok_msg.success = htonl (result);
1039   send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1040   send_ok_msg.peer = n->id;
1041   transmit_to_client (client, &send_ok_msg.header, GNUNET_NO); 
1042 }
1043
1044
1045 /**
1046  * Function called by the GNUNET_TRANSPORT_TransmitFunction
1047  * upon "completion" of a send request.  This tells the API
1048  * that it is now legal to send another message to the given
1049  * peer.
1050  *
1051  * @param cls closure, identifies the entry on the
1052  *            message queue that was transmitted and the
1053  *            client responsible for queueing the message
1054  * @param target the peer receiving the message
1055  * @param result GNUNET_OK on success, if the transmission
1056  *           failed, we should not tell the client to transmit
1057  *           more messages
1058  */
1059 static void
1060 transmit_send_continuation (void *cls,
1061                             const struct GNUNET_PeerIdentity *target,
1062                             int result)
1063 {
1064   struct MessageQueue *mq = cls;
1065   struct NeighbourList *n;
1066   
1067   GNUNET_STATISTICS_update (stats,
1068                             gettext_noop ("# bytes pending with plugins"),
1069                             - (int64_t) mq->message_buf_size,
1070                             GNUNET_NO);
1071   if (result == GNUNET_OK)
1072     {
1073       GNUNET_STATISTICS_update (stats,
1074                                 gettext_noop ("# bytes successfully transmitted by plugins"),
1075                                 mq->message_buf_size,
1076                                 GNUNET_NO);      
1077     }
1078   else
1079     {
1080       GNUNET_STATISTICS_update (stats,
1081                                 gettext_noop ("# bytes with transmission failure by plugins"),
1082                                 mq->message_buf_size,
1083                                 GNUNET_NO);      
1084     }  
1085   n = find_neighbour(&mq->neighbour_id);
1086   GNUNET_assert (n != NULL);
1087   if (mq->specific_address != NULL)
1088     {
1089       if (result == GNUNET_OK)    
1090         {
1091           mq->specific_address->timeout =
1092             GNUNET_TIME_relative_to_absolute
1093             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1094           if (mq->specific_address->connected != GNUNET_YES)
1095             {
1096               GNUNET_STATISTICS_update (stats,
1097                                         gettext_noop ("# connected addresses"),
1098                                         1,
1099                                         GNUNET_NO);
1100               mq->specific_address->connected = GNUNET_YES;
1101             }
1102         }    
1103       else
1104         {
1105           if (mq->specific_address->connected != GNUNET_NO)
1106             {
1107               GNUNET_STATISTICS_update (stats,
1108                                         gettext_noop ("# connected addresses"),
1109                                         -1,
1110                                         GNUNET_NO);
1111               mq->specific_address->connected = GNUNET_NO;
1112             }
1113         }    
1114       if (! mq->internal_msg) 
1115         mq->specific_address->in_transmit = GNUNET_NO;
1116     }
1117   if (mq->client != NULL)
1118     transmit_send_ok (mq->client, n, result);
1119   GNUNET_free (mq);
1120   try_transmission_to_peer (n);
1121 }
1122
1123
1124 /**
1125  * Find an address in any of the available transports for
1126  * the given neighbour that would be good for message
1127  * transmission.  This is essentially the transport selection
1128  * routine.
1129  *
1130  * @param neighbour for whom to select an address
1131  * @return selected address, NULL if we have none
1132  */
1133 struct ForeignAddressList *
1134 find_ready_address(struct NeighbourList *neighbour)
1135 {
1136   struct ReadyList *head = neighbour->plugins;
1137   struct ForeignAddressList *addresses;
1138   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1139   struct ForeignAddressList *best_address;
1140
1141   best_address = NULL;
1142   while (head != NULL)
1143     {
1144       addresses = head->addresses;
1145       while (addresses != NULL)
1146         {
1147           if ( (addresses->timeout.value < now.value) && 
1148                (addresses->connected == GNUNET_YES) )
1149             {
1150 #if DEBUG_TRANSPORT
1151               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1152                           "Marking long-time inactive connection to `%4s' as down.\n",
1153                           GNUNET_i2s (&neighbour->id));
1154 #endif
1155               GNUNET_STATISTICS_update (stats,
1156                                         gettext_noop ("# connected addresses"),
1157                                         -1,
1158                                         GNUNET_NO);
1159               addresses->connected = GNUNET_NO;
1160             }
1161           addresses = addresses->next;
1162         }
1163
1164       addresses = head->addresses;
1165       while (addresses != NULL)
1166         {
1167           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1168                       "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1169                       GNUNET_a2s (addresses->addr,
1170                                   addresses->addrlen),
1171                       GNUNET_i2s (&neighbour->id),
1172                       addresses->connected,
1173                       addresses->in_transmit,
1174                       addresses->validated,
1175                       addresses->connect_attempts,
1176                       (unsigned long long) addresses->timeout.value,
1177                       (unsigned int) addresses->distance);
1178           if ( ( (best_address == NULL) || 
1179                  (addresses->connected == GNUNET_YES) ||
1180                  (best_address->connected == GNUNET_NO) ) &&
1181                (addresses->in_transmit == GNUNET_NO) &&
1182                ( (best_address == NULL) || 
1183                  (addresses->latency.value < best_address->latency.value)) )
1184             best_address = addresses;            
1185           /* FIXME: also give lower-latency addresses that are not
1186              connected a chance some times... */
1187           addresses = addresses->next;
1188         }
1189       head = head->next;
1190     }
1191   if (best_address != NULL)
1192     {
1193 #if DEBUG_TRANSPORT
1194       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                   "Best address found has latency of %llu ms.\n",
1196                   best_address->latency.value);
1197 #endif
1198     }
1199   else
1200     {
1201       GNUNET_STATISTICS_update (stats,
1202                                 gettext_noop ("# transmission attempts failed (no address)"),
1203                                 1,
1204                                 GNUNET_NO);
1205     }
1206   return best_address;
1207
1208 }
1209
1210
1211 /**
1212  * We should re-try transmitting to the given peer,
1213  * hopefully we've learned something in the meantime.
1214  */
1215 static void
1216 retry_transmission_task (void *cls,
1217                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1218 {
1219   struct NeighbourList *n = cls;
1220
1221   n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1222   try_transmission_to_peer (n);
1223 }
1224
1225
1226 /**
1227  * Check the ready list for the given neighbour and if a plugin is
1228  * ready for transmission (and if we have a message), do so!
1229  *
1230  * @param neighbour target peer for which to transmit
1231  */
1232 static void
1233 try_transmission_to_peer (struct NeighbourList *neighbour)
1234 {
1235   struct ReadyList *rl;
1236   struct MessageQueue *mq;
1237   struct GNUNET_TIME_Relative timeout;
1238   ssize_t ret;
1239   int force_address;
1240
1241   if (neighbour->messages_head == NULL)
1242     {
1243       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244                   "Transmission queue for `%4s' is empty\n",
1245                   GNUNET_i2s (&neighbour->id));
1246       return;                     /* nothing to do */
1247     }
1248   rl = NULL;
1249   mq = neighbour->messages_head;
1250   /* FIXME: support bi-directional use of TCP */
1251   force_address = GNUNET_YES;
1252   if (mq->specific_address == NULL)
1253     {
1254       mq->specific_address = find_ready_address(neighbour); 
1255       GNUNET_STATISTICS_update (stats,
1256                                 gettext_noop ("# transport selected peer address freely"),
1257                                 1,
1258                                 GNUNET_NO); 
1259       force_address = GNUNET_NO;
1260     }
1261   if (mq->specific_address == NULL)
1262     {
1263       GNUNET_STATISTICS_update (stats,
1264                                 gettext_noop ("# transport failed to selected peer address"),
1265                                 1,
1266                                 GNUNET_NO); 
1267       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1268       if (timeout.value == 0)
1269         {
1270 #if DEBUG_TRANSPORT
1271           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272                       "No destination address available to transmit message of size %u to peer `%4s'\n",
1273                       mq->message_buf_size,
1274                       GNUNET_i2s (&mq->neighbour_id));
1275 #endif
1276           GNUNET_STATISTICS_update (stats,
1277                                     gettext_noop ("# bytes in message queue for other peers"),
1278                                     - (int64_t) mq->message_buf_size,
1279                                     GNUNET_NO);
1280           GNUNET_STATISTICS_update (stats,
1281                                     gettext_noop ("# bytes discarded (no destination address available)"),
1282                                     mq->message_buf_size,
1283                                     GNUNET_NO);      
1284           if (mq->client != NULL)
1285             transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1286           GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1287                                        neighbour->messages_tail,
1288                                        mq);
1289           GNUNET_free (mq);
1290           return;               /* nobody ready */ 
1291         }
1292       GNUNET_STATISTICS_update (stats,
1293                                 gettext_noop ("# message delivery deferred (no address)"),
1294                                 1,
1295                                 GNUNET_NO);
1296       if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1297         GNUNET_SCHEDULER_cancel (sched,
1298                                  neighbour->retry_task);
1299       neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1300                                                             timeout,
1301                                                             &retry_transmission_task,
1302                                                             neighbour);
1303 #if DEBUG_TRANSPORT
1304       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1305                   "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1306                   mq->message_buf_size,
1307                   GNUNET_i2s (&mq->neighbour_id),
1308                   timeout.value);
1309 #endif
1310       /* FIXME: might want to trigger peerinfo lookup here
1311          (unless that's already pending...) */
1312       return;    
1313     }
1314   GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1315                                neighbour->messages_tail,
1316                                mq);
1317   if (mq->specific_address->connected == GNUNET_NO)
1318     mq->specific_address->connect_attempts++;
1319   rl = mq->specific_address->ready_list;
1320   mq->plugin = rl->plugin;
1321   if (!mq->internal_msg)
1322     mq->specific_address->in_transmit = GNUNET_YES;
1323 #if DEBUG_TRANSPORT
1324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1325               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1326               mq->message_buf_size,
1327               GNUNET_i2s (&neighbour->id), 
1328               GNUNET_a2s (mq->specific_address->addr,
1329                           mq->specific_address->addrlen),
1330               rl->plugin->short_name);
1331 #endif
1332   GNUNET_STATISTICS_update (stats,
1333                             gettext_noop ("# bytes in message queue for other peers"),
1334                             - (int64_t) mq->message_buf_size,
1335                             GNUNET_NO);
1336   GNUNET_STATISTICS_update (stats,
1337                             gettext_noop ("# bytes pending with plugins"),
1338                             mq->message_buf_size,
1339                             GNUNET_NO);
1340   ret = rl->plugin->api->send (rl->plugin->api->cls,
1341                                &mq->neighbour_id,
1342                                mq->message_buf,
1343                                mq->message_buf_size,
1344                                mq->priority,
1345                                GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1346                                mq->specific_address->addr,
1347                                mq->specific_address->addrlen,
1348                                force_address,
1349                                &transmit_send_continuation, mq);
1350   if (ret == -1)
1351     {
1352       /* failure, but 'send' would not call continuation in this case,
1353          so we need to do it here! */
1354       transmit_send_continuation (mq, 
1355                                   &mq->neighbour_id,
1356                                   GNUNET_SYSERR);
1357     }
1358 }
1359
1360
1361 /**
1362  * Send the specified message to the specified peer.
1363  *
1364  * @param client source of the transmission request (can be NULL)
1365  * @param peer_address ForeignAddressList where we should send this message
1366  * @param priority how important is the message
1367  * @param timeout how long do we have to transmit?
1368  * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1369  * @param message_buf_size total size of all messages in message_buf
1370  * @param is_internal is this an internal message; these are pre-pended and
1371  *                    also do not count for plugins being "ready" to transmit
1372  * @param neighbour handle to the neighbour for transmission
1373  */
1374 static void
1375 transmit_to_peer (struct TransportClient *client,
1376                   struct ForeignAddressList *peer_address,
1377                   unsigned int priority,
1378                   struct GNUNET_TIME_Relative timeout,
1379                   const char *message_buf,
1380                   size_t message_buf_size,
1381                   int is_internal, struct NeighbourList *neighbour)
1382 {
1383   struct MessageQueue *mq;
1384
1385 #if EXTRA_CHECKS
1386   if (client != NULL)
1387     {
1388       /* check for duplicate submission */
1389       mq = neighbour->messages_head;
1390       while (NULL != mq)
1391         {
1392           if (mq->client == client)
1393             {
1394               /* client transmitted to same peer twice
1395                  before getting SEND_OK! */
1396               GNUNET_break (0);
1397               return;
1398             }
1399           mq = mq->next;
1400         }
1401     }
1402 #endif
1403   GNUNET_STATISTICS_update (stats,
1404                             gettext_noop ("# bytes in message queue for other peers"),
1405                             message_buf_size,
1406                             GNUNET_NO);
1407   mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1408   mq->specific_address = peer_address;
1409   mq->client = client;
1410   memcpy (&mq[1], message_buf, message_buf_size);
1411   mq->message_buf = (const char*) &mq[1];
1412   mq->message_buf_size = message_buf_size;
1413   memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1414   mq->internal_msg = is_internal;
1415   mq->priority = priority;
1416   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1417   if (is_internal)    
1418     GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1419                                  neighbour->messages_tail,
1420                                  mq);
1421   else
1422     GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1423                                        neighbour->messages_tail,
1424                                        neighbour->messages_tail,
1425                                        mq);
1426   try_transmission_to_peer (neighbour);
1427 }
1428
1429
1430 /**
1431  * FIXME: document.
1432  */
1433 struct GeneratorContext
1434 {
1435   struct TransportPlugin *plug_pos;
1436   struct OwnAddressList *addr_pos;
1437   struct GNUNET_TIME_Absolute expiration;
1438 };
1439
1440
1441 /**
1442  * FIXME: document.
1443  */
1444 static size_t
1445 address_generator (void *cls, size_t max, void *buf)
1446 {
1447   struct GeneratorContext *gc = cls;
1448   size_t ret;
1449
1450   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1451     {
1452       gc->plug_pos = gc->plug_pos->next;
1453       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1454     }
1455   if (NULL == gc->plug_pos)
1456     {
1457
1458       return 0;
1459     }
1460   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1461                                   gc->expiration,
1462                                   gc->addr_pos->addr,
1463                                   gc->addr_pos->addrlen, buf, max);
1464   gc->addr_pos = gc->addr_pos->next;
1465   return ret;
1466 }
1467
1468
1469 /**
1470  * Construct our HELLO message from all of the addresses of
1471  * all of the transports.
1472  */
1473 static void
1474 refresh_hello ()
1475 {
1476   struct GNUNET_HELLO_Message *hello;
1477   struct TransportClient *cpos;
1478   struct NeighbourList *npos;
1479   struct GeneratorContext gc;
1480
1481   gc.plug_pos = plugins;
1482   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1483   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1484   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1485 #if DEBUG_TRANSPORT
1486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1487               "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1488 #endif
1489   GNUNET_STATISTICS_update (stats,
1490                             gettext_noop ("# refreshed my HELLO"),
1491                             1,
1492                             GNUNET_NO);
1493   cpos = clients;
1494   while (cpos != NULL)
1495     {
1496       transmit_to_client (cpos,
1497                           (const struct GNUNET_MessageHeader *) hello,
1498                           GNUNET_NO);
1499       cpos = cpos->next;
1500     }
1501
1502   GNUNET_free_non_null (our_hello);
1503   our_hello = hello;
1504   our_hello_version++;
1505   GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1506   npos = neighbours;
1507   while (npos != NULL)
1508     {
1509 #if DEBUG_TRANSPORT
1510       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1511                   "Transmitting updated `%s' to neighbour `%4s'\n",
1512                   "HELLO", GNUNET_i2s (&npos->id));
1513 #endif
1514       GNUNET_STATISTICS_update (stats,
1515                                 gettext_noop ("# transmitted my HELLO to other peers"),
1516                                 1,
1517                                 GNUNET_NO);
1518       transmit_to_peer (NULL, NULL, 0,
1519                         HELLO_ADDRESS_EXPIRATION,
1520                         (const char *) our_hello, 
1521                         GNUNET_HELLO_size(our_hello),
1522                         GNUNET_NO, npos);
1523       npos = npos->next;
1524     }
1525 }
1526
1527
1528 /**
1529  * Task used to clean up expired addresses for a plugin.
1530  *
1531  * @param cls closure
1532  * @param tc context
1533  */
1534 static void
1535 expire_address_task (void *cls,
1536                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1537
1538
1539 /**
1540  * Update the list of addresses for this plugin,
1541  * expiring those that are past their expiration date.
1542  *
1543  * @param plugin addresses of which plugin should be recomputed?
1544  * @param fresh set to GNUNET_YES if a new address was added
1545  *        and we need to regenerate the HELLO even if nobody
1546  *        expired
1547  */
1548 static void
1549 update_addresses (struct TransportPlugin *plugin, int fresh)
1550 {
1551   struct GNUNET_TIME_Relative min_remaining;
1552   struct GNUNET_TIME_Relative remaining;
1553   struct GNUNET_TIME_Absolute now;
1554   struct OwnAddressList *pos;
1555   struct OwnAddressList *prev;
1556   struct OwnAddressList *next;
1557   int expired;
1558
1559   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1560     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1561   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1562   now = GNUNET_TIME_absolute_get ();
1563   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1564   expired = GNUNET_NO;
1565   prev = NULL;
1566   pos = plugin->addresses;
1567   while (pos != NULL)
1568     {
1569       next = pos->next;
1570       if (pos->expires.value < now.value)
1571         {
1572           expired = GNUNET_YES;
1573           if (prev == NULL)
1574             plugin->addresses = pos->next;
1575           else
1576             prev->next = pos->next;
1577
1578           
1579           GNUNET_free (pos);
1580         }
1581       else
1582         {
1583           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1584           if (remaining.value < min_remaining.value)
1585             min_remaining = remaining;
1586           prev = pos;
1587         }
1588       pos = next;
1589     }
1590
1591   if (expired || fresh)
1592     refresh_hello ();
1593   if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1594     plugin->address_update_task
1595       = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1596                                       min_remaining,
1597                                       &expire_address_task, plugin);
1598
1599 }
1600
1601
1602 /**
1603  * Task used to clean up expired addresses for a plugin.
1604  *
1605  * @param cls closure
1606  * @param tc context
1607  */
1608 static void
1609 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1610 {
1611   struct TransportPlugin *plugin = cls;
1612   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1613   update_addresses (plugin, GNUNET_NO);
1614 }
1615
1616
1617 /**
1618  * Function that must be called by each plugin to notify the
1619  * transport service about the addresses under which the transport
1620  * provided by the plugin can be reached.
1621  *
1622  * @param cls closure
1623  * @param name name of the transport that generated the address
1624  * @param addr one of the addresses of the host, NULL for the last address
1625  *        the specific address format depends on the transport
1626  * @param addrlen length of the address
1627  * @param expires when should this address automatically expire?
1628  */
1629 static void
1630 plugin_env_notify_address (void *cls,
1631                            const char *name,
1632                            const void *addr,
1633                            size_t addrlen,
1634                            struct GNUNET_TIME_Relative expires)
1635 {
1636   struct TransportPlugin *p = cls;
1637   struct OwnAddressList *al;
1638   struct GNUNET_TIME_Absolute abex;
1639
1640   abex = GNUNET_TIME_relative_to_absolute (expires);
1641   GNUNET_assert (p == find_transport (name));
1642
1643   al = p->addresses;
1644   while (al != NULL)
1645     {
1646       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1647         {
1648           if (al->expires.value < abex.value)
1649             al->expires = abex;
1650           return;
1651         }
1652       al = al->next;
1653     }
1654
1655   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1656   al->addr = &al[1];
1657   al->next = p->addresses;
1658   p->addresses = al;
1659   al->expires = abex;
1660   al->addrlen = addrlen;
1661   memcpy (&al[1], addr, addrlen);
1662   update_addresses (p, GNUNET_YES);
1663 }
1664
1665
1666 /**
1667  * Notify all of our clients about a peer connecting.
1668  */
1669 static void
1670 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1671                         struct GNUNET_TIME_Relative latency,
1672                         uint32_t distance)
1673 {
1674   struct ConnectInfoMessage cim;
1675   struct TransportClient *cpos;
1676
1677 #if DEBUG_TRANSPORT
1678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1679               "Notifying clients about connection from `%s'\n",
1680               GNUNET_i2s (peer));
1681 #endif
1682   GNUNET_STATISTICS_update (stats,
1683                             gettext_noop ("# peers connected"),
1684                             1,
1685                             GNUNET_NO);
1686   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1687   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1688   cim.distance = htonl (distance);
1689   cim.latency = GNUNET_TIME_relative_hton (latency);
1690   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1691   cpos = clients;
1692   while (cpos != NULL)
1693     {
1694       transmit_to_client (cpos, &cim.header, GNUNET_NO);
1695       cpos = cpos->next;
1696     }
1697 }
1698
1699
1700 /**
1701  * Notify all of our clients about a peer disconnecting.
1702  */
1703 static void
1704 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1705 {
1706   struct DisconnectInfoMessage dim;
1707   struct TransportClient *cpos;
1708
1709 #if DEBUG_TRANSPORT
1710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1711               "Notifying clients about lost connection to `%s'\n",
1712               GNUNET_i2s (peer));
1713 #endif
1714   GNUNET_STATISTICS_update (stats,
1715                             gettext_noop ("# peers connected"),
1716                             -1,
1717                             GNUNET_NO);
1718   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1719   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1720   dim.reserved = htonl (0);
1721   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1722   cpos = clients;
1723   while (cpos != NULL)
1724     {
1725       transmit_to_client (cpos, &dim.header, GNUNET_NO);
1726       cpos = cpos->next;
1727     }
1728 }
1729
1730
1731 /**
1732  * Find a ForeignAddressList entry for the given neighbour
1733  * that matches the given address and transport.
1734  *
1735  * @param neighbour which peer we care about
1736  * @param tname name of the transport plugin
1737  * @param addr binary address
1738  * @param addrlen length of addr
1739  * @return NULL if no such entry exists
1740  */
1741 static struct ForeignAddressList *
1742 find_peer_address(struct NeighbourList *neighbour,
1743                   const char *tname,
1744                   const char *addr,
1745                   size_t addrlen)
1746 {
1747   struct ReadyList *head;
1748   struct ForeignAddressList *address_head;
1749
1750   head = neighbour->plugins;
1751   while (head != NULL)
1752     {
1753       if (0 == strcmp (tname, head->plugin->short_name))
1754         break;
1755       head = head->next;
1756     }
1757   if (head == NULL)
1758     return NULL;
1759
1760   address_head = head->addresses;
1761   while ( (address_head != NULL) &&
1762           ( (address_head->addrlen != addrlen) ||
1763             (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1764     address_head = address_head->next;
1765   return address_head;
1766 }
1767
1768
1769 /**
1770  * Get the peer address struct for the given neighbour and
1771  * address.  If it doesn't yet exist, create it.
1772  *
1773  * @param neighbour which peer we care about
1774  * @param tname name of the transport plugin
1775  * @param addr binary address
1776  * @param addrlen length of addr
1777  * @return NULL if we do not have a transport plugin for 'tname'
1778  */
1779 static struct ForeignAddressList *
1780 add_peer_address (struct NeighbourList *neighbour,
1781                   const char *tname,
1782                   const char *addr, 
1783                   size_t addrlen)
1784 {
1785   struct ReadyList *head;
1786   struct ForeignAddressList *ret;
1787
1788   ret = find_peer_address (neighbour, tname, addr, addrlen);
1789   if (ret != NULL)
1790     return ret;
1791   head = neighbour->plugins;
1792   while (head != NULL)
1793     {
1794       if (0 == strcmp (tname, head->plugin->short_name))
1795         break;
1796       head = head->next;
1797     }
1798   if (head == NULL)
1799     return NULL;
1800   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1801   ret->addr = (const char*) &ret[1];
1802   memcpy (&ret[1], addr, addrlen);
1803   ret->addrlen = addrlen;
1804   ret->expires = GNUNET_TIME_relative_to_absolute
1805     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1806   ret->latency = GNUNET_TIME_relative_get_forever();
1807   ret->distance = -1;
1808   ret->timeout = GNUNET_TIME_relative_to_absolute
1809     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); 
1810   ret->ready_list = head;
1811   ret->next = head->addresses;
1812   head->addresses = ret;
1813   return ret;
1814 }
1815
1816
1817 /**
1818  * Closure for 'add_validated_address'.
1819  */
1820 struct AddValidatedAddressContext
1821 {
1822   /**
1823    * Entry that has been validated.
1824    */
1825   const struct ValidationEntry *ve;
1826
1827   /**
1828    * Flag set after we have added the address so
1829    * that we terminate the iteration next time.
1830    */
1831   int done;
1832 };
1833
1834
1835 /**
1836  * Callback function used to fill a buffer of max bytes with a list of
1837  * addresses in the format used by HELLOs.  Should use
1838  * "GNUNET_HELLO_add_address" as a helper function.
1839  *
1840  * @param cls the 'struct AddValidatedAddressContext' with the validated address
1841  * @param max maximum number of bytes that can be written to buf
1842  * @param buf where to write the address information
1843  * @return number of bytes written, 0 to signal the
1844  *         end of the iteration.
1845  */
1846 static size_t
1847 add_validated_address (void *cls,
1848                        size_t max, void *buf)
1849 {
1850   struct AddValidatedAddressContext *avac = cls;
1851   const struct ValidationEntry *ve = avac->ve;
1852
1853   if (GNUNET_YES == avac->done)
1854     return 0;
1855   avac->done = GNUNET_YES;
1856   return GNUNET_HELLO_add_address (ve->transport_name,
1857                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1858                                    ve->addr,
1859                                    ve->addrlen,
1860                                    buf,
1861                                    max);
1862 }
1863
1864
1865
1866 /**
1867  * Closure for 'check_address_exists'.
1868  */
1869 struct CheckAddressExistsClosure
1870 {
1871   /**
1872    * Address to check for.
1873    */
1874   const void *addr;
1875
1876   /**
1877    * Name of the transport.
1878    */
1879   const char *tname;
1880
1881   /**
1882    * Length of addr.
1883    */
1884   size_t addrlen;
1885
1886   /**
1887    * Set to GNUNET_YES if the address exists.
1888    */
1889   int exists;
1890 };
1891
1892
1893 /**
1894  * Iterator over hash map entries.  Checks if the given
1895  * validation entry is for the same address as what is given
1896  * in the closure.
1897  *
1898  * @param cls the 'struct CheckAddressExistsClosure*'
1899  * @param key current key code (ignored)
1900  * @param value value in the hash map ('struct ValidationEntry')
1901  * @return GNUNET_YES if we should continue to
1902  *         iterate (mismatch), GNUNET_NO if not (entry matched)
1903  */
1904 static int
1905 check_address_exists (void *cls,
1906                       const GNUNET_HashCode * key,
1907                       void *value)
1908 {
1909   struct CheckAddressExistsClosure *caec = cls;
1910   struct ValidationEntry *ve = value;
1911   if ( (0 == strcmp (caec->tname,
1912                      ve->transport_name)) &&
1913        (caec->addrlen == ve->addrlen) &&
1914        (0 == memcmp (caec->addr,
1915                      ve->addr,
1916                      caec->addrlen)) )
1917     {
1918       caec->exists = GNUNET_YES;
1919       return GNUNET_NO;
1920     }
1921   return GNUNET_YES;
1922 }
1923
1924
1925 /**
1926  * HELLO validation cleanup task (validation failed).
1927  *
1928  * @param cls the 'struct ValidationEntry' that failed
1929  * @param tc scheduler context (unused)
1930  */
1931 static void
1932 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1933 {
1934   struct ValidationEntry *va = cls;
1935   struct GNUNET_PeerIdentity pid;
1936
1937   GNUNET_STATISTICS_update (stats,
1938                             gettext_noop ("# address validation timeouts"),
1939                             1,
1940                             GNUNET_NO);
1941   GNUNET_CRYPTO_hash (&va->publicKey,
1942                       sizeof (struct
1943                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1944                       &pid.hashPubKey);
1945   GNUNET_CONTAINER_multihashmap_remove (validation_map,
1946                                         &pid.hashPubKey,
1947                                         va);
1948   GNUNET_free (va->transport_name);
1949   GNUNET_free (va);
1950 }
1951
1952
1953 static void
1954 neighbour_timeout_task (void *cls,
1955                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1956 {
1957   struct NeighbourList *n = cls;
1958
1959 #if DEBUG_TRANSPORT
1960   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1961               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1962 #endif
1963   GNUNET_STATISTICS_update (stats,
1964                             gettext_noop ("# disconnects due to timeout"),
1965                             1,
1966                             GNUNET_NO);
1967   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1968   disconnect_neighbour (n, GNUNET_NO);
1969 }
1970
1971
1972 /**
1973  * Schedule the job that will cause us to send a PING to the
1974  * foreign address to evaluate its validity and latency.
1975  *
1976  * @param fal address to PING
1977  */
1978 static void
1979 schedule_next_ping (struct ForeignAddressList *fal);
1980
1981
1982 /**
1983  * Add the given address to the list of foreign addresses
1984  * available for the given peer (check for duplicates).
1985  *
1986  * @param cls the respective 'struct NeighbourList' to update
1987  * @param tname name of the transport
1988  * @param expiration expiration time
1989  * @param addr the address
1990  * @param addrlen length of the address
1991  * @return GNUNET_OK (always)
1992  */
1993 static int
1994 add_to_foreign_address_list (void *cls,
1995                              const char *tname,
1996                              struct GNUNET_TIME_Absolute expiration,
1997                              const void *addr, size_t addrlen)
1998 {
1999   struct NeighbourList *n = cls;
2000   struct ForeignAddressList *fal;
2001   int try;
2002
2003   GNUNET_STATISTICS_update (stats,
2004                             gettext_noop ("# valid peer addresses returned by peerinfo"),
2005                             1,
2006                             GNUNET_NO);      
2007   try = GNUNET_NO;
2008   fal = find_peer_address (n, tname, addr, addrlen);
2009   if (fal == NULL)
2010     {
2011 #if DEBUG_TRANSPORT
2012       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2013                   "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2014                   GNUNET_a2s (addr, addrlen),
2015                   tname,
2016                   GNUNET_i2s (&n->id),
2017                   expiration.value);
2018 #endif
2019       fal = add_peer_address (n, tname, addr, addrlen);
2020       if (fal == NULL)
2021         {
2022           GNUNET_STATISTICS_update (stats,
2023                                     gettext_noop ("# previously validated addresses lacking transport"),
2024                                     1,
2025                                     GNUNET_NO); 
2026         }
2027       else
2028         {
2029           fal->expires = GNUNET_TIME_absolute_max (expiration,
2030                                                    fal->expires);
2031           schedule_next_ping (fal);
2032         }
2033       try = GNUNET_YES;
2034     }
2035   else
2036     {
2037       fal->expires = GNUNET_TIME_absolute_max (expiration,
2038                                                fal->expires);
2039     }
2040   if (fal == NULL)
2041     {
2042       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2043                   "Failed to add new address for `%4s'\n",
2044                   GNUNET_i2s (&n->id));
2045       return GNUNET_OK;
2046     }
2047   if (fal->validated == GNUNET_NO)
2048     {
2049       fal->validated = GNUNET_YES;  
2050       GNUNET_STATISTICS_update (stats,
2051                                 gettext_noop ("# peer addresses considered valid"),
2052                                 1,
2053                                 GNUNET_NO);      
2054     }
2055   if (try == GNUNET_YES)
2056     {
2057       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2058                   "Have new addresses, will try to trigger transmissions.\n");
2059       try_transmission_to_peer (n);
2060     }
2061   return GNUNET_OK;
2062 }
2063
2064
2065 /**
2066  * Add addresses in validated HELLO "h" to the set of addresses
2067  * we have for this peer.
2068  *
2069  * @param cls closure ('struct NeighbourList*')
2070  * @param peer id of the peer, NULL for last call
2071  * @param h hello message for the peer (can be NULL)
2072  * @param trust amount of trust we have in the peer (not used)
2073  */
2074 static void
2075 add_hello_for_peer (void *cls,
2076                     const struct GNUNET_PeerIdentity *peer,
2077                     const struct GNUNET_HELLO_Message *h, 
2078                     uint32_t trust)
2079 {
2080   struct NeighbourList *n = cls;
2081
2082   if (peer == NULL)
2083     {
2084       n->piter = NULL;
2085       return;
2086     } 
2087   if (h == NULL)
2088     return; /* no HELLO available */
2089 #if DEBUG_TRANSPORT
2090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091               "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2092               "HELLO",
2093               GNUNET_i2s (peer));
2094 #endif
2095   if (GNUNET_YES != n->public_key_valid)
2096     {
2097       GNUNET_HELLO_get_key (h, &n->publicKey);
2098       n->public_key_valid = GNUNET_YES;
2099     }
2100   GNUNET_HELLO_iterate_addresses (h,
2101                                   GNUNET_NO,
2102                                   &add_to_foreign_address_list,
2103                                   n);
2104 }
2105
2106
2107 /**
2108  * Create a fresh entry in our neighbour list for the given peer.
2109  * Will try to transmit our current HELLO to the new neighbour.
2110  *
2111  * @param peer the peer for which we create the entry
2112  * @return the new neighbour list entry
2113  */
2114 static struct NeighbourList *
2115 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2116 {
2117   struct NeighbourList *n;
2118   struct TransportPlugin *tp;
2119   struct ReadyList *rl;
2120
2121   GNUNET_assert (our_hello != NULL);
2122   GNUNET_STATISTICS_update (stats,
2123                             gettext_noop ("# active neighbours"),
2124                             1,
2125                             GNUNET_NO);
2126   n = GNUNET_malloc (sizeof (struct NeighbourList));
2127   n->next = neighbours;
2128   neighbours = n;
2129   n->id = *peer;
2130   n->peer_timeout =
2131     GNUNET_TIME_relative_to_absolute
2132     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2133   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2134                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2135                                  MAX_BANDWIDTH_CARRY_S);
2136   tp = plugins;
2137   while (tp != NULL)
2138     {
2139       if (tp->api->send != NULL)
2140         {
2141           rl = GNUNET_malloc (sizeof (struct ReadyList));
2142           rl->neighbour = n;
2143           rl->next = n->plugins;
2144           n->plugins = rl;
2145           rl->plugin = tp;
2146           rl->addresses = NULL;
2147         }
2148       tp = tp->next;
2149     }
2150   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2151   n->distance = -1;
2152   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2153                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2154                                                   &neighbour_timeout_task, n);
2155   n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2156                                       0, GNUNET_TIME_UNIT_FOREVER_REL,
2157                                       &add_hello_for_peer, n);
2158   transmit_to_peer (NULL, NULL, 0,
2159                     HELLO_ADDRESS_EXPIRATION,
2160                     (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2161                     GNUNET_NO, n);
2162   return n;
2163 }
2164
2165
2166 /**
2167  * Send periodic PING messages to a give foreign address.
2168  *
2169  * @param cls our 'struct PeriodicValidationContext*'
2170  * @param tc task context
2171  */
2172 static void 
2173 send_periodic_ping (void *cls, 
2174                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2175 {
2176   struct ForeignAddressList *peer_address = cls;
2177   struct TransportPlugin *tp;
2178   struct ValidationEntry *va;
2179   struct NeighbourList *neighbour;
2180   struct TransportPingMessage ping;
2181   struct CheckAddressExistsClosure caec;
2182   char * message_buf;
2183   uint16_t hello_size;
2184   size_t tsize;
2185
2186   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2187   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2188     return; 
2189   tp = peer_address->ready_list->plugin;
2190   neighbour = peer_address->ready_list->neighbour;
2191   if (GNUNET_YES != neighbour->public_key_valid)
2192     {
2193       /* no public key yet, try again later */
2194       schedule_next_ping (peer_address);     
2195       return;
2196     }
2197   caec.addr = peer_address->addr;
2198   caec.addrlen = peer_address->addrlen;
2199   caec.tname = tp->short_name;
2200   caec.exists = GNUNET_NO;
2201   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2202                                          &check_address_exists,
2203                                          &caec);
2204   if (caec.exists == GNUNET_YES)
2205     {
2206       /* During validation attempts we will likely trigger the other
2207          peer trying to validate our address which in turn will cause
2208          it to send us its HELLO, so we expect to hit this case rather
2209          frequently.  Only print something if we are very verbose. */
2210 #if DEBUG_TRANSPORT > 1
2211       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2213                   GNUNET_a2s (peer_address->addr,
2214                               peer_address->addrlen),
2215                   tp->short_name,
2216                   GNUNET_i2s (&neighbour->id));
2217 #endif
2218       schedule_next_ping (peer_address);     
2219       return;
2220     }
2221   va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2222   va->transport_name = GNUNET_strdup (tp->short_name);
2223   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2224                                             (unsigned int) -1);
2225   va->send_time = GNUNET_TIME_absolute_get();
2226   va->addr = (const void*) &va[1];
2227   memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2228   va->addrlen = peer_address->addrlen;
2229
2230   memcpy(&va->publicKey,
2231          &neighbour->publicKey, 
2232          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2233
2234   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2235                                                    HELLO_VERIFICATION_TIMEOUT,
2236                                                    &timeout_hello_validation,
2237                                                    va);
2238   GNUNET_CONTAINER_multihashmap_put (validation_map,
2239                                      &neighbour->id.hashPubKey,
2240                                      va,
2241                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2242   hello_size = GNUNET_HELLO_size(our_hello);
2243   tsize = sizeof(struct TransportPingMessage) + hello_size;
2244   message_buf = GNUNET_malloc(tsize);
2245   ping.challenge = htonl(va->challenge);
2246   ping.header.size = htons(sizeof(struct TransportPingMessage));
2247   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2248   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2249   memcpy(message_buf, our_hello, hello_size);
2250   memcpy(&message_buf[hello_size],
2251          &ping,
2252          sizeof(struct TransportPingMessage));
2253 #if DEBUG_TRANSPORT_REVALIDATION
2254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2256               GNUNET_a2s (peer_address->addr,
2257                           peer_address->addrlen),
2258               tp->short_name,
2259               GNUNET_i2s (&neighbour->id),
2260               "HELLO", hello_size,
2261               "PING", sizeof (struct TransportPingMessage));
2262 #endif
2263   GNUNET_STATISTICS_update (stats,
2264                             gettext_noop ("# PING messages sent for re-validation"),
2265                             1,
2266                             GNUNET_NO);
2267   transmit_to_peer (NULL, peer_address,
2268                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2269                     HELLO_VERIFICATION_TIMEOUT,
2270                     message_buf, tsize,
2271                     GNUNET_YES, neighbour);
2272   GNUNET_free(message_buf);
2273   schedule_next_ping (peer_address);
2274 }
2275
2276
2277 /**
2278  * Schedule the job that will cause us to send a PING to the
2279  * foreign address to evaluate its validity and latency.
2280  *
2281  * @param fal address to PING
2282  */
2283 static void
2284 schedule_next_ping (struct ForeignAddressList *fal)
2285 {
2286   struct GNUNET_TIME_Relative delay;
2287
2288   if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2289     return;
2290   delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2291   delay.value /= 2; /* do before expiration */
2292   delay = GNUNET_TIME_relative_min (delay,
2293                                     LATENCY_EVALUATION_MAX_DELAY);
2294   if (GNUNET_YES != fal->estimated)
2295     {
2296       delay = GNUNET_TIME_UNIT_ZERO;
2297       fal->estimated = GNUNET_YES;
2298     }                               
2299   if (GNUNET_YES == fal->connected)
2300     {
2301       delay = GNUNET_TIME_relative_min (delay,
2302                                         CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2303     }  
2304   /* FIXME: also adjust delay based on how close the last
2305      observed latency is to the latency of the best alternative */
2306   /* bound how fast we can go */
2307   delay = GNUNET_TIME_relative_max (delay,
2308                                     GNUNET_TIME_UNIT_SECONDS);
2309   /* randomize a bit (to avoid doing all at the same time) */
2310   delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2311   fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched, 
2312                                                       delay,
2313                                                       &send_periodic_ping, 
2314                                                       fal);
2315 }
2316
2317
2318 /**
2319  * Iterator over hash map entries.  Checks if the given validation
2320  * entry is for the same challenge as what is given in the PONG.
2321  *
2322  * @param cls the 'struct TransportPongMessage*'
2323  * @param key peer identity
2324  * @param value value in the hash map ('struct ValidationEntry')
2325  * @return GNUNET_YES if we should continue to
2326  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2327  */
2328 static int
2329 check_pending_validation (void *cls,
2330                           const GNUNET_HashCode * key,
2331                           void *value)
2332 {
2333   const struct TransportPongMessage *pong = cls;
2334   struct ValidationEntry *ve = value;
2335   struct AddValidatedAddressContext avac;
2336   unsigned int challenge = ntohl(pong->challenge);
2337   struct GNUNET_HELLO_Message *hello;
2338   struct GNUNET_PeerIdentity target;
2339   struct NeighbourList *n;
2340   struct ForeignAddressList *fal;
2341
2342   if (ve->challenge != challenge)
2343     return GNUNET_YES;
2344
2345 #if DEBUG_TRANSPORT
2346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347               "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2348               GNUNET_h2s (key),
2349               GNUNET_a2s ((const struct sockaddr *) ve->addr,
2350                           ve->addrlen),
2351               ve->transport_name);
2352 #endif
2353   GNUNET_STATISTICS_update (stats,
2354                             gettext_noop ("# address validation successes"),
2355                             1,
2356                             GNUNET_NO);
2357   /* create the updated HELLO */
2358   GNUNET_CRYPTO_hash (&ve->publicKey,
2359                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2360                       &target.hashPubKey);
2361   avac.done = GNUNET_NO;
2362   avac.ve = ve;
2363   hello = GNUNET_HELLO_create (&ve->publicKey,
2364                                &add_validated_address,
2365                                &avac);
2366   GNUNET_PEERINFO_add_peer (cfg, sched,
2367                             &target,
2368                             hello);
2369   GNUNET_free (hello);
2370   n = find_neighbour (&target);
2371   if (n != NULL)
2372     {
2373       n->publicKey = ve->publicKey;
2374       n->public_key_valid = GNUNET_YES;
2375       fal = add_peer_address (n,
2376                               ve->transport_name,
2377                               ve->addr,
2378                               ve->addrlen);
2379       GNUNET_assert (fal != NULL);
2380       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2381       fal->validated = GNUNET_YES;
2382       GNUNET_STATISTICS_update (stats,
2383                                 gettext_noop ("# peer addresses considered valid"),
2384                                 1,
2385                                 GNUNET_NO);      
2386       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2387       schedule_next_ping (fal);
2388       if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2389         n->latency = fal->latency;
2390       else
2391         n->latency.value = (fal->latency.value + n->latency.value) / 2;
2392       n->distance = fal->distance;
2393       if (GNUNET_NO == n->received_pong)
2394         {
2395           notify_clients_connect (&target, n->latency, n->distance);
2396           n->received_pong = GNUNET_YES;
2397         }
2398       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2399         {
2400           GNUNET_SCHEDULER_cancel (sched,
2401                                    n->retry_task);
2402           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2403           try_transmission_to_peer (n);
2404         }
2405     }
2406
2407   /* clean up validation entry */
2408   GNUNET_assert (GNUNET_YES ==
2409                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
2410                                                        key,
2411                                                        ve));
2412   GNUNET_SCHEDULER_cancel (sched,
2413                            ve->timeout_task);
2414   GNUNET_free (ve->transport_name);
2415   GNUNET_free (ve);
2416   return GNUNET_NO;
2417 }
2418
2419
2420 /**
2421  * Function that will be called if we receive a validation
2422  * of an address challenge that we transmitted to another
2423  * peer.  Note that the validation should only be considered
2424  * acceptable if the challenge matches AND if the sender
2425  * address is at least a plausible address for this peer
2426  * (otherwise we may be seeing a MiM attack).
2427  *
2428  * @param cls closure
2429  * @param message the pong message
2430  * @param peer who responded to our challenge
2431  * @param sender_address string describing our sender address (as observed
2432  *         by the other peer in binary format)
2433  * @param sender_address_len number of bytes in 'sender_address'
2434  */
2435 static void
2436 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2437              const struct GNUNET_PeerIdentity *peer,
2438              const char *sender_address,
2439              size_t sender_address_len)
2440 {
2441 #if DEBUG_TRANSPORT > 1
2442   /* we get tons of these that just get discarded, only log
2443      if we are quite verbose */
2444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445               "Receiving `%s' message from `%4s'.\n", "PONG",
2446               GNUNET_i2s (peer));
2447 #endif
2448   GNUNET_STATISTICS_update (stats,
2449                             gettext_noop ("# PONG messages received"),
2450                             1,
2451                             GNUNET_NO);
2452   if (GNUNET_SYSERR !=
2453       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2454                                                   &peer->hashPubKey,
2455                                                   &check_pending_validation,
2456                                                   (void*) message))
2457     {
2458       /* This is *expected* to happen a lot since we send
2459          PONGs to *all* known addresses of the sender of
2460          the PING, so most likely we get multiple PONGs
2461          per PING, and all but the first PONG will end up
2462          here. So really we should not print anything here
2463          unless we want to be very, very verbose... */
2464 #if DEBUG_TRANSPORT > 2
2465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2467                   "PONG",
2468                   GNUNET_i2s (peer),
2469                   "PING");
2470 #endif
2471       return;
2472     }
2473
2474 #if 0
2475   /* FIXME: add given address to potential pool of our addresses
2476      (for voting) */
2477   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2478               _("Another peer saw us using the address `%s' via `%s'.\n"),
2479               GNUNET_a2s ((const struct sockaddr *) &pong[1],
2480                           ntohs(pong->addrlen)),
2481               va->transport_name);
2482 #endif
2483 }
2484
2485
2486 /**
2487  * Check if the given address is already being validated; if not,
2488  * append the given address to the list of entries that are being be
2489  * validated and initiate validation.
2490  *
2491  * @param cls closure ('struct CheckHelloValidatedContext *')
2492  * @param tname name of the transport
2493  * @param expiration expiration time
2494  * @param addr the address
2495  * @param addrlen length of the address
2496  * @return GNUNET_OK (always)
2497  */
2498 static int
2499 run_validation (void *cls,
2500                 const char *tname,
2501                 struct GNUNET_TIME_Absolute expiration,
2502                 const void *addr, size_t addrlen)
2503 {
2504   struct CheckHelloValidatedContext *chvc = cls;
2505   struct GNUNET_PeerIdentity id;
2506   struct TransportPlugin *tp;
2507   struct ValidationEntry *va;
2508   struct NeighbourList *neighbour;
2509   struct ForeignAddressList *peer_address;
2510   struct TransportPingMessage ping;
2511   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2512   struct CheckAddressExistsClosure caec;
2513   char * message_buf;
2514   uint16_t hello_size;
2515   size_t tsize;
2516
2517   GNUNET_STATISTICS_update (stats,
2518                             gettext_noop ("# peer addresses scheduled for validation"),
2519                             1,
2520                             GNUNET_NO);      
2521   tp = find_transport (tname);
2522   if (tp == NULL)
2523     {
2524       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2525                   GNUNET_ERROR_TYPE_BULK,
2526                   _
2527                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2528                   tname);
2529       GNUNET_STATISTICS_update (stats,
2530                                 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2531                                 1,
2532                                 GNUNET_NO);      
2533       return GNUNET_OK;
2534     }
2535   GNUNET_HELLO_get_key (chvc->hello, &pk);
2536   GNUNET_CRYPTO_hash (&pk,
2537                       sizeof (struct
2538                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2539                       &id.hashPubKey);
2540   caec.addr = addr;
2541   caec.addrlen = addrlen;
2542   caec.tname = tname;
2543   caec.exists = GNUNET_NO;
2544   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2545                                          &check_address_exists,
2546                                          &caec);
2547   if (caec.exists == GNUNET_YES)
2548     {
2549       /* During validation attempts we will likely trigger the other
2550          peer trying to validate our address which in turn will cause
2551          it to send us its HELLO, so we expect to hit this case rather
2552          frequently.  Only print something if we are very verbose. */
2553 #if DEBUG_TRANSPORT > 1
2554       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2556                   GNUNET_a2s (addr, addrlen),
2557                   tname,
2558                   GNUNET_i2s (&id));
2559 #endif
2560       GNUNET_STATISTICS_update (stats,
2561                                 gettext_noop ("# peer addresses not validated (in progress)"),
2562                                 1,
2563                                 GNUNET_NO);      
2564       return GNUNET_OK;
2565     }
2566   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2567   va->transport_name = GNUNET_strdup (tname);
2568   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2569                                             (unsigned int) -1);
2570   va->send_time = GNUNET_TIME_absolute_get();
2571   va->addr = (const void*) &va[1];
2572   memcpy (&va[1], addr, addrlen);
2573   va->addrlen = addrlen;
2574   GNUNET_HELLO_get_key (chvc->hello,
2575                         &va->publicKey);
2576   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2577                                                    HELLO_VERIFICATION_TIMEOUT,
2578                                                    &timeout_hello_validation,
2579                                                    va);
2580   GNUNET_CONTAINER_multihashmap_put (validation_map,
2581                                      &id.hashPubKey,
2582                                      va,
2583                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2584   neighbour = find_neighbour(&id);
2585   if (neighbour == NULL)
2586     neighbour = setup_new_neighbour(&id);
2587   neighbour->publicKey = va->publicKey;
2588   neighbour->public_key_valid = GNUNET_YES;
2589   peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2590   GNUNET_assert(peer_address != NULL);
2591   hello_size = GNUNET_HELLO_size(our_hello);
2592   tsize = sizeof(struct TransportPingMessage) + hello_size;
2593   message_buf = GNUNET_malloc(tsize);
2594   ping.challenge = htonl(va->challenge);
2595   ping.header.size = htons(sizeof(struct TransportPingMessage));
2596   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2597   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2598   memcpy(message_buf, our_hello, hello_size);
2599   memcpy(&message_buf[hello_size],
2600          &ping,
2601          sizeof(struct TransportPingMessage));
2602 #if DEBUG_TRANSPORT
2603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2604               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2605               GNUNET_a2s (addr, addrlen),
2606               tname,
2607               GNUNET_i2s (&id),
2608               "HELLO", hello_size,
2609               "PING", sizeof (struct TransportPingMessage));
2610 #endif
2611   GNUNET_STATISTICS_update (stats,
2612                             gettext_noop ("# PING messages sent for initial validation"),
2613                             1,
2614                             GNUNET_NO);      
2615   transmit_to_peer (NULL, peer_address,
2616                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2617                     HELLO_VERIFICATION_TIMEOUT,
2618                     message_buf, tsize,
2619                     GNUNET_YES, neighbour);
2620   GNUNET_free(message_buf);
2621   return GNUNET_OK;
2622 }
2623
2624
2625 /**
2626  * Check if addresses in validated hello "h" overlap with
2627  * those in "chvc->hello" and validate the rest.
2628  *
2629  * @param cls closure
2630  * @param peer id of the peer, NULL for last call
2631  * @param h hello message for the peer (can be NULL)
2632  * @param trust amount of trust we have in the peer (not used)
2633  */
2634 static void
2635 check_hello_validated (void *cls,
2636                        const struct GNUNET_PeerIdentity *peer,
2637                        const struct GNUNET_HELLO_Message *h, 
2638                        uint32_t trust)
2639 {
2640   struct CheckHelloValidatedContext *chvc = cls;
2641   struct GNUNET_HELLO_Message *plain_hello;
2642   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2643   struct GNUNET_PeerIdentity target;
2644   struct NeighbourList *n;
2645
2646   if (peer == NULL)
2647     {
2648       chvc->piter = NULL;
2649       GNUNET_CONTAINER_DLL_remove (chvc_head,
2650                                    chvc_tail,
2651                                    chvc);
2652       if (GNUNET_NO == chvc->hello_known)
2653         {
2654           /* notify PEERINFO about the peer now, so that we at least
2655              have the public key if some other component needs it */
2656           GNUNET_HELLO_get_key (chvc->hello, &pk);
2657           GNUNET_CRYPTO_hash (&pk,
2658                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2659                               &target.hashPubKey);
2660           plain_hello = GNUNET_HELLO_create (&pk,
2661                                              NULL, 
2662                                              NULL);
2663           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2664           GNUNET_free (plain_hello);
2665 #if DEBUG_TRANSPORT
2666           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2668                       "HELLO",
2669                       GNUNET_i2s (&target));
2670 #endif
2671           GNUNET_STATISTICS_update (stats,
2672                                     gettext_noop ("# new HELLOs requiring full validation"),
2673                                     1,
2674                                     GNUNET_NO);      
2675           GNUNET_HELLO_iterate_addresses (chvc->hello,
2676                                           GNUNET_NO, 
2677                                           &run_validation, 
2678                                           chvc);
2679         }
2680       else
2681         {
2682           GNUNET_STATISTICS_update (stats,
2683                                     gettext_noop ("# duplicate HELLO (peer known)"),
2684                                     1,
2685                                     GNUNET_NO);      
2686         }
2687       GNUNET_free (chvc);
2688       return;
2689     } 
2690   if (h == NULL)
2691     return;
2692 #if DEBUG_TRANSPORT
2693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2694               "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2695               "HELLO",
2696               GNUNET_i2s (peer));
2697 #endif
2698   chvc->hello_known = GNUNET_YES;
2699   n = find_neighbour (peer);
2700   if (n != NULL)
2701     {
2702       GNUNET_HELLO_iterate_addresses (h,
2703                                       GNUNET_NO,
2704                                       &add_to_foreign_address_list,
2705                                       n);
2706       try_transmission_to_peer (n);
2707     }
2708   else
2709     {
2710       GNUNET_STATISTICS_update (stats,
2711                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
2712                                 1,
2713                                 GNUNET_NO);      
2714     }
2715   GNUNET_STATISTICS_update (stats,
2716                             gettext_noop ("# HELLO validations (update case)"),
2717                             1,
2718                             GNUNET_NO);      
2719   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2720                                       h,
2721                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2722                                       &run_validation, 
2723                                       chvc);
2724 }
2725
2726 /**
2727  * Process HELLO-message.
2728  *
2729  * @param plugin transport involved, may be NULL
2730  * @param message the actual message
2731  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2732  */
2733 static int
2734 process_hello (struct TransportPlugin *plugin,
2735                const struct GNUNET_MessageHeader *message)
2736 {
2737   uint16_t hsize;
2738   struct GNUNET_PeerIdentity target;
2739   const struct GNUNET_HELLO_Message *hello;
2740   struct CheckHelloValidatedContext *chvc;
2741   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2742
2743   hsize = ntohs (message->size);
2744   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2745       (hsize < sizeof (struct GNUNET_MessageHeader)))
2746     {
2747       GNUNET_break (0);
2748       return GNUNET_SYSERR;
2749     }
2750   GNUNET_STATISTICS_update (stats,
2751                             gettext_noop ("# HELLOs received for validation"),
2752                             1,
2753                             GNUNET_NO);      
2754   /* first, check if load is too high */
2755   if (GNUNET_SCHEDULER_get_load (sched,
2756                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2757     {
2758       GNUNET_STATISTICS_update (stats,
2759                                 gettext_noop ("# HELLOs ignored due to high load"),
2760                                 1,
2761                                 GNUNET_NO);      
2762       return GNUNET_OK;
2763     }
2764   hello = (const struct GNUNET_HELLO_Message *) message;
2765   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2766     {
2767       GNUNET_break_op (0);
2768       return GNUNET_SYSERR;
2769     }
2770   GNUNET_CRYPTO_hash (&publicKey,
2771                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2772                       &target.hashPubKey);
2773   if (0 == memcmp (&my_identity,
2774                    &target,
2775                    sizeof (struct GNUNET_PeerIdentity)))
2776     {
2777       GNUNET_STATISTICS_update (stats,
2778                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
2779                                 1,
2780                                 GNUNET_NO);      
2781       return GNUNET_OK;      
2782     }
2783 #if DEBUG_TRANSPORT > 1
2784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2785               "Processing `%s' message for `%4s' of size %u\n",
2786               "HELLO", 
2787               GNUNET_i2s (&target), 
2788               GNUNET_HELLO_size(hello));
2789 #endif
2790   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2791   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2792   memcpy (&chvc[1], hello, hsize);
2793   GNUNET_CONTAINER_DLL_insert (chvc_head,
2794                                chvc_tail,
2795                                chvc);
2796   /* finally, check if HELLO was previously validated
2797      (continuation will then schedule actual validation) */
2798   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2799                                          sched,
2800                                          &target,
2801                                          0,
2802                                          HELLO_VERIFICATION_TIMEOUT,
2803                                          &check_hello_validated, chvc);
2804   return GNUNET_OK;
2805 }
2806
2807
2808 /**
2809  * The peer specified by the given neighbour has timed-out or a plugin
2810  * has disconnected.  We may either need to do nothing (other plugins
2811  * still up), or trigger a full disconnect and clean up.  This
2812  * function updates our state and does the necessary notifications.
2813  * Also notifies our clients that the neighbour is now officially
2814  * gone.
2815  *
2816  * @param n the neighbour list entry for the peer
2817  * @param check should we just check if all plugins
2818  *        disconnected or must we ask all plugins to
2819  *        disconnect?
2820  */
2821 static void
2822 disconnect_neighbour (struct NeighbourList *n, int check)
2823 {
2824   struct ReadyList *rpos;
2825   struct NeighbourList *npos;
2826   struct NeighbourList *nprev;
2827   struct MessageQueue *mq;
2828   struct ForeignAddressList *peer_addresses;
2829   struct ForeignAddressList *peer_pos;
2830
2831   if (GNUNET_YES == check)
2832     {
2833       rpos = n->plugins;
2834       while (NULL != rpos)
2835         {
2836           peer_addresses = rpos->addresses;
2837           while (peer_addresses != NULL)
2838             {
2839               if (GNUNET_YES == peer_addresses->connected)
2840                 return;             /* still connected */
2841               peer_addresses = peer_addresses->next;
2842             }
2843           rpos = rpos->next;
2844         }
2845     }
2846 #if DEBUG_TRANSPORT
2847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2848               "Disconnecting from `%4s'\n",
2849               GNUNET_i2s (&n->id));
2850 #endif
2851   /* remove n from neighbours list */
2852   nprev = NULL;
2853   npos = neighbours;
2854   while ((npos != NULL) && (npos != n))
2855     {
2856       nprev = npos;
2857       npos = npos->next;
2858     }
2859   GNUNET_assert (npos != NULL);
2860   if (nprev == NULL)
2861     neighbours = n->next;
2862   else
2863     nprev->next = n->next;
2864
2865   /* notify all clients about disconnect */
2866   if (GNUNET_YES == n->received_pong)
2867     notify_clients_disconnect (&n->id);
2868
2869   /* clean up all plugins, cancel connections and pending transmissions */
2870   while (NULL != (rpos = n->plugins))
2871     {
2872       n->plugins = rpos->next;
2873       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2874       while (rpos->addresses != NULL)
2875         {
2876           peer_pos = rpos->addresses;
2877           rpos->addresses = peer_pos->next;
2878           if (peer_pos->connected == GNUNET_YES)
2879             GNUNET_STATISTICS_update (stats,
2880                                       gettext_noop ("# connected addresses"),
2881                                       -1,
2882                                       GNUNET_NO); 
2883           if (GNUNET_YES == peer_pos->validated)
2884             GNUNET_STATISTICS_update (stats,
2885                                       gettext_noop ("# peer addresses considered valid"),
2886                                       -1,
2887                                       GNUNET_NO);      
2888           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
2889             {
2890               GNUNET_SCHEDULER_cancel (sched,
2891                                        peer_pos->revalidate_task);
2892               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2893             }
2894           GNUNET_free(peer_pos);
2895         }
2896       GNUNET_free (rpos);
2897     }
2898
2899   /* free all messages on the queue */
2900   while (NULL != (mq = n->messages_head))
2901     {
2902       GNUNET_STATISTICS_update (stats,
2903                                 gettext_noop ("# bytes in message queue for other peers"),
2904                                 - (int64_t) mq->message_buf_size,
2905                                 GNUNET_NO);
2906       GNUNET_STATISTICS_update (stats,
2907                                 gettext_noop ("# bytes discarded due to disconnect"),
2908                                 mq->message_buf_size,
2909                                 GNUNET_NO);
2910       GNUNET_CONTAINER_DLL_remove (n->messages_head,
2911                                    n->messages_tail,
2912                                    mq);
2913       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
2914                                  &n->id,
2915                                  sizeof(struct GNUNET_PeerIdentity)));
2916       GNUNET_free (mq);
2917     }
2918   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2919     {
2920       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2921       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2922     }
2923   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2924     {
2925       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2926       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2927     }
2928   if (n->piter != NULL)
2929     {
2930       GNUNET_PEERINFO_iterate_cancel (n->piter);
2931       n->piter = NULL;
2932     }
2933   /* finally, free n itself */
2934   GNUNET_STATISTICS_update (stats,
2935                             gettext_noop ("# active neighbours"),
2936                             -1,
2937                             GNUNET_NO);
2938   GNUNET_free (n);
2939 }
2940
2941
2942 /**
2943  * We have received a PING message from someone.  Need to send a PONG message
2944  * in response to the peer by any means necessary. 
2945  *
2946  * FIXME: With something like TCP where a connection exists, we may
2947  * want to send it that way.  But the current API does not seem to
2948  * allow us to do so (can't tell this to the transport!)
2949  */
2950 static int 
2951 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2952             const struct GNUNET_PeerIdentity *peer,
2953             const char *sender_address,
2954             size_t sender_address_len)
2955 {
2956   struct TransportPlugin *plugin = cls;
2957   struct TransportPingMessage *ping;
2958   struct TransportPongMessage *pong;
2959   struct NeighbourList *n;
2960   struct ReadyList *rl;
2961   struct ForeignAddressList *fal;
2962
2963   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2964     {
2965       GNUNET_break_op (0);
2966       return GNUNET_SYSERR;
2967     }
2968   ping = (struct TransportPingMessage *) message;
2969   if (0 != memcmp (&ping->target,
2970                    plugin->env.my_identity,
2971                    sizeof (struct GNUNET_PeerIdentity)))
2972     {
2973       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2974                   _("Received `%s' message not destined for me!\n"), 
2975                   "PING");
2976       return GNUNET_SYSERR;
2977     }
2978 #if DEBUG_TRANSPORT
2979   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2980               "Processing `%s' from `%s'\n",
2981               "PING", 
2982               GNUNET_a2s ((const struct sockaddr *)sender_address, 
2983                           sender_address_len));
2984 #endif
2985   GNUNET_STATISTICS_update (stats,
2986                             gettext_noop ("# PING messages received"),
2987                             1,
2988                             GNUNET_NO);
2989   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2990   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2991   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2992   pong->purpose.size =
2993     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2994            sizeof (uint32_t) +
2995            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2996   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2997   pong->challenge = ping->challenge;
2998   pong->addrlen = htons(sender_address_len);
2999   memcpy(&pong->signer, 
3000          &my_public_key, 
3001          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3002   memcpy (&pong[1], sender_address, sender_address_len);
3003   GNUNET_assert (GNUNET_OK ==
3004                  GNUNET_CRYPTO_rsa_sign (my_private_key,
3005                                          &pong->purpose, &pong->signature));
3006
3007   n = find_neighbour(peer);
3008   if (n == NULL)
3009     n = setup_new_neighbour(peer);
3010   /* broadcast 'PONG' to all available addresses */
3011   rl = n->plugins;
3012   while (rl != NULL)
3013     {
3014       fal = rl->addresses;
3015       while (fal != NULL)
3016         {
3017           transmit_to_peer(NULL, fal,
3018                            TRANSPORT_PONG_PRIORITY, 
3019                            HELLO_VERIFICATION_TIMEOUT,
3020                            (const char *)pong, 
3021                            ntohs(pong->header.size), 
3022                            GNUNET_YES, 
3023                            n);
3024           fal = fal->next;
3025         }
3026       rl = rl->next;
3027     }
3028   GNUNET_free(pong);
3029   return GNUNET_OK;
3030 }
3031
3032
3033 /**
3034  * Function called by the plugin for each received message.
3035  * Update data volumes, possibly notify plugins about
3036  * reducing the rate at which they read from the socket
3037  * and generally forward to our receive callback.
3038  *
3039  * @param cls the "struct TransportPlugin *" we gave to the plugin
3040  * @param peer (claimed) identity of the other peer
3041  * @param message the message, NULL if we only care about
3042  *                learning about the delay until we should receive again
3043  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3044  * @param sender_address binary address of the sender (if observed)
3045  * @param sender_address_len number of bytes in sender_address
3046  * @return how long the plugin should wait until receiving more data
3047  *         (plugins that do not support this, can ignore the return value)
3048  */
3049 static struct GNUNET_TIME_Relative
3050 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3051                     const struct GNUNET_MessageHeader *message,
3052                     unsigned int distance, const char *sender_address,
3053                     size_t sender_address_len)
3054 {
3055   struct ReadyList *service_context;
3056   struct TransportPlugin *plugin = cls;
3057   struct TransportClient *cpos;
3058   struct InboundMessage *im;
3059   struct ForeignAddressList *peer_address;
3060   uint16_t msize;
3061   struct NeighbourList *n;
3062   struct GNUNET_TIME_Relative ret;
3063
3064   n = find_neighbour (peer);
3065   if (n == NULL)
3066     n = setup_new_neighbour (peer);    
3067   service_context = n->plugins;
3068   while ((service_context != NULL) && (plugin != service_context->plugin))
3069     service_context = service_context->next;
3070   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3071   if (message != NULL)
3072     {
3073       peer_address = add_peer_address(n, 
3074                                       plugin->short_name,
3075                                       sender_address, 
3076                                       sender_address_len);  
3077       if (peer_address != NULL)
3078         {
3079           peer_address->distance = distance;
3080           if (peer_address->connected == GNUNET_NO)
3081             {
3082               /* FIXME: be careful here to not mark
3083                  MULTIPLE addresses as connected! */
3084               peer_address->connected = GNUNET_YES;
3085               GNUNET_STATISTICS_update (stats,
3086                                         gettext_noop ("# connected addresses"),
3087                                         1,
3088                                         GNUNET_NO);
3089             }
3090           peer_address->timeout
3091             =
3092             GNUNET_TIME_relative_to_absolute
3093             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3094           schedule_next_ping (peer_address);
3095         }
3096       /* update traffic received amount ... */
3097       msize = ntohs (message->size);      
3098       GNUNET_STATISTICS_update (stats,
3099                                 gettext_noop ("# bytes received from other peers"),
3100                                 msize,
3101                                 GNUNET_NO);
3102       n->distance = distance;
3103       n->peer_timeout =
3104         GNUNET_TIME_relative_to_absolute
3105         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3106       GNUNET_SCHEDULER_cancel (sched,
3107                                n->timeout_task);
3108       n->timeout_task =
3109         GNUNET_SCHEDULER_add_delayed (sched,
3110                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3111                                       &neighbour_timeout_task, n);
3112       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3113         {
3114           /* dropping message due to frequent inbound volume violations! */
3115           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3116                       GNUNET_ERROR_TYPE_BULK,
3117                       _
3118                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
3119                       n->in_tracker.available_bytes_per_s__,
3120                       n->quota_violation_count);
3121           GNUNET_STATISTICS_update (stats,
3122                                     gettext_noop ("# bandwidth quota violations by other peers"),
3123                                     1,
3124                                     GNUNET_NO);
3125           return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
3126         }
3127       switch (ntohs (message->type))
3128         {
3129         case GNUNET_MESSAGE_TYPE_HELLO:
3130           GNUNET_STATISTICS_update (stats,
3131                                     gettext_noop ("# HELLO messages received from other peers"),
3132                                     1,
3133                                     GNUNET_NO);
3134           process_hello (plugin, message);
3135           break;
3136         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3137           handle_ping(plugin, message, peer, sender_address, sender_address_len);
3138           break;
3139         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3140           handle_pong(plugin, message, peer, sender_address, sender_address_len);
3141           break;
3142         default:
3143 #if DEBUG_TRANSPORT
3144           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3145                       "Received message of type %u from `%4s', sending to all clients.\n",
3146                       ntohs (message->type), GNUNET_i2s (peer));
3147 #endif
3148           if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3149                                                               msize))
3150             n->quota_violation_count++;
3151           else 
3152             n->quota_violation_count = 0; /* back within limits */
3153           GNUNET_STATISTICS_update (stats,
3154                                     gettext_noop ("# payload received from other peers"),
3155                                     msize,
3156                                     GNUNET_NO);
3157           /* transmit message to all clients */
3158           im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3159           im->header.size = htons (sizeof (struct InboundMessage) + msize);
3160           im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3161           im->latency = GNUNET_TIME_relative_hton (n->latency);
3162           im->peer = *peer;
3163           memcpy (&im[1], message, msize);
3164           cpos = clients;
3165           while (cpos != NULL)
3166             {
3167               transmit_to_client (cpos, &im->header, GNUNET_YES);
3168               cpos = cpos->next;
3169             }
3170           GNUNET_free (im);
3171         }
3172     }  
3173   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3174   if (ret.value > 0)
3175     {
3176       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3177                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3178                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
3179                   (unsigned int) n->in_tracker.available_bytes_per_s__,
3180                   (unsigned long long) ret.value);
3181       GNUNET_STATISTICS_update (stats,
3182                                 gettext_noop ("# ms throttling suggested"),
3183                                 (int64_t) ret.value,
3184                                 GNUNET_NO);      
3185     }
3186   return ret;
3187 }
3188
3189
3190 /**
3191  * Handle START-message.  This is the first message sent to us
3192  * by any client which causes us to add it to our list.
3193  *
3194  * @param cls closure (always NULL)
3195  * @param client identification of the client
3196  * @param message the actual message
3197  */
3198 static void
3199 handle_start (void *cls,
3200               struct GNUNET_SERVER_Client *client,
3201               const struct GNUNET_MessageHeader *message)
3202 {
3203   struct TransportClient *c;
3204   struct ConnectInfoMessage cim;
3205   struct NeighbourList *n;
3206
3207 #if DEBUG_TRANSPORT
3208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3209               "Received `%s' request from client\n", "START");
3210 #endif
3211   c = clients;
3212   while (c != NULL)
3213     {
3214       if (c->client == client)
3215         {
3216           /* client already on our list! */
3217           GNUNET_break (0);
3218           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3219           return;
3220         }
3221       c = c->next;
3222     }
3223   c = GNUNET_malloc (sizeof (struct TransportClient));
3224   c->next = clients;
3225   clients = c;
3226   c->client = client;
3227   if (our_hello != NULL)
3228     {
3229 #if DEBUG_TRANSPORT
3230       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231                   "Sending our own `%s' to new client\n", "HELLO");
3232 #endif
3233       transmit_to_client (c,
3234                           (const struct GNUNET_MessageHeader *) our_hello,
3235                           GNUNET_NO);
3236       /* tell new client about all existing connections */
3237       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3238       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3239       n = neighbours; 
3240       while (n != NULL)
3241         {
3242           if (GNUNET_YES == n->received_pong)
3243             {
3244               cim.id = n->id;
3245               cim.latency = GNUNET_TIME_relative_hton (n->latency);
3246               cim.distance = htonl (n->distance);
3247               transmit_to_client (c, &cim.header, GNUNET_NO);
3248             }
3249             n = n->next;
3250         }
3251     }
3252   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3253 }
3254
3255
3256 /**
3257  * Handle HELLO-message.
3258  *
3259  * @param cls closure (always NULL)
3260  * @param client identification of the client
3261  * @param message the actual message
3262  */
3263 static void
3264 handle_hello (void *cls,
3265               struct GNUNET_SERVER_Client *client,
3266               const struct GNUNET_MessageHeader *message)
3267 {
3268   int ret;
3269
3270   GNUNET_STATISTICS_update (stats,
3271                             gettext_noop ("# HELLOs received from clients"),
3272                             1,
3273                             GNUNET_NO);      
3274   ret = process_hello (NULL, message);
3275   GNUNET_SERVER_receive_done (client, ret);
3276 }
3277
3278
3279 /**
3280  * Handle SEND-message.
3281  *
3282  * @param cls closure (always NULL)
3283  * @param client identification of the client
3284  * @param message the actual message
3285  */
3286 static void
3287 handle_send (void *cls,
3288              struct GNUNET_SERVER_Client *client,
3289              const struct GNUNET_MessageHeader *message)
3290 {
3291   struct TransportClient *tc;
3292   struct NeighbourList *n;
3293   const struct OutboundMessage *obm;
3294   const struct GNUNET_MessageHeader *obmm;
3295   uint16_t size;
3296   uint16_t msize;
3297
3298   size = ntohs (message->size);
3299   if (size <
3300       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3301     {
3302       GNUNET_break (0);
3303       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3304       return;
3305     }
3306   GNUNET_STATISTICS_update (stats,
3307                             gettext_noop ("# payload received for other peers"),
3308                             size,
3309                             GNUNET_NO);      
3310   obm = (const struct OutboundMessage *) message;
3311 #if DEBUG_TRANSPORT
3312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3313               "Received `%s' request from client with target `%4s'\n",
3314               "SEND", GNUNET_i2s (&obm->peer));
3315 #endif
3316   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3317   msize = ntohs (obmm->size);
3318   if (size != msize + sizeof (struct OutboundMessage))
3319     {
3320       GNUNET_break (0);
3321       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3322       return;
3323     }
3324   n = find_neighbour (&obm->peer);
3325   if (n == NULL)
3326     n = setup_new_neighbour (&obm->peer);
3327   tc = clients;
3328   while ((tc != NULL) && (tc->client != client))
3329     tc = tc->next;
3330
3331 #if DEBUG_TRANSPORT
3332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3333               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3334               ntohs (obmm->size),
3335               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3336 #endif
3337   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
3338                     GNUNET_TIME_relative_ntoh (obm->timeout),
3339                     (char *)obmm, 
3340                     ntohs (obmm->size), GNUNET_NO, n);
3341   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3342 }
3343
3344
3345 /**
3346  * Handle SET_QUOTA-message.
3347  *
3348  * @param cls closure (always NULL)
3349  * @param client identification of the client
3350  * @param message the actual message
3351  */
3352 static void
3353 handle_set_quota (void *cls,
3354                   struct GNUNET_SERVER_Client *client,
3355                   const struct GNUNET_MessageHeader *message)
3356 {
3357   const struct QuotaSetMessage *qsm =
3358     (const struct QuotaSetMessage *) message;
3359   struct NeighbourList *n;
3360   
3361   GNUNET_STATISTICS_update (stats,
3362                             gettext_noop ("# SET QUOTA messages received"),
3363                             1,
3364                             GNUNET_NO);      
3365   n = find_neighbour (&qsm->peer);
3366   if (n == NULL)
3367     {
3368       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3369       GNUNET_STATISTICS_update (stats,
3370                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3371                                 1,
3372                                 GNUNET_NO);      
3373       return;
3374     }
3375 #if DEBUG_TRANSPORT
3376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3377               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3378               "SET_QUOTA", 
3379               (unsigned int) ntohl (qsm->quota.value__),
3380               (unsigned int) n->in_tracker.available_bytes_per_s__,
3381               GNUNET_i2s (&qsm->peer));
3382 #endif
3383   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3384                                          qsm->quota);
3385   if (0 == ntohl (qsm->quota.value__)) 
3386     disconnect_neighbour (n, GNUNET_NO);    
3387   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3388 }
3389
3390
3391 /**
3392  * Take the given address and append it to the set of results send back to
3393  * the client.
3394  * 
3395  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3396  * @param address the resolved name, NULL to indicate the last response
3397  */
3398 static void
3399 transmit_address_to_client (void *cls, const char *address)
3400 {
3401   struct GNUNET_SERVER_TransmitContext *tc = cls;
3402   size_t slen;
3403
3404   if (NULL == address)
3405     slen = 0;
3406   else
3407     slen = strlen (address) + 1;
3408   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3409                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3410   if (NULL == address)
3411     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3412 }
3413
3414
3415 /**
3416  * Handle AddressLookup-message.
3417  *
3418  * @param cls closure (always NULL)
3419  * @param client identification of the client
3420  * @param message the actual message
3421  */
3422 static void
3423 handle_address_lookup (void *cls,
3424                        struct GNUNET_SERVER_Client *client,
3425                        const struct GNUNET_MessageHeader *message)
3426 {
3427   const struct AddressLookupMessage *alum;
3428   struct TransportPlugin *lsPlugin;
3429   const char *nameTransport;
3430   const char *address;
3431   uint16_t size;
3432   struct GNUNET_SERVER_TransmitContext *tc;
3433   struct GNUNET_TIME_Absolute timeout;
3434   struct GNUNET_TIME_Relative rtimeout;
3435   int32_t numeric;
3436
3437   size = ntohs (message->size);
3438   if (size < sizeof (struct AddressLookupMessage))
3439     {
3440       GNUNET_break_op (0);
3441       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3442       return;
3443     }
3444   alum = (const struct AddressLookupMessage *) message;
3445   uint32_t addressLen = ntohl (alum->addrlen);
3446   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3447     {
3448       GNUNET_break_op (0);
3449       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3450       return;
3451     }
3452   address = (const char *) &alum[1];
3453   nameTransport = (const char *) &address[addressLen];
3454   if (nameTransport
3455       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3456     {
3457       GNUNET_break_op (0);
3458       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3459       return;
3460     }
3461   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3462   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3463   numeric = ntohl (alum->numeric_only);
3464   lsPlugin = find_transport (nameTransport);
3465   if (NULL == lsPlugin)
3466     {
3467       tc = GNUNET_SERVER_transmit_context_create (client);
3468       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3469                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3470       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3471       return;
3472     }
3473   tc = GNUNET_SERVER_transmit_context_create (client);
3474   lsPlugin->api->address_pretty_printer (cls, nameTransport,
3475                                          address, addressLen, 
3476                                          numeric,
3477                                          rtimeout,
3478                                          &transmit_address_to_client, tc);
3479 }
3480
3481 /**
3482  * List of handlers for the messages understood by this
3483  * service.
3484  */
3485 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3486   {&handle_start, NULL,
3487    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3488   {&handle_hello, NULL,
3489    GNUNET_MESSAGE_TYPE_HELLO, 0},
3490   {&handle_send, NULL,
3491    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3492   {&handle_set_quota, NULL,
3493    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3494   {&handle_address_lookup, NULL,
3495    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3496    0},
3497   {NULL, NULL, 0, 0}
3498 };
3499
3500
3501 /**
3502  * Setup the environment for this plugin.
3503  */
3504 static void
3505 create_environment (struct TransportPlugin *plug)
3506 {
3507   plug->env.cfg = cfg;
3508   plug->env.sched = sched;
3509   plug->env.my_identity = &my_identity;
3510   plug->env.cls = plug;
3511   plug->env.receive = &plugin_env_receive;
3512   plug->env.notify_address = &plugin_env_notify_address;
3513   plug->env.max_connections = max_connect_per_transport;
3514   plug->env.stats = stats;
3515 }
3516
3517
3518 /**
3519  * Start the specified transport (load the plugin).
3520  */
3521 static void
3522 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3523 {
3524   struct TransportPlugin *plug;
3525   char *libname;
3526
3527   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3528               _("Loading `%s' transport plugin\n"), name);
3529   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3530   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3531   create_environment (plug);
3532   plug->short_name = GNUNET_strdup (name);
3533   plug->lib_name = libname;
3534   plug->next = plugins;
3535   plugins = plug;
3536   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3537   if (plug->api == NULL)
3538     {
3539       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3540                   _("Failed to load transport plugin for `%s'\n"), name);
3541       GNUNET_free (plug->short_name);
3542       plugins = plug->next;
3543       GNUNET_free (libname);
3544       GNUNET_free (plug);
3545     }
3546 }
3547
3548
3549 /**
3550  * Called whenever a client is disconnected.  Frees our
3551  * resources associated with that client.
3552  *
3553  * @param cls closure
3554  * @param client identification of the client
3555  */
3556 static void
3557 client_disconnect_notification (void *cls,
3558                                 struct GNUNET_SERVER_Client *client)
3559 {
3560   struct TransportClient *pos;
3561   struct TransportClient *prev;
3562   struct ClientMessageQueueEntry *mqe;
3563
3564   if (client == NULL)
3565     return;
3566 #if DEBUG_TRANSPORT
3567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3568               "Client disconnected, cleaning up.\n");
3569 #endif
3570   prev = NULL;
3571   pos = clients;
3572   while ((pos != NULL) && (pos->client != client))
3573     {
3574       prev = pos;
3575       pos = pos->next;
3576     }
3577   if (pos == NULL)
3578     return;
3579   while (NULL != (mqe = pos->message_queue_head))
3580     {
3581       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3582                                    pos->message_queue_tail,
3583                                    mqe);
3584       pos->message_count--;
3585       GNUNET_free (mqe);
3586     }
3587   if (prev == NULL)
3588     clients = pos->next;
3589   else
3590     prev->next = pos->next;
3591   if (GNUNET_YES == pos->tcs_pending)
3592     {
3593       pos->client = NULL;
3594       return;
3595     }
3596   if (pos->th != NULL)
3597     {
3598       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3599       pos->th = NULL;
3600     }
3601   GNUNET_break (0 == pos->message_count);
3602   GNUNET_free (pos);
3603 }
3604
3605
3606 /**
3607  * Iterator to free entries in the validation_map.
3608  *
3609  * @param cls closure (unused)
3610  * @param key current key code
3611  * @param value value in the hash map (validation to abort)
3612  * @return GNUNET_YES (always)
3613  */
3614 static int 
3615 abort_validation (void *cls,
3616                   const GNUNET_HashCode * key,
3617                   void *value)
3618 {
3619   struct ValidationEntry *va = value;
3620
3621   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3622   GNUNET_free (va->transport_name);
3623   GNUNET_free (va);
3624   return GNUNET_YES;
3625 }
3626
3627
3628 /**
3629  * Function called when the service shuts down.  Unloads our plugins
3630  * and cancels pending validations.
3631  *
3632  * @param cls closure, unused
3633  * @param tc task context (unused)
3634  */
3635 static void
3636 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3637 {
3638   struct TransportPlugin *plug;
3639   struct OwnAddressList *al;
3640   struct CheckHelloValidatedContext *chvc;
3641
3642   while (neighbours != NULL)
3643     disconnect_neighbour (neighbours, GNUNET_NO);
3644 #if DEBUG_TRANSPORT
3645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3646               "Transport service is unloading plugins...\n");
3647 #endif
3648   while (NULL != (plug = plugins))
3649     {
3650       plugins = plug->next;
3651       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3652       GNUNET_free (plug->lib_name);
3653       GNUNET_free (plug->short_name);
3654       while (NULL != (al = plug->addresses))
3655         {
3656           plug->addresses = al->next;
3657           GNUNET_free (al);
3658         }
3659       GNUNET_free (plug);
3660     }
3661   if (my_private_key != NULL)
3662     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3663   GNUNET_free_non_null (our_hello);
3664
3665   /* free 'chvc' data structure */
3666   while (NULL != (chvc = chvc_head))
3667     {
3668       chvc_head = chvc->next;
3669       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3670       GNUNET_free (chvc);
3671     }
3672   chvc_tail = NULL;
3673
3674   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3675                                          &abort_validation,
3676                                          NULL);
3677   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3678   validation_map = NULL;
3679   if (stats != NULL)
3680     {
3681       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3682       stats = NULL;
3683     }
3684 }
3685
3686
3687 /**
3688  * Initiate transport service.
3689  *
3690  * @param cls closure
3691  * @param s scheduler to use
3692  * @param serv the initialized server
3693  * @param c configuration to use
3694  */
3695 static void
3696 run (void *cls,
3697      struct GNUNET_SCHEDULER_Handle *s,
3698      struct GNUNET_SERVER_Handle *serv,
3699      const struct GNUNET_CONFIGURATION_Handle *c)
3700 {
3701   char *plugs;
3702   char *pos;
3703   int no_transports;
3704   unsigned long long tneigh;
3705   char *keyfile;
3706
3707   sched = s;
3708   cfg = c;
3709   stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3710   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3711   /* parse configuration */
3712   if ((GNUNET_OK !=
3713        GNUNET_CONFIGURATION_get_value_number (c,
3714                                               "TRANSPORT",
3715                                               "NEIGHBOUR_LIMIT",
3716                                               &tneigh)) ||
3717       (GNUNET_OK !=
3718        GNUNET_CONFIGURATION_get_value_filename (c,
3719                                                 "GNUNETD",
3720                                                 "HOSTKEY", &keyfile)))
3721     {
3722       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3723                   _
3724                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
3725       GNUNET_SCHEDULER_shutdown (s);
3726       if (stats != NULL)
3727         {
3728           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3729           stats = NULL;
3730         }
3731       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3732       validation_map = NULL;
3733       return;
3734     }
3735   max_connect_per_transport = (uint32_t) tneigh;
3736   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3737   GNUNET_free (keyfile);
3738   if (my_private_key == NULL)
3739     {
3740       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3741                   _
3742                   ("Transport service could not access hostkey.  Exiting.\n"));
3743       GNUNET_SCHEDULER_shutdown (s);
3744       if (stats != NULL)
3745         {
3746           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3747           stats = NULL;
3748         }
3749       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3750       validation_map = NULL;
3751       return;
3752     }
3753   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3754   GNUNET_CRYPTO_hash (&my_public_key,
3755                       sizeof (my_public_key), &my_identity.hashPubKey);
3756   /* setup notification */
3757   server = serv;
3758   GNUNET_SERVER_disconnect_notify (server,
3759                                    &client_disconnect_notification, NULL);
3760   /* load plugins... */
3761   no_transports = 1;
3762   if (GNUNET_OK ==
3763       GNUNET_CONFIGURATION_get_value_string (c,
3764                                              "TRANSPORT", "PLUGINS", &plugs))
3765     {
3766       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3767                   _("Starting transport plugins `%s'\n"), plugs);
3768       pos = strtok (plugs, " ");
3769       while (pos != NULL)
3770         {
3771           start_transport (server, pos);
3772           no_transports = 0;
3773           pos = strtok (NULL, " ");
3774         }
3775       GNUNET_free (plugs);
3776     }
3777   GNUNET_SCHEDULER_add_delayed (sched,
3778                                 GNUNET_TIME_UNIT_FOREVER_REL,
3779                                 &shutdown_task, NULL);
3780   if (no_transports)
3781     refresh_hello ();
3782
3783 #if DEBUG_TRANSPORT
3784   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3785 #endif
3786   /* process client requests */
3787   GNUNET_SERVER_add_handlers (server, handlers);
3788 }
3789
3790
3791 /**
3792  * The main function for the transport service.
3793  *
3794  * @param argc number of arguments from the command line
3795  * @param argv command line arguments
3796  * @return 0 ok, 1 on error
3797  */
3798 int
3799 main (int argc, char *const *argv)
3800 {
3801   return (GNUNET_OK ==
3802           GNUNET_SERVICE_run (argc,
3803                               argv,
3804                               "transport",
3805                               GNUNET_SERVICE_OPTION_NONE,
3806                               &run, NULL)) ? 0 : 1;
3807 }
3808
3809 /* end of gnunet-service-transport.c */