longer timeout, disconnect on zero quota
[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       GNUNET_assert (fal != NULL);
1794       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1795       fal->validated = GNUNET_YES;
1796       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1797       periodic_validation_context = GNUNET_malloc(sizeof(struct PeriodicValidationContext));
1798       periodic_validation_context->foreign_address = fal;
1799       periodic_validation_context->transport = strdup(ve->transport_name);
1800       memcpy(&periodic_validation_context->publicKey, 
1801              &ve->publicKey, 
1802              sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1803       /* FIXME: this causes all of the revalidation PINGs for the same HELLO
1804          to be transmitted in bulk, which is not nice; also,
1805          triggering these HERE means that revalidations do NOT happen AT ALL
1806          for HELLOs a previous instance of this process validated (since
1807          there is no "initial" validation PING => no revalidation => BUG! */
1808       fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched, 
1809                                                           TRANSPORT_DEFAULT_REVALIDATION, 
1810                                                           &send_periodic_ping, 
1811                                                           periodic_validation_context);
1812       if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1813         n->latency = fal->latency;
1814       else
1815         n->latency.value = (fal->latency.value + n->latency.value) / 2;
1816       n->distance = fal->distance;
1817       if (GNUNET_NO == n->received_pong)
1818         {
1819           notify_clients_connect (&target, n->latency, n->distance);
1820           n->received_pong = GNUNET_YES;
1821         }
1822       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1823         {
1824           GNUNET_SCHEDULER_cancel (sched,
1825                                    n->retry_task);
1826           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1827           try_transmission_to_peer (n);
1828         }
1829     }
1830
1831   /* clean up validation entry */
1832   GNUNET_assert (GNUNET_YES ==
1833                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
1834                                                        key,
1835                                                        ve));
1836   GNUNET_SCHEDULER_cancel (sched,
1837                            ve->timeout_task);
1838   GNUNET_free (ve->transport_name);
1839   GNUNET_free (ve);
1840   return GNUNET_NO;
1841 }
1842
1843
1844 /**
1845  * Function that will be called if we receive a validation
1846  * of an address challenge that we transmitted to another
1847  * peer.  Note that the validation should only be considered
1848  * acceptable if the challenge matches AND if the sender
1849  * address is at least a plausible address for this peer
1850  * (otherwise we may be seeing a MiM attack).
1851  *
1852  * @param cls closure
1853  * @param message the pong message
1854  * @param peer who responded to our challenge
1855  * @param sender_address string describing our sender address (as observed
1856  *         by the other peer in binary format)
1857  * @param sender_address_len number of bytes in 'sender_address'
1858  */
1859 static void
1860 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1861              const struct GNUNET_PeerIdentity *peer,
1862              const char *sender_address,
1863              size_t sender_address_len)
1864 {
1865 #if DEBUG_TRANSPORT > 1
1866   /* we get tons of these that just get discarded, only log
1867      if we are quite verbose */
1868   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1869               "Receiving `%s' message from `%4s'.\n", "PONG",
1870               GNUNET_i2s (peer));
1871 #endif
1872   if (GNUNET_SYSERR !=
1873       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1874                                                   &peer->hashPubKey,
1875                                                   &check_pending_validation,
1876                                                   (void*) message))
1877     {
1878       /* This is *expected* to happen a lot since we send
1879          PONGs to *all* known addresses of the sender of
1880          the PING, so most likely we get multiple PONGs
1881          per PING, and all but the first PONG will end up
1882          here. So really we should not print anything here
1883          unless we want to be very, very verbose... */
1884 #if DEBUG_TRANSPORT > 2
1885       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1886                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1887                   "PONG",
1888                   GNUNET_i2s (peer),
1889                   "PING");
1890 #endif
1891       return;
1892     }
1893
1894 #if 0
1895   /* FIXME: add given address to potential pool of our addresses
1896      (for voting) */
1897   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1898               _("Another peer saw us using the address `%s' via `%s'.\n"),
1899               GNUNET_a2s ((const struct sockaddr *) &pong[1],
1900                           ntohs(pong->addrlen)),
1901               va->transport_name);
1902 #endif
1903 }
1904
1905
1906 static void
1907 neighbour_timeout_task (void *cls,
1908                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1909 {
1910   struct NeighbourList *n = cls;
1911
1912 #if DEBUG_TRANSPORT
1913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1914               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1915 #endif
1916   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1917   disconnect_neighbour (n, GNUNET_NO);
1918 }
1919
1920
1921 /**
1922  * Create a fresh entry in our neighbour list for the given peer.
1923  * Will try to transmit our current HELLO to the new neighbour.  Also
1924  * notifies our clients about the new "connection".
1925  *
1926  * @param peer the peer for which we create the entry
1927  * @return the new neighbour list entry
1928  */
1929 static struct NeighbourList *
1930 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1931 {
1932   struct NeighbourList *n;
1933   struct TransportPlugin *tp;
1934   struct ReadyList *rl;
1935
1936   GNUNET_assert (our_hello != NULL);
1937   n = GNUNET_malloc (sizeof (struct NeighbourList));
1938   n->next = neighbours;
1939   neighbours = n;
1940   n->id = *peer;
1941   n->peer_timeout =
1942     GNUNET_TIME_relative_to_absolute
1943     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1944   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1945                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1946                                  MAX_BANDWIDTH_CARRY_S);
1947   tp = plugins;
1948   while (tp != NULL)
1949     {
1950       if (tp->api->send != NULL)
1951         {
1952           rl = GNUNET_malloc (sizeof (struct ReadyList));
1953           rl->next = n->plugins;
1954           n->plugins = rl;
1955           rl->plugin = tp;
1956           rl->addresses = NULL;
1957         }
1958       tp = tp->next;
1959     }
1960   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1961   n->distance = -1;
1962   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1963                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1964                                                   &neighbour_timeout_task, n);
1965   transmit_to_peer (NULL, NULL, 0,
1966                     HELLO_ADDRESS_EXPIRATION,
1967                     (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1968                     GNUNET_NO, n);
1969   return n;
1970 }
1971
1972
1973 /**
1974  * Closure for 'check_address_exists'.
1975  */
1976 struct CheckAddressExistsClosure
1977 {
1978   /**
1979    * Address to check for.
1980    */
1981   const void *addr;
1982
1983   /**
1984    * Name of the transport.
1985    */
1986   const char *tname;
1987
1988   /**
1989    * Length of addr.
1990    */
1991   size_t addrlen;
1992
1993   /**
1994    * Set to GNUNET_YES if the address exists.
1995    */
1996   int exists;
1997 };
1998
1999
2000 /**
2001  * Iterator over hash map entries.  Checks if the given
2002  * validation entry is for the same address as what is given
2003  * in the closure.
2004  *
2005  * @param cls the 'struct CheckAddressExistsClosure*'
2006  * @param key current key code (ignored)
2007  * @param value value in the hash map ('struct ValidationEntry')
2008  * @return GNUNET_YES if we should continue to
2009  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2010  */
2011 static int
2012 check_address_exists (void *cls,
2013                       const GNUNET_HashCode * key,
2014                       void *value)
2015 {
2016   struct CheckAddressExistsClosure *caec = cls;
2017   struct ValidationEntry *ve = value;
2018   if ( (0 == strcmp (caec->tname,
2019                      ve->transport_name)) &&
2020        (caec->addrlen == ve->addrlen) &&
2021        (0 == memcmp (caec->addr,
2022                      ve->addr,
2023                      caec->addrlen)) )
2024     {
2025       caec->exists = GNUNET_YES;
2026       return GNUNET_NO;
2027     }
2028   return GNUNET_YES;
2029 }
2030
2031
2032 /**
2033  * HELLO validation cleanup task (validation failed).
2034  *
2035  * @param cls the 'struct ValidationEntry' that failed
2036  * @param tc scheduler context (unused)
2037  */
2038 static void
2039 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2040 {
2041   struct ValidationEntry *va = cls;
2042   struct GNUNET_PeerIdentity pid;
2043
2044   GNUNET_CRYPTO_hash (&va->publicKey,
2045                       sizeof (struct
2046                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2047                       &pid.hashPubKey);
2048   GNUNET_CONTAINER_multihashmap_remove (validation_map,
2049                                         &pid.hashPubKey,
2050                                         va);
2051   GNUNET_free (va->transport_name);
2052   GNUNET_free (va);
2053 }
2054
2055
2056 /**
2057  * Check if the given address is already being validated; if not,
2058  * append the given address to the list of entries that are being be
2059  * validated and initiate validation.
2060  *
2061  * @param cls closure ('struct PeriodicValidationContext *')
2062  * @param tname name of the transport
2063  * @param expiration expiration time
2064  * @param addr the address
2065  * @param addrlen length of the address
2066  * @return GNUNET_OK (always)
2067  */
2068 static int
2069 rerun_validation (void *cls,
2070                 const char *tname,
2071                 struct GNUNET_TIME_Absolute expiration,
2072                 const void *addr, size_t addrlen)
2073 {
2074   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey = cls;
2075   struct GNUNET_PeerIdentity id;
2076   struct TransportPlugin *tp;
2077   struct ValidationEntry *va;
2078   struct NeighbourList *neighbour;
2079   struct ForeignAddressList *peer_address;
2080   struct TransportPingMessage ping;
2081   /*struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;*/
2082   struct CheckAddressExistsClosure caec;
2083   char * message_buf;
2084   uint16_t hello_size;
2085   size_t tsize;
2086
2087   tp = find_transport (tname);
2088   if (tp == NULL)
2089     {
2090       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2091                   GNUNET_ERROR_TYPE_BULK,
2092                   _
2093                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2094                   tname);
2095       return GNUNET_OK;
2096     }
2097
2098   GNUNET_CRYPTO_hash (publicKey,
2099                       sizeof (struct
2100                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2101                       &id.hashPubKey);
2102   caec.addr = addr;
2103   caec.addrlen = addrlen;
2104   caec.tname = tname;
2105   caec.exists = GNUNET_NO;
2106   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2107                                          &check_address_exists,
2108                                          &caec);
2109   if (caec.exists == GNUNET_YES)
2110     {
2111       /* During validation attempts we will likely trigger the other
2112          peer trying to validate our address which in turn will cause
2113          it to send us its HELLO, so we expect to hit this case rather
2114          frequently.  Only print something if we are very verbose. */
2115 #if DEBUG_TRANSPORT > 1
2116       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2117                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2118                   GNUNET_a2s (addr, addrlen),
2119                   tname,
2120                   GNUNET_i2s (&id));
2121 #endif
2122       return GNUNET_OK;
2123     }
2124   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2125   va->transport_name = GNUNET_strdup (tname);
2126   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2127                                             (unsigned int) -1);
2128   va->send_time = GNUNET_TIME_absolute_get();
2129   va->addr = (const void*) &va[1];
2130   memcpy (&va[1], addr, addrlen);
2131   va->addrlen = addrlen;
2132   memcpy(&va->publicKey, publicKey, sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2133   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2134                                                    HELLO_VERIFICATION_TIMEOUT,
2135                                                    &timeout_hello_validation,
2136                                                    va);
2137   GNUNET_CONTAINER_multihashmap_put (validation_map,
2138                                      &id.hashPubKey,
2139                                      va,
2140                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2141   neighbour = find_neighbour(&id);
2142   if (neighbour == NULL)
2143     neighbour = setup_new_neighbour(&id);
2144   peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2145   GNUNET_assert(peer_address != NULL);
2146   hello_size = GNUNET_HELLO_size(our_hello);
2147   tsize = sizeof(struct TransportPingMessage) + hello_size;
2148   message_buf = GNUNET_malloc(tsize);
2149   ping.challenge = htonl(va->challenge);
2150   ping.header.size = htons(sizeof(struct TransportPingMessage));
2151   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2152   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2153   memcpy(message_buf, our_hello, hello_size);
2154   memcpy(&message_buf[hello_size],
2155          &ping,
2156          sizeof(struct TransportPingMessage));
2157 #if DEBUG_TRANSPORT_REVALIDATION
2158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2160               GNUNET_a2s (addr, addrlen),
2161               tname,
2162               GNUNET_i2s (&id),
2163               "HELLO", hello_size,
2164               "PING", sizeof (struct TransportPingMessage));
2165 #endif
2166   transmit_to_peer (NULL, peer_address,
2167                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2168                     HELLO_VERIFICATION_TIMEOUT,
2169                     message_buf, tsize,
2170                     GNUNET_YES, neighbour);
2171   GNUNET_free(message_buf);
2172   return GNUNET_OK;
2173 }
2174
2175
2176 /**
2177  * Send periodic ping messages to a give foreign address.
2178  *
2179  * cls closure, can be safely cast to ForeignAddressList
2180  * tc task context
2181  *
2182  * FIXME: Since a _billion_ pongs are sent for every ping,
2183  * maybe this should be a special message type or something
2184  * that gets discarded on the other side instead of initiating
2185  * a flood.
2186  */
2187 static void 
2188 send_periodic_ping (void *cls, 
2189                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2190 {
2191   struct PeriodicValidationContext *periodic_validation_context = cls;
2192
2193   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2194     {
2195       GNUNET_free(periodic_validation_context->transport);
2196       GNUNET_free(periodic_validation_context);
2197       return; /* We have been shutdown, don't do anything! */
2198     }
2199   rerun_validation(&periodic_validation_context->publicKey,
2200                    periodic_validation_context->transport, 
2201                    periodic_validation_context->foreign_address->expires,
2202                    periodic_validation_context->foreign_address->addr, 
2203                    periodic_validation_context->foreign_address->addrlen);
2204   GNUNET_free(periodic_validation_context->transport);
2205   GNUNET_free(periodic_validation_context);
2206 }
2207
2208
2209 /**
2210  * Check if the given address is already being validated; if not,
2211  * append the given address to the list of entries that are being be
2212  * validated and initiate validation.
2213  *
2214  * @param cls closure ('struct CheckHelloValidatedContext *')
2215  * @param tname name of the transport
2216  * @param expiration expiration time
2217  * @param addr the address
2218  * @param addrlen length of the address
2219  * @return GNUNET_OK (always)
2220  */
2221 static int
2222 run_validation (void *cls,
2223                 const char *tname,
2224                 struct GNUNET_TIME_Absolute expiration,
2225                 const void *addr, size_t addrlen)
2226 {
2227   struct CheckHelloValidatedContext *chvc = cls;
2228   struct GNUNET_PeerIdentity id;
2229   struct TransportPlugin *tp;
2230   struct ValidationEntry *va;
2231   struct NeighbourList *neighbour;
2232   struct ForeignAddressList *peer_address;
2233   struct TransportPingMessage ping;
2234   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2235   struct CheckAddressExistsClosure caec;
2236   char * message_buf;
2237   uint16_t hello_size;
2238   size_t tsize;
2239
2240   tp = find_transport (tname);
2241   if (tp == NULL)
2242     {
2243       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2244                   GNUNET_ERROR_TYPE_BULK,
2245                   _
2246                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2247                   tname);
2248       return GNUNET_OK;
2249     }
2250   GNUNET_HELLO_get_key (chvc->hello, &pk);
2251   GNUNET_CRYPTO_hash (&pk,
2252                       sizeof (struct
2253                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2254                       &id.hashPubKey);
2255   caec.addr = addr;
2256   caec.addrlen = addrlen;
2257   caec.tname = tname;
2258   caec.exists = GNUNET_NO;
2259   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2260                                          &check_address_exists,
2261                                          &caec);
2262   if (caec.exists == GNUNET_YES)
2263     {
2264       /* During validation attempts we will likely trigger the other
2265          peer trying to validate our address which in turn will cause
2266          it to send us its HELLO, so we expect to hit this case rather
2267          frequently.  Only print something if we are very verbose. */
2268 #if DEBUG_TRANSPORT > 1
2269       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2270                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2271                   GNUNET_a2s (addr, addrlen),
2272                   tname,
2273                   GNUNET_i2s (&id));
2274 #endif
2275       return GNUNET_OK;
2276     }
2277   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2278   va->transport_name = GNUNET_strdup (tname);
2279   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2280                                             (unsigned int) -1);
2281   va->send_time = GNUNET_TIME_absolute_get();
2282   va->addr = (const void*) &va[1];
2283   memcpy (&va[1], addr, addrlen);
2284   va->addrlen = addrlen;
2285   GNUNET_HELLO_get_key (chvc->hello,
2286                         &va->publicKey);
2287   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2288                                                    HELLO_VERIFICATION_TIMEOUT,
2289                                                    &timeout_hello_validation,
2290                                                    va);
2291   GNUNET_CONTAINER_multihashmap_put (validation_map,
2292                                      &id.hashPubKey,
2293                                      va,
2294                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2295   neighbour = find_neighbour(&id);
2296   if (neighbour == NULL)
2297     neighbour = setup_new_neighbour(&id);
2298   peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2299   GNUNET_assert(peer_address != NULL);
2300   hello_size = GNUNET_HELLO_size(our_hello);
2301   tsize = sizeof(struct TransportPingMessage) + hello_size;
2302   message_buf = GNUNET_malloc(tsize);
2303   ping.challenge = htonl(va->challenge);
2304   ping.header.size = htons(sizeof(struct TransportPingMessage));
2305   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2306   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2307   memcpy(message_buf, our_hello, hello_size);
2308   memcpy(&message_buf[hello_size],
2309          &ping,
2310          sizeof(struct TransportPingMessage));
2311 #if DEBUG_TRANSPORT
2312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2313               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2314               GNUNET_a2s (addr, addrlen),
2315               tname,
2316               GNUNET_i2s (&id),
2317               "HELLO", hello_size,
2318               "PING", sizeof (struct TransportPingMessage));
2319 #endif
2320   transmit_to_peer (NULL, peer_address,
2321                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2322                     HELLO_VERIFICATION_TIMEOUT,
2323                     message_buf, tsize,
2324                     GNUNET_YES, neighbour);
2325   GNUNET_free(message_buf);
2326   return GNUNET_OK;
2327 }
2328
2329
2330 /**
2331  * Add the given address to the list of foreign addresses
2332  * available for the given peer (check for duplicates).
2333  *
2334  * @param cls the respective 'struct NeighbourList' to update
2335  * @param tname name of the transport
2336  * @param expiration expiration time
2337  * @param addr the address
2338  * @param addrlen length of the address
2339  * @return GNUNET_OK (always)
2340  */
2341 static int
2342 add_to_foreign_address_list (void *cls,
2343                              const char *tname,
2344                              struct GNUNET_TIME_Absolute expiration,
2345                              const void *addr, size_t addrlen)
2346 {
2347   struct NeighbourList *n = cls;
2348   struct ForeignAddressList *fal;
2349   int try;
2350
2351   try = GNUNET_NO;
2352   fal = find_peer_address (n, tname, addr, addrlen);
2353   if (fal == NULL)
2354     {
2355 #if DEBUG_TRANSPORT
2356       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357                   "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2358                   GNUNET_a2s (addr, addrlen),
2359                   tname,
2360                   GNUNET_i2s (&n->id),
2361                   expiration.value);
2362 #endif
2363       fal = add_peer_address (n, tname, addr, addrlen);
2364       try = GNUNET_YES;
2365     }
2366   if (fal == NULL)
2367     return GNUNET_OK;
2368   fal->expires = GNUNET_TIME_absolute_max (expiration,
2369                                            fal->expires);
2370   fal->validated = GNUNET_YES;  
2371   if (try == GNUNET_YES)
2372     try_transmission_to_peer (n);
2373   return GNUNET_OK;
2374 }
2375
2376
2377 /**
2378  * Check if addresses in validated hello "h" overlap with
2379  * those in "chvc->hello" and validate the rest.
2380  *
2381  * @param cls closure
2382  * @param peer id of the peer, NULL for last call
2383  * @param h hello message for the peer (can be NULL)
2384  * @param trust amount of trust we have in the peer (not used)
2385  */
2386 static void
2387 check_hello_validated (void *cls,
2388                        const struct GNUNET_PeerIdentity *peer,
2389                        const struct GNUNET_HELLO_Message *h, 
2390                        uint32_t trust)
2391 {
2392   struct CheckHelloValidatedContext *chvc = cls;
2393   struct GNUNET_HELLO_Message *plain_hello;
2394   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2395   struct GNUNET_PeerIdentity target;
2396   struct NeighbourList *n;
2397
2398   if (peer == NULL)
2399     {
2400       chvc->piter = NULL;
2401       GNUNET_CONTAINER_DLL_remove (chvc_head,
2402                                    chvc_tail,
2403                                    chvc);
2404       if (GNUNET_NO == chvc->hello_known)
2405         {
2406           /* notify PEERINFO about the peer now, so that we at least
2407              have the public key if some other component needs it */
2408           GNUNET_HELLO_get_key (chvc->hello, &pk);
2409           GNUNET_CRYPTO_hash (&pk,
2410                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2411                               &target.hashPubKey);
2412           plain_hello = GNUNET_HELLO_create (&pk,
2413                                              NULL, 
2414                                              NULL);
2415           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2416           GNUNET_free (plain_hello);
2417 #if DEBUG_TRANSPORT
2418           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2419                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2420                       "HELLO",
2421                       GNUNET_i2s (&target));
2422 #endif
2423           GNUNET_HELLO_iterate_addresses (chvc->hello,
2424                                           GNUNET_NO, 
2425                                           &run_validation, 
2426                                           chvc);
2427         }
2428       GNUNET_free (chvc);
2429       return;
2430     }
2431   if (h == NULL)
2432     return;
2433   chvc->hello_known = GNUNET_YES;
2434   n = find_neighbour (peer);
2435   if (n != NULL)
2436     {
2437       GNUNET_HELLO_iterate_addresses (h,
2438                                       GNUNET_NO,
2439                                       &add_to_foreign_address_list,
2440                                       n);
2441       try_transmission_to_peer (n);
2442     }
2443   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2444                                       h,
2445                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2446                                       &run_validation, 
2447                                       chvc);
2448 }
2449
2450 /**
2451  * Process HELLO-message.
2452  *
2453  * @param plugin transport involved, may be NULL
2454  * @param message the actual message
2455  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2456  */
2457 static int
2458 process_hello (struct TransportPlugin *plugin,
2459                const struct GNUNET_MessageHeader *message)
2460 {
2461   uint16_t hsize;
2462   struct GNUNET_PeerIdentity target;
2463   const struct GNUNET_HELLO_Message *hello;
2464   struct CheckHelloValidatedContext *chvc;
2465   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2466
2467   hsize = ntohs (message->size);
2468   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2469       (hsize < sizeof (struct GNUNET_MessageHeader)))
2470     {
2471       GNUNET_break (0);
2472       return GNUNET_SYSERR;
2473     }
2474   /* first, check if load is too high */
2475   if (GNUNET_SCHEDULER_get_load (sched,
2476                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2477     {
2478       /* TODO: call to stats? */
2479       return GNUNET_OK;
2480     }
2481   hello = (const struct GNUNET_HELLO_Message *) message;
2482   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2483     {
2484       GNUNET_break_op (0);
2485       return GNUNET_SYSERR;
2486     }
2487   GNUNET_CRYPTO_hash (&publicKey,
2488                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2489                       &target.hashPubKey);
2490 #if DEBUG_TRANSPORT > 1
2491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2492               "Processing `%s' message for `%4s' of size %u\n",
2493               "HELLO", 
2494               GNUNET_i2s (&target), 
2495               GNUNET_HELLO_size(hello));
2496 #endif
2497   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2498   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2499   memcpy (&chvc[1], hello, hsize);
2500   GNUNET_CONTAINER_DLL_insert (chvc_head,
2501                                chvc_tail,
2502                                chvc);
2503   /* finally, check if HELLO was previously validated
2504      (continuation will then schedule actual validation) */
2505   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2506                                          sched,
2507                                          &target,
2508                                          0,
2509                                          HELLO_VERIFICATION_TIMEOUT,
2510                                          &check_hello_validated, chvc);
2511   return GNUNET_OK;
2512 }
2513
2514
2515 /**
2516  * The peer specified by the given neighbour has timed-out or a plugin
2517  * has disconnected.  We may either need to do nothing (other plugins
2518  * still up), or trigger a full disconnect and clean up.  This
2519  * function updates our state and does the necessary notifications.
2520  * Also notifies our clients that the neighbour is now officially
2521  * gone.
2522  *
2523  * @param n the neighbour list entry for the peer
2524  * @param check should we just check if all plugins
2525  *        disconnected or must we ask all plugins to
2526  *        disconnect?
2527  */
2528 static void
2529 disconnect_neighbour (struct NeighbourList *n, int check)
2530 {
2531   struct ReadyList *rpos;
2532   struct NeighbourList *npos;
2533   struct NeighbourList *nprev;
2534   struct MessageQueue *mq;
2535   struct ForeignAddressList *peer_addresses;
2536   struct ForeignAddressList *peer_pos;
2537
2538   if (GNUNET_YES == check)
2539     {
2540       rpos = n->plugins;
2541       while (NULL != rpos)
2542         {
2543           peer_addresses = rpos->addresses;
2544           while (peer_addresses != NULL)
2545             {
2546               if (GNUNET_YES == peer_addresses->connected)
2547                 return;             /* still connected */
2548               peer_addresses = peer_addresses->next;
2549             }
2550           rpos = rpos->next;
2551         }
2552     }
2553 #if DEBUG_TRANSPORT
2554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2555               "Disconnecting from `%4s'\n",
2556               GNUNET_i2s (&n->id));
2557 #endif
2558   /* remove n from neighbours list */
2559   nprev = NULL;
2560   npos = neighbours;
2561   while ((npos != NULL) && (npos != n))
2562     {
2563       nprev = npos;
2564       npos = npos->next;
2565     }
2566   GNUNET_assert (npos != NULL);
2567   if (nprev == NULL)
2568     neighbours = n->next;
2569   else
2570     nprev->next = n->next;
2571
2572   /* notify all clients about disconnect */
2573   if (GNUNET_YES == n->received_pong)
2574     notify_clients_disconnect (&n->id);
2575
2576   /* clean up all plugins, cancel connections and pending transmissions */
2577   while (NULL != (rpos = n->plugins))
2578     {
2579       n->plugins = rpos->next;
2580       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2581
2582       while (rpos->addresses != NULL)
2583         {
2584           peer_pos = rpos->addresses;
2585           rpos->addresses = peer_pos->next;
2586           GNUNET_free(peer_pos);
2587         }
2588       GNUNET_free (rpos);
2589     }
2590
2591   /* free all messages on the queue */
2592   while (NULL != (mq = n->messages_head))
2593     {
2594       GNUNET_CONTAINER_DLL_remove (n->messages_head,
2595                                    n->messages_tail,
2596                                    mq);
2597       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
2598                                  &n->id,
2599                                  sizeof(struct GNUNET_PeerIdentity)));
2600       GNUNET_free (mq);
2601     }
2602   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2603     {
2604       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2605       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2606     }
2607   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2608     {
2609       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2610       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2611     }
2612   /* finally, free n itself */
2613   GNUNET_free (n);
2614 }
2615
2616
2617 /**
2618  * We have received a PING message from someone.  Need to send a PONG message
2619  * in response to the peer by any means necessary. 
2620  *
2621  * FIXME: With something like TCP where a connection exists, we may
2622  * want to send it that way.  But the current API does not seem to
2623  * allow us to do so (can't tell this to the transport!)
2624  */
2625 static int 
2626 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2627             const struct GNUNET_PeerIdentity *peer,
2628             const char *sender_address,
2629             size_t sender_address_len)
2630 {
2631   struct TransportPlugin *plugin = cls;
2632   struct TransportPingMessage *ping;
2633   struct TransportPongMessage *pong;
2634   struct NeighbourList *n;
2635   struct ReadyList *rl;
2636   struct ForeignAddressList *fal;
2637
2638   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2639     {
2640       GNUNET_break_op (0);
2641       return GNUNET_SYSERR;
2642     }
2643   ping = (struct TransportPingMessage *) message;
2644   if (0 != memcmp (&ping->target,
2645                    plugin->env.my_identity,
2646                    sizeof (struct GNUNET_PeerIdentity)))
2647     {
2648       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2649                   _("Received `%s' message not destined for me!\n"), 
2650                   "PING");
2651       return GNUNET_SYSERR;
2652     }
2653 #if DEBUG_TRANSPORT
2654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2655               "Processing `%s' from `%s'\n",
2656               "PING", 
2657               GNUNET_a2s ((const struct sockaddr *)sender_address, 
2658                           sender_address_len));
2659 #endif
2660   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2661   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2662   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2663   pong->purpose.size =
2664     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2665            sizeof (uint32_t) +
2666            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2667   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2668   pong->challenge = ping->challenge;
2669   pong->addrlen = htons(sender_address_len);
2670   memcpy(&pong->signer, 
2671          &my_public_key, 
2672          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2673   memcpy (&pong[1], sender_address, sender_address_len);
2674   GNUNET_assert (GNUNET_OK ==
2675                  GNUNET_CRYPTO_rsa_sign (my_private_key,
2676                                          &pong->purpose, &pong->signature));
2677
2678   n = find_neighbour(peer);
2679   if (n == NULL)
2680     n = setup_new_neighbour(peer);
2681   /* broadcast 'PONG' to all available addresses */
2682   rl = n->plugins;
2683   while (rl != NULL)
2684     {
2685       fal = rl->addresses;
2686       while (fal != NULL)
2687         {
2688           transmit_to_peer(NULL, fal,
2689                            TRANSPORT_PONG_PRIORITY, 
2690                            HELLO_VERIFICATION_TIMEOUT,
2691                            (const char *)pong, 
2692                            ntohs(pong->header.size), 
2693                            GNUNET_YES, 
2694                            n);
2695           fal = fal->next;
2696         }
2697       rl = rl->next;
2698     }
2699   GNUNET_free(pong);
2700   return GNUNET_OK;
2701 }
2702
2703
2704 /**
2705  * Function called by the plugin for each received message.
2706  * Update data volumes, possibly notify plugins about
2707  * reducing the rate at which they read from the socket
2708  * and generally forward to our receive callback.
2709  *
2710  * @param cls the "struct TransportPlugin *" we gave to the plugin
2711  * @param peer (claimed) identity of the other peer
2712  * @param message the message, NULL if we only care about
2713  *                learning about the delay until we should receive again
2714  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2715  * @param sender_address binary address of the sender (if observed)
2716  * @param sender_address_len number of bytes in sender_address
2717  * @return how long the plugin should wait until receiving more data
2718  *         (plugins that do not support this, can ignore the return value)
2719  */
2720 static struct GNUNET_TIME_Relative
2721 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2722                     const struct GNUNET_MessageHeader *message,
2723                     unsigned int distance, const char *sender_address,
2724                     size_t sender_address_len)
2725 {
2726   struct ReadyList *service_context;
2727   struct TransportPlugin *plugin = cls;
2728   struct TransportClient *cpos;
2729   struct InboundMessage *im;
2730   struct ForeignAddressList *peer_address;
2731   uint16_t msize;
2732   struct NeighbourList *n;
2733   struct GNUNET_TIME_Relative ret;
2734
2735   n = find_neighbour (peer);
2736   if (n == NULL)
2737     n = setup_new_neighbour (peer);    
2738   service_context = n->plugins;
2739   while ((service_context != NULL) && (plugin != service_context->plugin))
2740     service_context = service_context->next;
2741   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2742   if (message != NULL)
2743     {
2744       peer_address = add_peer_address(n, 
2745                                       plugin->short_name,
2746                                       sender_address, 
2747                                       sender_address_len);  
2748       if (peer_address != NULL)
2749         {
2750           peer_address->distance = distance;
2751           if (peer_address->connected == GNUNET_NO)
2752             {
2753               peer_address->connected = GNUNET_YES;
2754               peer_address->connect_attempts++;
2755             }
2756           peer_address->timeout
2757             =
2758             GNUNET_TIME_relative_to_absolute
2759             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2760         }
2761       /* update traffic received amount ... */
2762       msize = ntohs (message->size);      
2763       n->distance = distance;
2764       n->peer_timeout =
2765         GNUNET_TIME_relative_to_absolute
2766         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2767       GNUNET_SCHEDULER_cancel (sched,
2768                                n->timeout_task);
2769       n->timeout_task =
2770         GNUNET_SCHEDULER_add_delayed (sched,
2771                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2772                                       &neighbour_timeout_task, n);
2773       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2774         {
2775           /* dropping message due to frequent inbound volume violations! */
2776           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2777                       GNUNET_ERROR_TYPE_BULK,
2778                       _
2779                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
2780                       n->in_tracker.available_bytes_per_s__,
2781                       n->quota_violation_count);
2782           return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2783         }
2784       switch (ntohs (message->type))
2785         {
2786         case GNUNET_MESSAGE_TYPE_HELLO:
2787           process_hello (plugin, message);
2788           break;
2789         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2790           handle_ping(plugin, message, peer, sender_address, sender_address_len);
2791           break;
2792         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2793           handle_pong(plugin, message, peer, sender_address, sender_address_len);
2794           break;
2795         default:
2796 #if DEBUG_TRANSPORT
2797           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2798                       "Received message of type %u from `%4s', sending to all clients.\n",
2799                       ntohs (message->type), GNUNET_i2s (peer));
2800 #endif
2801           if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2802                                                               msize))
2803             n->quota_violation_count++;
2804           else 
2805             n->quota_violation_count = 0; /* back within limits */
2806           /* transmit message to all clients */
2807           im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2808           im->header.size = htons (sizeof (struct InboundMessage) + msize);
2809           im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2810           im->latency = GNUNET_TIME_relative_hton (n->latency);
2811           im->peer = *peer;
2812           memcpy (&im[1], message, msize);
2813           cpos = clients;
2814           while (cpos != NULL)
2815             {
2816               transmit_to_client (cpos, &im->header, GNUNET_YES);
2817               cpos = cpos->next;
2818             }
2819           GNUNET_free (im);
2820         }
2821     }  
2822   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
2823   if (ret.value > 0)
2824     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2825                 "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
2826                 (unsigned long long) n->in_tracker.consumption_since_last_update__,
2827                 (unsigned int) n->in_tracker.available_bytes_per_s__,
2828                 (unsigned long long) ret.value);
2829   return ret;
2830 }
2831
2832
2833 /**
2834  * Handle START-message.  This is the first message sent to us
2835  * by any client which causes us to add it to our list.
2836  *
2837  * @param cls closure (always NULL)
2838  * @param client identification of the client
2839  * @param message the actual message
2840  */
2841 static void
2842 handle_start (void *cls,
2843               struct GNUNET_SERVER_Client *client,
2844               const struct GNUNET_MessageHeader *message)
2845 {
2846   struct TransportClient *c;
2847   struct ConnectInfoMessage cim;
2848   struct NeighbourList *n;
2849
2850 #if DEBUG_TRANSPORT
2851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2852               "Received `%s' request from client\n", "START");
2853 #endif
2854   c = clients;
2855   while (c != NULL)
2856     {
2857       if (c->client == client)
2858         {
2859           /* client already on our list! */
2860           GNUNET_break (0);
2861           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2862           return;
2863         }
2864       c = c->next;
2865     }
2866   c = GNUNET_malloc (sizeof (struct TransportClient));
2867   c->next = clients;
2868   clients = c;
2869   c->client = client;
2870   if (our_hello != NULL)
2871     {
2872 #if DEBUG_TRANSPORT
2873       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2874                   "Sending our own `%s' to new client\n", "HELLO");
2875 #endif
2876       transmit_to_client (c,
2877                           (const struct GNUNET_MessageHeader *) our_hello,
2878                           GNUNET_NO);
2879       /* tell new client about all existing connections */
2880       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2881       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2882       n = neighbours; 
2883       while (n != NULL)
2884         {
2885           if (GNUNET_YES == n->received_pong)
2886             {
2887               cim.id = n->id;
2888               cim.latency = GNUNET_TIME_relative_hton (n->latency);
2889               cim.distance = htonl (n->distance);
2890               transmit_to_client (c, &cim.header, GNUNET_NO);
2891             }
2892             n = n->next;
2893         }
2894     }
2895   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2896 }
2897
2898
2899 /**
2900  * Handle HELLO-message.
2901  *
2902  * @param cls closure (always NULL)
2903  * @param client identification of the client
2904  * @param message the actual message
2905  */
2906 static void
2907 handle_hello (void *cls,
2908               struct GNUNET_SERVER_Client *client,
2909               const struct GNUNET_MessageHeader *message)
2910 {
2911   int ret;
2912
2913   ret = process_hello (NULL, message);
2914   GNUNET_SERVER_receive_done (client, ret);
2915 }
2916
2917
2918 /**
2919  * Handle SEND-message.
2920  *
2921  * @param cls closure (always NULL)
2922  * @param client identification of the client
2923  * @param message the actual message
2924  */
2925 static void
2926 handle_send (void *cls,
2927              struct GNUNET_SERVER_Client *client,
2928              const struct GNUNET_MessageHeader *message)
2929 {
2930   struct TransportClient *tc;
2931   struct NeighbourList *n;
2932   const struct OutboundMessage *obm;
2933   const struct GNUNET_MessageHeader *obmm;
2934   uint16_t size;
2935   uint16_t msize;
2936
2937   size = ntohs (message->size);
2938   if (size <
2939       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2940     {
2941       GNUNET_break (0);
2942       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2943       return;
2944     }
2945   obm = (const struct OutboundMessage *) message;
2946 #if DEBUG_TRANSPORT
2947   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2948               "Received `%s' request from client with target `%4s'\n",
2949               "SEND", GNUNET_i2s (&obm->peer));
2950 #endif
2951   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2952   msize = ntohs (obmm->size);
2953   if (size != msize + sizeof (struct OutboundMessage))
2954     {
2955       GNUNET_break (0);
2956       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2957       return;
2958     }
2959   n = find_neighbour (&obm->peer);
2960   if (n == NULL)
2961     n = setup_new_neighbour (&obm->peer);
2962   tc = clients;
2963   while ((tc != NULL) && (tc->client != client))
2964     tc = tc->next;
2965
2966 #if DEBUG_TRANSPORT
2967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2969               ntohs (obmm->size),
2970               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2971 #endif
2972   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
2973                     GNUNET_TIME_relative_ntoh (obm->timeout),
2974                     (char *)obmm, 
2975                     ntohs (obmm->size), GNUNET_NO, n);
2976   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2977 }
2978
2979
2980 /**
2981  * Handle SET_QUOTA-message.
2982  *
2983  * @param cls closure (always NULL)
2984  * @param client identification of the client
2985  * @param message the actual message
2986  */
2987 static void
2988 handle_set_quota (void *cls,
2989                   struct GNUNET_SERVER_Client *client,
2990                   const struct GNUNET_MessageHeader *message)
2991 {
2992   const struct QuotaSetMessage *qsm =
2993     (const struct QuotaSetMessage *) message;
2994   struct NeighbourList *n;
2995
2996   n = find_neighbour (&qsm->peer);
2997   if (n == NULL)
2998     {
2999       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3000       return;
3001     }
3002 #if DEBUG_TRANSPORT
3003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3004               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3005               "SET_QUOTA", 
3006               (unsigned int) ntohl (qsm->quota.value__),
3007               (unsigned int) n->in_tracker.available_bytes_per_s__,
3008               GNUNET_i2s (&qsm->peer));
3009 #endif
3010   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3011                                          qsm->quota);
3012   if (0 == ntohl (qsm->quota.value__)) 
3013     disconnect_neighbour (n, GNUNET_NO);    
3014   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3015 }
3016
3017
3018 static void
3019 transmit_address_to_client (void *cls, const char *address)
3020 {
3021   struct GNUNET_SERVER_TransmitContext *tc = cls;
3022   size_t slen;
3023
3024   if (NULL == address)
3025     slen = 0;
3026   else
3027     slen = strlen (address) + 1;
3028   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3029                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3030   if (NULL == address)
3031     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3032 }
3033
3034
3035 /**
3036  * Handle AddressLookup-message.
3037  *
3038  * @param cls closure (always NULL)
3039  * @param client identification of the client
3040  * @param message the actual message
3041  */
3042 static void
3043 handle_address_lookup (void *cls,
3044                        struct GNUNET_SERVER_Client *client,
3045                        const struct GNUNET_MessageHeader *message)
3046 {
3047   const struct AddressLookupMessage *alum;
3048   struct TransportPlugin *lsPlugin;
3049   const char *nameTransport;
3050   const char *address;
3051   uint16_t size;
3052   struct GNUNET_SERVER_TransmitContext *tc;
3053
3054   size = ntohs (message->size);
3055   if (size < sizeof (struct AddressLookupMessage))
3056     {
3057       GNUNET_break_op (0);
3058       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3059       return;
3060     }
3061   alum = (const struct AddressLookupMessage *) message;
3062   uint32_t addressLen = ntohl (alum->addrlen);
3063   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3064     {
3065       GNUNET_break_op (0);
3066       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3067       return;
3068     }
3069   address = (const char *) &alum[1];
3070   nameTransport = (const char *) &address[addressLen];
3071   if (nameTransport
3072       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3073     {
3074       GNUNET_break_op (0);
3075       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3076       return;
3077     }
3078   struct GNUNET_TIME_Absolute timeout =
3079     GNUNET_TIME_absolute_ntoh (alum->timeout);
3080   struct GNUNET_TIME_Relative rtimeout =
3081     GNUNET_TIME_absolute_get_remaining (timeout);
3082   lsPlugin = find_transport (nameTransport);
3083   if (NULL == lsPlugin)
3084     {
3085       tc = GNUNET_SERVER_transmit_context_create (client);
3086       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3087                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3088       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3089       return;
3090     }
3091   tc = GNUNET_SERVER_transmit_context_create (client);
3092   lsPlugin->api->address_pretty_printer (cls, nameTransport,
3093                                          address, addressLen, GNUNET_YES,
3094                                          rtimeout,
3095                                          &transmit_address_to_client, tc);
3096 }
3097
3098 /**
3099  * List of handlers for the messages understood by this
3100  * service.
3101  */
3102 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3103   {&handle_start, NULL,
3104    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3105   {&handle_hello, NULL,
3106    GNUNET_MESSAGE_TYPE_HELLO, 0},
3107   {&handle_send, NULL,
3108    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3109   {&handle_set_quota, NULL,
3110    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3111   {&handle_address_lookup, NULL,
3112    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3113    0},
3114   {NULL, NULL, 0, 0}
3115 };
3116
3117
3118 /**
3119  * Setup the environment for this plugin.
3120  */
3121 static void
3122 create_environment (struct TransportPlugin *plug)
3123 {
3124   plug->env.cfg = cfg;
3125   plug->env.sched = sched;
3126   plug->env.my_identity = &my_identity;
3127   plug->env.cls = plug;
3128   plug->env.receive = &plugin_env_receive;
3129   plug->env.notify_address = &plugin_env_notify_address;
3130   plug->env.max_connections = max_connect_per_transport;
3131 }
3132
3133
3134 /**
3135  * Start the specified transport (load the plugin).
3136  */
3137 static void
3138 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3139 {
3140   struct TransportPlugin *plug;
3141   char *libname;
3142
3143   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3144               _("Loading `%s' transport plugin\n"), name);
3145   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3146   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3147   create_environment (plug);
3148   plug->short_name = GNUNET_strdup (name);
3149   plug->lib_name = libname;
3150   plug->next = plugins;
3151   plugins = plug;
3152   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3153   if (plug->api == NULL)
3154     {
3155       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3156                   _("Failed to load transport plugin for `%s'\n"), name);
3157       GNUNET_free (plug->short_name);
3158       plugins = plug->next;
3159       GNUNET_free (libname);
3160       GNUNET_free (plug);
3161     }
3162 }
3163
3164
3165 /**
3166  * Called whenever a client is disconnected.  Frees our
3167  * resources associated with that client.
3168  *
3169  * @param cls closure
3170  * @param client identification of the client
3171  */
3172 static void
3173 client_disconnect_notification (void *cls,
3174                                 struct GNUNET_SERVER_Client *client)
3175 {
3176   struct TransportClient *pos;
3177   struct TransportClient *prev;
3178   struct ClientMessageQueueEntry *mqe;
3179
3180   if (client == NULL)
3181     return;
3182 #if DEBUG_TRANSPORT
3183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3184               "Client disconnected, cleaning up.\n");
3185 #endif
3186   prev = NULL;
3187   pos = clients;
3188   while ((pos != NULL) && (pos->client != client))
3189     {
3190       prev = pos;
3191       pos = pos->next;
3192     }
3193   if (pos == NULL)
3194     return;
3195   while (NULL != (mqe = pos->message_queue_head))
3196     {
3197       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3198                                    pos->message_queue_tail,
3199                                    mqe);
3200       pos->message_count--;
3201       GNUNET_free (mqe);
3202     }
3203   if (prev == NULL)
3204     clients = pos->next;
3205   else
3206     prev->next = pos->next;
3207   if (GNUNET_YES == pos->tcs_pending)
3208     {
3209       pos->client = NULL;
3210       return;
3211     }
3212   if (pos->th != NULL)
3213     {
3214       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3215       pos->th = NULL;
3216     }
3217   GNUNET_break (0 == pos->message_count);
3218   GNUNET_free (pos);
3219 }
3220
3221
3222 /**
3223  * Iterator to free entries in the validation_map.
3224  *
3225  * @param cls closure (unused)
3226  * @param key current key code
3227  * @param value value in the hash map (validation to abort)
3228  * @return GNUNET_YES (always)
3229  */
3230 static int 
3231 abort_validation (void *cls,
3232                   const GNUNET_HashCode * key,
3233                   void *value)
3234 {
3235   struct ValidationEntry *va = value;
3236
3237   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3238   GNUNET_free (va->transport_name);
3239   GNUNET_free (va);
3240   return GNUNET_YES;
3241 }
3242
3243
3244 /**
3245  * Function called when the service shuts down.  Unloads our plugins
3246  * and cancels pending validations.
3247  *
3248  * @param cls closure, unused
3249  * @param tc task context (unused)
3250  */
3251 static void
3252 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3253 {
3254   struct TransportPlugin *plug;
3255   struct OwnAddressList *al;
3256   struct CheckHelloValidatedContext *chvc;
3257
3258   while (neighbours != NULL)
3259     disconnect_neighbour (neighbours, GNUNET_NO);
3260 #if DEBUG_TRANSPORT
3261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3262               "Transport service is unloading plugins...\n");
3263 #endif
3264   while (NULL != (plug = plugins))
3265     {
3266       plugins = plug->next;
3267       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3268       GNUNET_free (plug->lib_name);
3269       GNUNET_free (plug->short_name);
3270       while (NULL != (al = plug->addresses))
3271         {
3272           plug->addresses = al->next;
3273           GNUNET_free (al);
3274         }
3275       GNUNET_free (plug);
3276     }
3277   if (my_private_key != NULL)
3278     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3279   GNUNET_free_non_null (our_hello);
3280
3281   /* free 'chvc' data structure */
3282   while (NULL != (chvc = chvc_head))
3283     {
3284       chvc_head = chvc->next;
3285       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3286       GNUNET_free (chvc);
3287     }
3288   chvc_tail = NULL;
3289
3290   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3291                                          &abort_validation,
3292                                          NULL);
3293   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3294 }
3295
3296
3297 /**
3298  * Initiate transport service.
3299  *
3300  * @param cls closure
3301  * @param s scheduler to use
3302  * @param serv the initialized server
3303  * @param c configuration to use
3304  */
3305 static void
3306 run (void *cls,
3307      struct GNUNET_SCHEDULER_Handle *s,
3308      struct GNUNET_SERVER_Handle *serv,
3309      const struct GNUNET_CONFIGURATION_Handle *c)
3310 {
3311   char *plugs;
3312   char *pos;
3313   int no_transports;
3314   unsigned long long tneigh;
3315   char *keyfile;
3316
3317   sched = s;
3318   cfg = c;
3319   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3320   /* parse configuration */
3321   if ((GNUNET_OK !=
3322        GNUNET_CONFIGURATION_get_value_number (c,
3323                                               "TRANSPORT",
3324                                               "NEIGHBOUR_LIMIT",
3325                                               &tneigh)) ||
3326       (GNUNET_OK !=
3327        GNUNET_CONFIGURATION_get_value_filename (c,
3328                                                 "GNUNETD",
3329                                                 "HOSTKEY", &keyfile)))
3330     {
3331       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3332                   _
3333                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
3334       GNUNET_SCHEDULER_shutdown (s);
3335       return;
3336     }
3337   max_connect_per_transport = (uint32_t) tneigh;
3338   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3339   GNUNET_free (keyfile);
3340   if (my_private_key == NULL)
3341     {
3342       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3343                   _
3344                   ("Transport service could not access hostkey.  Exiting.\n"));
3345       GNUNET_SCHEDULER_shutdown (s);
3346       return;
3347     }
3348   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3349   GNUNET_CRYPTO_hash (&my_public_key,
3350                       sizeof (my_public_key), &my_identity.hashPubKey);
3351   /* setup notification */
3352   server = serv;
3353   GNUNET_SERVER_disconnect_notify (server,
3354                                    &client_disconnect_notification, NULL);
3355   /* load plugins... */
3356   no_transports = 1;
3357   if (GNUNET_OK ==
3358       GNUNET_CONFIGURATION_get_value_string (c,
3359                                              "TRANSPORT", "PLUGINS", &plugs))
3360     {
3361       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3362                   _("Starting transport plugins `%s'\n"), plugs);
3363       pos = strtok (plugs, " ");
3364       while (pos != NULL)
3365         {
3366           start_transport (server, pos);
3367           no_transports = 0;
3368           pos = strtok (NULL, " ");
3369         }
3370       GNUNET_free (plugs);
3371     }
3372   GNUNET_SCHEDULER_add_delayed (sched,
3373                                 GNUNET_TIME_UNIT_FOREVER_REL,
3374                                 &shutdown_task, NULL);
3375   if (no_transports)
3376     refresh_hello ();
3377
3378 #if DEBUG_TRANSPORT
3379   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3380 #endif
3381   /* process client requests */
3382   GNUNET_SERVER_add_handlers (server, handlers);
3383 }
3384
3385
3386 /**
3387  * The main function for the transport service.
3388  *
3389  * @param argc number of arguments from the command line
3390  * @param argv command line arguments
3391  * @return 0 ok, 1 on error
3392  */
3393 int
3394 main (int argc, char *const *argv)
3395 {
3396   return (GNUNET_OK ==
3397           GNUNET_SERVICE_run (argc,
3398                               argv,
3399                               "transport",
3400                               GNUNET_SERVICE_OPTION_NONE,
3401                               &run, NULL)) ? 0 : 1;
3402 }
3403
3404 /* end of gnunet-service-transport.c */