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