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