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