(no commit message)
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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 3, 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  */
27 #include "platform.h"
28 #include "gnunet_client_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_peerinfo_service.h"
35 #include "gnunet_plugin_lib.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_service_lib.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_transport_plugin.h"
40 #include "transport.h"
41
42 #define DEBUG_BLACKLIST GNUNET_YES
43
44 #define DEBUG_PING_PONG GNUNET_YES
45
46 #define DEBUG_TRANSPORT_HELLO GNUNET_YES
47
48 /**
49  * Should we do some additional checks (to validate behavior
50  * of clients)?
51  */
52 #define EXTRA_CHECKS GNUNET_YES
53
54 /**
55  * How many messages can we have pending for a given client process
56  * before we start to drop incoming messages?  We typically should
57  * have only one client and so this would be the primary buffer for
58   * messages, so the number should be chosen rather generously.
59  *
60  * The expectation here is that most of the time the queue is large
61  * enough so that a drop is virtually never required.  Note that
62  * this value must be about as large as 'TOTAL_MSGS' in the
63  * 'test_transport_api_reliability.c', otherwise that testcase may
64  * fail.
65  */
66 #define MAX_PENDING (128 * 1024)
67
68 /**
69  * Size of the per-transport blacklist hash maps.
70  */
71 #define TRANSPORT_BLACKLIST_HT_SIZE 16
72
73 /**
74  * How often should we try to reconnect to a peer using a particular
75  * transport plugin before giving up?  Note that the plugin may be
76  * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
77  */
78 #define MAX_CONNECT_RETRY 3
79
80 /**
81  * Limit on the number of ready-to-run tasks when validating
82  * HELLOs.  If more tasks are ready to run, we will drop
83  * HELLOs instead of validating them.
84  */
85 #define MAX_HELLO_LOAD 4
86
87 /**
88  * How often must a peer violate bandwidth quotas before we start
89  * to simply drop its messages?
90  */
91 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
92
93 /**
94  * How long until a HELLO verification attempt should time out?
95  * Must be rather small, otherwise a partially successful HELLO
96  * validation (some addresses working) might not be available
97  * before a client's request for a connection fails for good.
98  * Besides, if a single request to an address takes a long time,
99  * then the peer is unlikely worthwhile anyway.
100  */
101 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
102
103 /**
104  * How long is a PONG signature valid?  We'll recycle a signature until
105  * 1/4 of this time is remaining.  PONGs should expire so that if our
106  * external addresses change an adversary cannot replay them indefinitely.
107  * OTOH, we don't want to spend too much time generating PONG signatures,
108  * so they must have some lifetime to reduce our CPU usage.
109  */
110 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
111
112 /**
113  * Priority to use for PONG messages.
114  */
115 #define TRANSPORT_PONG_PRIORITY 4
116
117 /**
118  * How often do we re-add (cheaper) plugins to our list of plugins
119  * to try for a given connected peer?
120  */
121 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
122
123 /**
124  * After how long do we expire an address in a HELLO that we just
125  * validated?  This value is also used for our own addresses when we
126  * create a HELLO.
127  */
128 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
129
130
131 /**
132  * How long before an existing address expires should we again try to
133  * validate it?  Must be (significantly) smaller than
134  * HELLO_ADDRESS_EXPIRATION.
135  */
136 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
137
138 /**
139  * Maximum frequency for re-evaluating latencies for all transport addresses.
140  */
141 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
142
143 /**
144  * Maximum frequency for re-evaluating latencies for connected addresses.
145  */
146 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
147
148
149 /**
150  * List of addresses of other peers
151  */
152 struct ForeignAddressList
153 {
154   /**
155    * This is a linked list.
156    */
157   struct ForeignAddressList *next;
158
159   /**
160    * Which ready list does this entry belong to.
161    */
162   struct ReadyList *ready_list;
163
164   /**
165    * How long until we auto-expire this address (unless it is
166    * re-confirmed by the transport)?
167    */
168   struct GNUNET_TIME_Absolute expires;
169
170   /**
171    * Task used to re-validate addresses, updates latencies and
172    * verifies liveness.
173    */
174   GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
175
176   /**
177    * The address.
178    */
179   const void *addr;
180
181   /**
182    * Session (or NULL if no valid session currently exists or if the
183    * plugin does not use sessions).
184    */
185   struct Session *session;
186
187   /**
188    * What was the last latency observed for this address, plugin and peer?
189    */
190   struct GNUNET_TIME_Relative latency;
191
192   /**
193    * If we did not successfully transmit a message to the given peer
194    * via this connection during the specified time, we should consider
195    * the connection to be dead.  This is used in the case that a TCP
196    * transport simply stalls writing to the stream but does not
197    * formerly get a signal that the other peer died.
198    */
199   struct GNUNET_TIME_Absolute timeout;
200
201   /**
202    * How often have we tried to connect using this plugin?  Used to
203    * discriminate against addresses that do not work well.
204    * FIXME: not yet used, but should be!
205    */
206   unsigned int connect_attempts;
207
208   /**
209    * DV distance to this peer (1 if no DV is used).
210    * FIXME: need to set this from transport plugins!
211    */
212   uint32_t distance;
213
214   /**
215    * Length of addr.
216    */
217   uint16_t addrlen;
218
219   /**
220    * Have we ever estimated the latency of this address?  Used to
221    * ensure that the first time we add an address, we immediately
222    * probe its latency.
223    */
224   int8_t estimated;
225
226   /**
227    * Are we currently connected via this address?  The first time we
228    * successfully transmit or receive data to a peer via a particular
229    * address, we set this to GNUNET_YES.  If we later get an error
230    * (disconnect notification, transmission failure, timeout), we set
231    * it back to GNUNET_NO.
232    */
233   int8_t connected;
234
235   /**
236    * Is this plugin currently busy transmitting to the specific target?
237    * GNUNET_NO if not (initial, default state is GNUNET_NO).   Internal
238    * messages do not count as 'in transmit'.
239    */
240   int8_t in_transmit;
241
242   /**
243    * Has this address been validated yet?
244    */
245   int8_t validated;
246
247 };
248
249
250 /**
251  * Entry in linked list of network addresses for ourselves.  Also
252  * includes a cached signature for 'struct TransportPongMessage's.
253  */
254 struct OwnAddressList
255 {
256   /**
257    * This is a linked list.
258    */
259   struct OwnAddressList *next;
260
261   /**
262    * How long until we actually auto-expire this address (unless it is
263    * re-confirmed by the transport)?
264    */
265   struct GNUNET_TIME_Absolute expires;
266
267   /**
268    * How long until the current signature expires? (ZERO if the
269    * signature was never created).
270    */
271   struct GNUNET_TIME_Absolute pong_sig_expires;
272
273   /**
274    * Signature for a 'struct TransportPongMessage' for this address.
275    */
276   struct GNUNET_CRYPTO_RsaSignature pong_signature;
277
278   /**
279    * Length of addr.
280    */
281   uint32_t addrlen;
282
283 };
284
285
286 /**
287  * Entry in linked list of all of our plugins.
288  */
289 struct TransportPlugin
290 {
291
292   /**
293    * This is a linked list.
294    */
295   struct TransportPlugin *next;
296
297   /**
298    * API of the transport as returned by the plugin's
299    * initialization function.
300    */
301   struct GNUNET_TRANSPORT_PluginFunctions *api;
302
303   /**
304    * Short name for the plugin (i.e. "tcp").
305    */
306   char *short_name;
307
308   /**
309    * Name of the library (i.e. "gnunet_plugin_transport_tcp").
310    */
311   char *lib_name;
312
313   /**
314    * List of our known addresses for this transport.
315    */
316   struct OwnAddressList *addresses;
317
318   /**
319    * Environment this transport service is using
320    * for this plugin.
321    */
322   struct GNUNET_TRANSPORT_PluginEnvironment env;
323
324   /**
325    * ID of task that is used to clean up expired addresses.
326    */
327   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
328
329   /**
330    * Set to GNUNET_YES if we need to scrap the existing list of
331    * "addresses" and start fresh when we receive the next address
332    * update from a transport.  Set to GNUNET_NO if we should just add
333    * the new address to the list and wait for the commit call.
334    */
335   int rebuild;
336
337   /**
338    * Hashmap of blacklisted peers for this particular transport.
339    */
340   struct GNUNET_CONTAINER_MultiHashMap *blacklist;
341 };
342
343 struct NeighbourList;
344
345 /**
346  * For each neighbour we keep a list of messages
347  * that we still want to transmit to the neighbour.
348  */
349 struct MessageQueue
350 {
351
352   /**
353    * This is a doubly linked list.
354    */
355   struct MessageQueue *next;
356
357   /**
358    * This is a doubly linked list.
359    */
360   struct MessageQueue *prev;
361
362   /**
363    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
364    * stuck together in memory.  Allocated at the end of this struct.
365    */
366   const char *message_buf;
367
368   /**
369    * Size of the message buf
370    */
371   size_t message_buf_size;
372
373   /**
374    * Client responsible for queueing the message;
375    * used to check that a client has no two messages
376    * pending for the same target.  Can be NULL.
377    */
378   struct TransportClient *client;
379
380   /**
381    * Using which specific address should we send this message?
382    */
383   struct ForeignAddressList *specific_address;
384
385   /**
386    * Peer ID of the Neighbour this entry belongs to.
387    */
388   struct GNUNET_PeerIdentity neighbour_id;
389
390   /**
391    * Plugin that we used for the transmission.
392    * NULL until we scheduled a transmission.
393    */
394   struct TransportPlugin *plugin;
395
396   /**
397    * At what time should we fail?
398    */
399   struct GNUNET_TIME_Absolute timeout;
400
401   /**
402    * Internal message of the transport system that should not be
403    * included in the usual SEND-SEND_OK transmission confirmation
404    * traffic management scheme.  Typically, "internal_msg" will
405    * be set whenever "client" is NULL (but it is not strictly
406    * required).
407    */
408   int internal_msg;
409
410   /**
411    * How important is the message?
412    */
413   unsigned int priority;
414
415 };
416
417
418 /**
419  * For a given Neighbour, which plugins are available
420  * to talk to this peer and what are their costs?
421  */
422 struct ReadyList
423 {
424   /**
425    * This is a linked list.
426    */
427   struct ReadyList *next;
428
429   /**
430    * Which of our transport plugins does this entry
431    * represent?
432    */
433   struct TransportPlugin *plugin;
434
435   /**
436    * Transport addresses, latency, and readiness for
437    * this particular plugin.
438    */
439   struct ForeignAddressList *addresses;
440
441   /**
442    * To which neighbour does this ready list belong to?
443    */
444   struct NeighbourList *neighbour;
445
446 };
447
448
449 /**
450  * Entry in linked list of all of our current neighbours.
451  */
452 struct NeighbourList
453 {
454
455   /**
456    * This is a linked list.
457    */
458   struct NeighbourList *next;
459
460   /**
461    * Which of our transports is connected to this peer
462    * and what is their status?
463    */
464   struct ReadyList *plugins;
465
466   /**
467    * Head of list of messages we would like to send to this peer;
468    * must contain at most one message per client.
469    */
470   struct MessageQueue *messages_head;
471
472   /**
473    * Tail of list of messages we would like to send to this peer; must
474    * contain at most one message per client.
475    */
476   struct MessageQueue *messages_tail;
477
478   /**
479    * Buffer for at most one payload message used when we receive
480    * payload data before our PING-PONG has succeeded.  We then
481    * store such messages in this intermediary buffer until the
482    * connection is fully up.
483    */
484   struct GNUNET_MessageHeader *pre_connect_message_buffer;
485
486   /**
487    * Context for peerinfo iteration.
488    * NULL after we are done processing peerinfo's information.
489    */
490   struct GNUNET_PEERINFO_IteratorContext *piter;
491
492   /**
493    * Public key for this peer.   Valid only if the respective flag is set below.
494    */
495   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
496
497   /**
498    * Identity of this neighbour.
499    */
500   struct GNUNET_PeerIdentity id;
501
502   /**
503    * ID of task scheduled to run when this peer is about to
504    * time out (will free resources associated with the peer).
505    */
506   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
507
508   /**
509    * ID of task scheduled to run when we should retry transmitting
510    * the head of the message queue.  Actually triggered when the
511    * transmission is timing out (we trigger instantly when we have
512    * a chance of success).
513    */
514   GNUNET_SCHEDULER_TaskIdentifier retry_task;
515
516   /**
517    * How long until we should consider this peer dead
518    * (if we don't receive another message in the
519    * meantime)?
520    */
521   struct GNUNET_TIME_Absolute peer_timeout;
522
523   /**
524    * Tracker for inbound bandwidth.
525    */
526   struct GNUNET_BANDWIDTH_Tracker in_tracker;
527
528   /**
529    * The latency we have seen for this particular address for
530    * this particular peer.  This latency may have been calculated
531    * over multiple transports.  This value reflects how long it took
532    * us to receive a response when SENDING via this particular
533    * transport/neighbour/address combination!
534    *
535    * FIXME: we need to periodically send PINGs to update this
536    * latency (at least more often than the current "huge" (11h?)
537    * update interval).
538    */
539   struct GNUNET_TIME_Relative latency;
540
541   /**
542    * How often has the other peer (recently) violated the
543    * inbound traffic limit?  Incremented by 10 per violation,
544    * decremented by 1 per non-violation (for each
545    * time interval).
546    */
547   unsigned int quota_violation_count;
548
549   /**
550    * DV distance to this peer (1 if no DV is used).
551    */
552   uint32_t distance;
553
554   /**
555    * Have we seen an PONG from this neighbour in the past (and
556    * not had a disconnect since)?
557    */
558   int received_pong;
559
560   /**
561    * Do we have a valid public key for this neighbour?
562    */
563   int public_key_valid;
564
565 };
566
567 /**
568  * Message used to ask a peer to validate receipt (to check an address
569  * from a HELLO).  Followed by the address we are trying to validate,
570  * or an empty address if we are just sending a PING to confirm that a
571  * connection which the receiver (of the PING) initiated is still valid.
572  */
573 struct TransportPingMessage
574 {
575
576   /**
577    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
578    */
579   struct GNUNET_MessageHeader header;
580
581   /**
582    * Challenge code (to ensure fresh reply).
583    */
584   uint32_t challenge GNUNET_PACKED;
585
586   /**
587    * Who is the intended recipient?
588    */
589   struct GNUNET_PeerIdentity target;
590
591 };
592
593
594 /**
595  * Message used to validate a HELLO.  The challenge is included in the
596  * confirmation to make matching of replies to requests possible.  The
597  * signature signs our public key, an expiration time and our address.<p>
598  *
599  * This message is followed by our transport address that the PING tried
600  * to confirm (if we liked it).  The address can be empty (zero bytes)
601  * if the PING had not address either (and we received the request via
602  * a connection that we initiated).
603  */
604 struct TransportPongMessage
605 {
606
607   /**
608    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
609    */
610   struct GNUNET_MessageHeader header;
611
612   /**
613    * Challenge code from PING (showing freshness).  Not part of what
614    * is signed so that we can re-use signatures.
615    */
616   uint32_t challenge GNUNET_PACKED;
617
618   /**
619    * Signature.
620    */
621   struct GNUNET_CRYPTO_RsaSignature signature;
622
623   /**
624    * What are we signing and why?  Two possible reason codes can be here:
625    * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
626    * plausible address for this peer (pid is set to identity of signer); or
627    * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
628    * an address we used to connect to the peer with the given pid.
629    */
630   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
631
632   /**
633    * When does this signature expire?
634    */
635   struct GNUNET_TIME_AbsoluteNBO expiration;
636
637   /**
638    * Either the identity of the peer Who signed this message, or the
639    * identity of the peer that we're connected to using the given
640    * address (depending on purpose.type).
641    */
642   struct GNUNET_PeerIdentity pid;
643
644   /**
645    * Size of address appended to this message (part of what is
646    * being signed, hence not redundant).
647    */
648   uint32_t addrlen;
649
650 };
651
652
653 /**
654  * Linked list of messages to be transmitted to the client.  Each
655  * entry is followed by the actual message.
656  */
657 struct ClientMessageQueueEntry
658 {
659   /**
660    * This is a doubly-linked list.
661    */
662   struct ClientMessageQueueEntry *next;
663
664   /**
665    * This is a doubly-linked list.
666    */
667   struct ClientMessageQueueEntry *prev;
668 };
669
670
671 /**
672  * Client connected to the transport service.
673  */
674 struct TransportClient
675 {
676
677   /**
678    * This is a linked list.
679    */
680   struct TransportClient *next;
681
682   /**
683    * Handle to the client.
684    */
685   struct GNUNET_SERVER_Client *client;
686
687   /**
688    * Linked list of messages yet to be transmitted to
689    * the client.
690    */
691   struct ClientMessageQueueEntry *message_queue_head;
692
693   /**
694    * Tail of linked list of messages yet to be transmitted to the
695    * client.
696    */
697   struct ClientMessageQueueEntry *message_queue_tail;
698
699   /**
700    * Current transmit request handle.
701    */
702   struct GNUNET_CONNECTION_TransmitHandle *th;
703
704   /**
705    * Is a call to "transmit_send_continuation" pending?  If so, we
706    * must not free this struct (even if the corresponding client
707    * disconnects) and instead only remove it from the linked list and
708    * set the "client" field to NULL.
709    */
710   int tcs_pending;
711
712   /**
713    * Length of the list of messages pending for this client.
714    */
715   unsigned int message_count;
716
717 };
718
719
720 /**
721  * Context of currently active requests to peerinfo
722  * for validation of HELLOs.
723  */
724 struct CheckHelloValidatedContext;
725
726
727 /**
728  * Entry in map of all HELLOs awaiting validation.
729  */
730 struct ValidationEntry
731 {
732
733   /**
734    * NULL if this entry is not part of a larger HELLO validation.
735    */
736   struct CheckHelloValidatedContext *chvc;
737
738   /**
739    * The address, actually a pointer to the end
740    * of this struct.  Do not free!
741    */
742   const void *addr;
743
744   /**
745    * Name of the transport.
746    */
747   char *transport_name;
748
749   /**
750    * The public key of the peer.
751    */
752   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
753
754   /**
755    * ID of task that will clean up this entry if we don't succeed
756    * with the validation first.
757    */
758   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
759
760   /**
761    * At what time did we send this validation?
762    */
763   struct GNUNET_TIME_Absolute send_time;
764
765   /**
766    * Session being validated (or NULL for none).
767    */
768   struct Session *session;
769
770   /**
771    * Challenge number we used.
772    */
773   uint32_t challenge;
774
775   /**
776    * Length of addr.
777    */
778   uint16_t addrlen;
779
780 };
781
782
783 /**
784  * Context of currently active requests to peerinfo
785  * for validation of HELLOs.
786  */
787 struct CheckHelloValidatedContext
788 {
789
790   /**
791    * This is a doubly-linked list.
792    */
793   struct CheckHelloValidatedContext *next;
794
795   /**
796    * This is a doubly-linked list.
797    */
798   struct CheckHelloValidatedContext *prev;
799
800   /**
801    * Hello that we are validating.
802    */
803   const struct GNUNET_HELLO_Message *hello;
804
805   /**
806    * Context for peerinfo iteration.
807    * NULL after we are done processing peerinfo's information.
808    */
809   struct GNUNET_PEERINFO_IteratorContext *piter;
810
811   /**
812    * Was a HELLO known for this peer to peerinfo?
813    */
814   int hello_known;
815
816   /**
817    * Number of validation entries currently referring to this
818    * CHVC.
819    */
820   unsigned int ve_count;
821 };
822
823
824
825 /**
826  * Our HELLO message.
827  */
828 static struct GNUNET_HELLO_Message *our_hello;
829
830 /**
831  * Our public key.
832  */
833 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
834
835 /**
836  * Our identity.
837  */
838 static struct GNUNET_PeerIdentity my_identity;
839
840 /**
841  * Our private key.
842  */
843 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
844
845 /**
846  * Our configuration.
847  */
848 const struct GNUNET_CONFIGURATION_Handle *cfg;
849
850 /**
851  * Linked list of all clients to this service.
852  */
853 static struct TransportClient *clients;
854
855 /**
856  * All loaded plugins.
857  */
858 static struct TransportPlugin *plugins;
859
860 /**
861  * Handle to peerinfo service.
862  */
863 static struct GNUNET_PEERINFO_Handle *peerinfo;
864
865 /**
866  * All known neighbours and their HELLOs.
867  */
868 static struct NeighbourList *neighbours;
869
870 /**
871  * Number of neighbours we'd like to have.
872  */
873 static uint32_t max_connect_per_transport;
874
875 /**
876  * Head of linked list.
877  */
878 static struct CheckHelloValidatedContext *chvc_head;
879
880 /**
881  * Tail of linked list.
882  */
883 static struct CheckHelloValidatedContext *chvc_tail;
884
885 /**
886  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
887  * of the given peer that we are currently validating).
888  */
889 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
890
891 /**
892  * Handle for reporting statistics.
893  */
894 static struct GNUNET_STATISTICS_Handle *stats;
895
896 /**
897  * The peer specified by the given neighbour has timed-out or a plugin
898  * has disconnected.  We may either need to do nothing (other plugins
899  * still up), or trigger a full disconnect and clean up.  This
900  * function updates our state and do the necessary notifications.
901  * Also notifies our clients that the neighbour is now officially
902  * gone.
903  *
904  * @param n the neighbour list entry for the peer
905  * @param check should we just check if all plugins
906  *        disconnected or must we ask all plugins to
907  *        disconnect?
908  */
909 static void disconnect_neighbour (struct NeighbourList *n, int check);
910
911 /**
912  * Check the ready list for the given neighbour and if a plugin is
913  * ready for transmission (and if we have a message), do so!
914  *
915  * @param neighbour target peer for which to transmit
916  */
917 static void try_transmission_to_peer (struct NeighbourList *neighbour);
918
919
920 /**
921  * Find an entry in the neighbour list for a particular peer.
922  *
923  * @return NULL if not found.
924  */
925 static struct NeighbourList *
926 find_neighbour (const struct GNUNET_PeerIdentity *key)
927 {
928   struct NeighbourList *head = neighbours;
929
930   while ((head != NULL) &&
931         (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
932     head = head->next;
933   return head;
934 }
935
936
937 /**
938  * Find an entry in the transport list for a particular transport.
939  *
940  * @return NULL if not found.
941  */
942 static struct TransportPlugin *
943 find_transport (const char *short_name)
944 {
945   struct TransportPlugin *head = plugins;
946   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
947     head = head->next;
948   return head;
949 }
950
951 /**
952  * Is a particular peer blacklisted for a particular transport?
953  *
954  * @param peer the peer to check for
955  * @param plugin the plugin used to connect to the peer
956  *
957  * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
958  */
959 static int
960 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
961 {
962
963   if (plugin->blacklist != NULL)
964     {
965       if (GNUNET_CONTAINER_multihashmap_contains(plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
966         {
967 #if DEBUG_BLACKLIST
968           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969                       _("Peer `%s:%s' is blacklisted!\n"),
970                       plugin->short_name, GNUNET_i2s (peer));
971 #endif
972           return GNUNET_YES;
973         }
974     }
975
976   return GNUNET_NO;
977 }
978
979
980 static void
981 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
982 {
983   struct TransportPlugin *plugin;
984
985   plugin = find_transport(transport_name);
986   if (plugin == NULL) /* Nothing to do */
987     return;
988   if (plugin->blacklist == NULL)
989     plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);
990   GNUNET_assert(plugin->blacklist != NULL);
991   GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
992                                     NULL,
993                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
994 }
995
996
997 /**
998  * Read the blacklist file, containing transport:peer entries.
999  * Provided the transport is loaded, set up hashmap with these
1000  * entries to blacklist peers by transport.
1001  *
1002  */
1003 static void
1004 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
1005 {
1006   char *fn;
1007   char *data;
1008   size_t pos;
1009   size_t colon_pos;
1010   int tsize;
1011   struct GNUNET_PeerIdentity pid;
1012   struct stat frstat;
1013   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
1014   unsigned int entries_found;
1015   char *transport_name;
1016
1017   if (GNUNET_OK !=
1018       GNUNET_CONFIGURATION_get_value_filename (cfg,
1019                                                "TRANSPORT",
1020                                                "BLACKLIST_FILE",
1021                                                &fn))
1022     {
1023 #if DEBUG_TRANSPORT
1024       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1025                   _("Option `%s' in section `%s' not specified!\n"),
1026                   "BLACKLIST_FILE",
1027                   "TRANSPORT");
1028 #endif
1029       return;
1030     }
1031   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1032     GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1033         | GNUNET_DISK_PERM_USER_WRITE);
1034   if (0 != STAT (fn, &frstat))
1035     {
1036       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1037                   _("Could not read blacklist file `%s'\n"), fn);
1038       GNUNET_free (fn);
1039       return;
1040     }
1041   if (frstat.st_size == 0)
1042     {
1043 #if DEBUG_TRANSPORT
1044       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1045                   _("Blacklist file `%s' is empty.\n"),
1046                   fn);
1047 #endif
1048       GNUNET_free (fn);
1049       return;
1050     }
1051   /* FIXME: use mmap */
1052   data = GNUNET_malloc_large (frstat.st_size);
1053   GNUNET_assert(data != NULL);
1054   if (frstat.st_size !=
1055       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1056     {
1057       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1058                   _("Failed to read blacklist from `%s'\n"), fn);
1059       GNUNET_free (fn);
1060       GNUNET_free (data);
1061       return;
1062     }
1063   entries_found = 0;
1064   pos = 0;
1065   while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1066     pos++;
1067   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1068          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1069     {
1070       colon_pos = pos;
1071       while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1072         colon_pos++;
1073
1074       if (colon_pos >= frstat.st_size)
1075         {
1076           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1077                       _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1078                       (unsigned long long) colon_pos);
1079           GNUNET_free (fn);
1080           GNUNET_free (data);
1081           return;
1082         }
1083
1084       if (isspace( (unsigned char) data[colon_pos]))
1085       {
1086         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1087                     _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1088                     (unsigned long long) colon_pos);
1089         pos = colon_pos;
1090         while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1091           pos++;
1092         continue;
1093       }
1094       tsize = colon_pos - pos;
1095       if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1096         {
1097           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1098                       _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1099                       (unsigned long long) colon_pos);
1100           GNUNET_free (fn);
1101           GNUNET_free (data);
1102           return;
1103         }
1104
1105       if (tsize < 1)
1106         continue;
1107
1108       transport_name = GNUNET_malloc(tsize + 1);
1109       memcpy(transport_name, &data[pos], tsize);
1110       pos = colon_pos + 1;
1111 #if DEBUG_TRANSPORT
1112       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1113                   _("Read transport name %s in blacklist file.\n"),
1114                   transport_name);
1115 #endif
1116       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1117       if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1118         {
1119           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1120                       _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1121                       (unsigned long long) pos);
1122           pos++;
1123           while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1124             pos++;
1125           GNUNET_free_non_null(transport_name);
1126           continue;
1127         }
1128       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1129       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1130         {
1131           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1132                       _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1133                       (unsigned long long) pos,
1134                       &enc);
1135         }
1136       else
1137         {
1138           if (0 != memcmp (&pid,
1139                            &my_identity,
1140                            sizeof (struct GNUNET_PeerIdentity)))
1141             {
1142               entries_found++;
1143               add_peer_to_blacklist (&pid,
1144                                      transport_name);
1145             }
1146           else
1147             {
1148               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1149                           _("Found myself `%s' in blacklist (useless, ignored)\n"),
1150                           GNUNET_i2s (&pid));
1151             }
1152         }
1153       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1154       GNUNET_free_non_null(transport_name);
1155       while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1156         pos++;
1157     }
1158   GNUNET_free (data);
1159   GNUNET_free (fn);
1160 }
1161
1162
1163 /**
1164  * Function called to notify a client about the socket being ready to
1165  * queue more data.  "buf" will be NULL and "size" zero if the socket
1166  * was closed for writing in the meantime.
1167  *
1168  * @param cls closure
1169  * @param size number of bytes available in buf
1170  * @param buf where the callee should write the message
1171  * @return number of bytes written to buf
1172  */
1173 static size_t
1174 transmit_to_client_callback (void *cls, size_t size, void *buf)
1175 {
1176   struct TransportClient *client = cls;
1177   struct ClientMessageQueueEntry *q;
1178   uint16_t msize;
1179   size_t tsize;
1180   const struct GNUNET_MessageHeader *msg;
1181   char *cbuf;
1182
1183   client->th = NULL;
1184   if (buf == NULL)
1185     {
1186       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187                   "Transmission to client failed, closing connection.\n");
1188       /* fatal error with client, free message queue! */
1189       while (NULL != (q = client->message_queue_head))
1190         {
1191           GNUNET_STATISTICS_update (stats,
1192                                     gettext_noop ("# bytes discarded (could not transmit to client)"),
1193                                     ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1194                                     GNUNET_NO);
1195           GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1196                                        client->message_queue_tail,
1197                                        q);
1198           GNUNET_free (q);
1199         }
1200       client->message_count = 0;
1201       return 0;
1202     }
1203   cbuf = buf;
1204   tsize = 0;
1205   while (NULL != (q = client->message_queue_head))
1206     {
1207       msg = (const struct GNUNET_MessageHeader *) &q[1];
1208       msize = ntohs (msg->size);
1209       if (msize + tsize > size)
1210         break;
1211 #if DEBUG_TRANSPORT
1212       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1213                   "Transmitting message of type %u to client.\n",
1214                   ntohs (msg->type));
1215 #endif
1216       GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1217                                    client->message_queue_tail,
1218                                    q);
1219       memcpy (&cbuf[tsize], msg, msize);
1220       tsize += msize;
1221       GNUNET_free (q);
1222       client->message_count--;
1223     }
1224   if (NULL != q)
1225     {
1226       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1227       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1228                                                         msize,
1229                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1230                                                         &transmit_to_client_callback,
1231                                                         client);
1232       GNUNET_assert (client->th != NULL);
1233     }
1234   return tsize;
1235 }
1236
1237
1238 /**
1239  * Convert an address to a string.
1240  *
1241  * @param plugin name of the plugin responsible for the address
1242  * @param addr binary address
1243  * @param addr_len number of bytes in addr
1244  * @return NULL on error, otherwise address string
1245  */
1246 static const char*
1247 a2s (const char *plugin,
1248      const void *addr,
1249      uint16_t addr_len)
1250 {
1251   struct TransportPlugin *p;
1252
1253   if (plugin == NULL)
1254     return NULL;
1255   p = find_transport (plugin);
1256   if (p == NULL)
1257     return NULL;
1258   return p->api->address_to_string (p->api->cls,
1259                                     addr,
1260                                     addr_len);
1261 }
1262
1263
1264 /**
1265  * Mark the given FAL entry as 'connected' (and hence preferred for
1266  * sending); also mark all others for the same peer as 'not connected'
1267  * (since only one can be preferred).
1268  *
1269  * @param fal address to set to 'connected'
1270  */
1271 static void
1272 mark_address_connected (struct ForeignAddressList *fal)
1273 {
1274   struct ForeignAddressList *pos;
1275   int cnt;
1276
1277   GNUNET_assert (GNUNET_YES == fal->validated);
1278   if (fal->connected == GNUNET_YES)
1279     return; /* nothing to do */
1280   cnt = GNUNET_YES;
1281   pos = fal->ready_list->addresses;
1282   while (pos != NULL)
1283     {
1284       if (GNUNET_YES == pos->connected)
1285         {
1286 #if DEBUG_TRANSPORT
1287           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288                       "Marking address `%s' as no longer connected (due to connect on other address)\n",
1289                       a2s (pos->ready_list->plugin->short_name,
1290                            pos->addr,
1291                            pos->addrlen));
1292 #endif
1293           GNUNET_break (cnt == GNUNET_YES);
1294           cnt = GNUNET_NO;
1295           pos->connected = GNUNET_NO;
1296           GNUNET_STATISTICS_update (stats,
1297                                     gettext_noop ("# connected addresses"),
1298                                     -1,
1299                                     GNUNET_NO);
1300         }
1301       pos = pos->next;
1302     }
1303   fal->connected = GNUNET_YES;
1304   if (GNUNET_YES == cnt)
1305     {
1306       GNUNET_STATISTICS_update (stats,
1307                                 gettext_noop ("# connected addresses"),
1308                                 1,
1309                                 GNUNET_NO);
1310     }
1311 }
1312
1313
1314 /**
1315  * Send the specified message to the specified client.  Since multiple
1316  * messages may be pending for the same client at a time, this code
1317  * makes sure that no message is lost.
1318  *
1319  * @param client client to transmit the message to
1320  * @param msg the message to send
1321  * @param may_drop can this message be dropped if the
1322  *        message queue for this client is getting far too large?
1323  */
1324 static void
1325 transmit_to_client (struct TransportClient *client,
1326                     const struct GNUNET_MessageHeader *msg, int may_drop)
1327 {
1328   struct ClientMessageQueueEntry *q;
1329   uint16_t msize;
1330
1331   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1332     {
1333       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1334                   _
1335                   ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1336                   ntohs (msg->type),
1337                   ntohs (msg->size),
1338                   client->message_count,
1339                   MAX_PENDING);
1340       GNUNET_STATISTICS_update (stats,
1341                                 gettext_noop ("# messages dropped due to slow client"),
1342                                 1,
1343                                 GNUNET_NO);
1344       return;
1345     }
1346   msize = ntohs (msg->size);
1347   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1348   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1349   memcpy (&q[1], msg, msize);
1350   GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1351                                      client->message_queue_tail,
1352                                      client->message_queue_tail,
1353                                      q);                                
1354   client->message_count++;
1355   if (client->th == NULL)
1356     {
1357       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1358                                                         msize,
1359                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1360                                                         &transmit_to_client_callback,
1361                                                         client);
1362       GNUNET_assert (client->th != NULL);
1363     }
1364 }
1365
1366
1367 /**
1368  * Transmit a 'SEND_OK' notification to the given client for the
1369  * given neighbour.
1370  *
1371  * @param client who to notify
1372  * @param n neighbour to notify about
1373  * @param result status code for the transmission request
1374  */
1375 static void
1376 transmit_send_ok (struct TransportClient *client,
1377                   struct NeighbourList *n,
1378                   int result)
1379 {
1380   struct SendOkMessage send_ok_msg;
1381
1382   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1383   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1384   send_ok_msg.success = htonl (result);
1385   send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1386   send_ok_msg.peer = n->id;
1387   transmit_to_client (client, &send_ok_msg.header, GNUNET_NO);
1388 }
1389
1390
1391 /**
1392  * Function called by the GNUNET_TRANSPORT_TransmitFunction
1393  * upon "completion" of a send request.  This tells the API
1394  * that it is now legal to send another message to the given
1395  * peer.
1396  *
1397  * @param cls closure, identifies the entry on the
1398  *            message queue that was transmitted and the
1399  *            client responsible for queueing the message
1400  * @param target the peer receiving the message
1401  * @param result GNUNET_OK on success, if the transmission
1402  *           failed, we should not tell the client to transmit
1403  *           more messages
1404  */
1405 static void
1406 transmit_send_continuation (void *cls,
1407                             const struct GNUNET_PeerIdentity *target,
1408                             int result)
1409 {
1410   struct MessageQueue *mq = cls;
1411   struct NeighbourList *n;
1412
1413   GNUNET_STATISTICS_update (stats,
1414                             gettext_noop ("# bytes pending with plugins"),
1415                             - (int64_t) mq->message_buf_size,
1416                             GNUNET_NO);
1417   if (result == GNUNET_OK)
1418     {
1419       GNUNET_STATISTICS_update (stats,
1420                                 gettext_noop ("# bytes successfully transmitted by plugins"),
1421                                 mq->message_buf_size,
1422                                 GNUNET_NO);
1423     }
1424   else
1425     {
1426       GNUNET_STATISTICS_update (stats,
1427                                 gettext_noop ("# bytes with transmission failure by plugins"),
1428                                 mq->message_buf_size,
1429                                 GNUNET_NO);
1430     }
1431   n = find_neighbour(&mq->neighbour_id);
1432   GNUNET_assert (n != NULL);
1433   if (mq->specific_address != NULL)
1434     {
1435       if (result == GNUNET_OK)
1436         {
1437           mq->specific_address->timeout =
1438             GNUNET_TIME_relative_to_absolute
1439             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1440           if (mq->specific_address->validated == GNUNET_YES)
1441             mark_address_connected (mq->specific_address);
1442         }
1443       else
1444         {
1445           if (mq->specific_address->connected != GNUNET_NO)
1446             {
1447 #if DEBUG_TRANSPORT
1448               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449                           "Marking address `%s' as no longer connected (due to transmission problem)\n",
1450                           a2s (mq->specific_address->ready_list->plugin->short_name,
1451                                mq->specific_address->addr,
1452                                mq->specific_address->addrlen));
1453 #endif
1454               GNUNET_STATISTICS_update (stats,
1455                                         gettext_noop ("# connected addresses"),
1456                                         -1,
1457                                         GNUNET_NO);
1458               mq->specific_address->connected = GNUNET_NO;
1459             }
1460         }
1461       if (! mq->internal_msg)
1462         mq->specific_address->in_transmit = GNUNET_NO;
1463     }
1464   if (mq->client != NULL)
1465     transmit_send_ok (mq->client, n, result);
1466   GNUNET_free (mq);
1467   try_transmission_to_peer (n);
1468 }
1469
1470
1471 /**
1472  * Find an address in any of the available transports for
1473  * the given neighbour that would be good for message
1474  * transmission.  This is essentially the transport selection
1475  * routine.
1476  *
1477  * @param neighbour for whom to select an address
1478  * @return selected address, NULL if we have none
1479  */
1480 struct ForeignAddressList *
1481 find_ready_address(struct NeighbourList *neighbour)
1482 {
1483   struct ReadyList *head = neighbour->plugins;
1484   struct ForeignAddressList *addresses;
1485   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1486   struct ForeignAddressList *best_address;
1487
1488   best_address = NULL;
1489   while (head != NULL)
1490     {
1491       addresses = head->addresses;
1492       while (addresses != NULL)
1493         {
1494           if ( (addresses->timeout.abs_value < now.abs_value) &&
1495                (addresses->connected == GNUNET_YES) )
1496             {
1497 #if DEBUG_TRANSPORT
1498               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499                           "Marking long-time inactive connection to `%4s' as down.\n",
1500                           GNUNET_i2s (&neighbour->id));
1501 #endif
1502               GNUNET_STATISTICS_update (stats,
1503                                         gettext_noop ("# connected addresses"),
1504                                         -1,
1505                                         GNUNET_NO);
1506               addresses->connected = GNUNET_NO;
1507             }
1508           addresses = addresses->next;
1509         }
1510
1511       addresses = head->addresses;
1512       while (addresses != NULL)
1513         {
1514 #if DEBUG_TRANSPORT > 1
1515           if (addresses->addr != NULL)
1516             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1517                         "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1518                         a2s (head->plugin->short_name,
1519                              addresses->addr,
1520                              addresses->addrlen),
1521                         GNUNET_i2s (&neighbour->id),
1522                         addresses->connected,
1523                         addresses->in_transmit,
1524                         addresses->validated,
1525                         addresses->connect_attempts,
1526                         (unsigned long long) addresses->timeout.abs_value,
1527                         (unsigned int) addresses->distance);
1528 #endif
1529           if ( ( (best_address == NULL) ||
1530                  (addresses->connected == GNUNET_YES) ||
1531                  (best_address->connected == GNUNET_NO) ) &&
1532                (addresses->in_transmit == GNUNET_NO) &&
1533                ( (best_address == NULL) ||
1534                  (addresses->latency.rel_value < best_address->latency.rel_value)) )
1535             best_address = addresses;
1536           /* FIXME: also give lower-latency addresses that are not
1537              connected a chance some times... */
1538           addresses = addresses->next;
1539         }
1540       head = head->next;
1541     }
1542   if (best_address != NULL)
1543     {
1544 #if DEBUG_TRANSPORT
1545       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546                   "Best address found (`%s') has latency of %llu ms.\n",
1547                   (best_address->addrlen > 0)
1548                   ? a2s (best_address->ready_list->plugin->short_name,
1549                        best_address->addr,
1550                        best_address->addrlen)
1551                   : "<inbound>",
1552                   best_address->latency.rel_value);
1553 #endif
1554     }
1555   else
1556     {
1557       GNUNET_STATISTICS_update (stats,
1558                                 gettext_noop ("# transmission attempts failed (no address)"),
1559                                 1,
1560                                 GNUNET_NO);
1561     }
1562   return best_address;
1563
1564 }
1565
1566
1567 /**
1568  * We should re-try transmitting to the given peer,
1569  * hopefully we've learned something in the meantime.
1570  */
1571 static void
1572 retry_transmission_task (void *cls,
1573                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1574 {
1575   struct NeighbourList *n = cls;
1576
1577   n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1578   try_transmission_to_peer (n);
1579 }
1580
1581
1582 /**
1583  * Check the ready list for the given neighbour and if a plugin is
1584  * ready for transmission (and if we have a message), do so!
1585  *
1586  * @param neighbour target peer for which to transmit
1587  */
1588 static void
1589 try_transmission_to_peer (struct NeighbourList *neighbour)
1590 {
1591   struct ReadyList *rl;
1592   struct MessageQueue *mq;
1593   struct GNUNET_TIME_Relative timeout;
1594   ssize_t ret;
1595   int force_address;
1596
1597   if (neighbour->messages_head == NULL)
1598     {
1599 #if DEBUG_TRANSPORT
1600       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1601                   "Transmission queue for `%4s' is empty\n",
1602                   GNUNET_i2s (&neighbour->id));
1603 #endif
1604       return;                     /* nothing to do */
1605     }
1606   rl = NULL;
1607   mq = neighbour->messages_head;
1608   force_address = GNUNET_YES;
1609   if (mq->specific_address == NULL)
1610     {
1611       mq->specific_address = find_ready_address(neighbour);
1612       GNUNET_STATISTICS_update (stats,
1613                                 gettext_noop ("# transport selected peer address freely"),
1614                                 1,
1615                                 GNUNET_NO);
1616       force_address = GNUNET_NO;
1617     }
1618   if (mq->specific_address == NULL)
1619     {
1620       GNUNET_STATISTICS_update (stats,
1621                                 gettext_noop ("# transport failed to selected peer address"),
1622                                 1,
1623                                 GNUNET_NO);
1624       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1625       if (timeout.rel_value == 0)
1626         {
1627 #if DEBUG_TRANSPORT
1628           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1629                       "No destination address available to transmit message of size %u to peer `%4s'\n",
1630                       mq->message_buf_size,
1631                       GNUNET_i2s (&mq->neighbour_id));
1632 #endif
1633           GNUNET_STATISTICS_update (stats,
1634                                     gettext_noop ("# bytes in message queue for other peers"),
1635                                     - (int64_t) mq->message_buf_size,
1636                                     GNUNET_NO);
1637           GNUNET_STATISTICS_update (stats,
1638                                     gettext_noop ("# bytes discarded (no destination address available)"),
1639                                     mq->message_buf_size,
1640                                     GNUNET_NO);
1641           if (mq->client != NULL)
1642             transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1643           GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1644                                        neighbour->messages_tail,
1645                                        mq);
1646           GNUNET_free (mq);
1647           return;               /* nobody ready */
1648         }
1649       GNUNET_STATISTICS_update (stats,
1650                                 gettext_noop ("# message delivery deferred (no address)"),
1651                                 1,
1652                                 GNUNET_NO);
1653       if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1654         GNUNET_SCHEDULER_cancel (neighbour->retry_task);
1655       neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (timeout,
1656                                                             &retry_transmission_task,
1657                                                             neighbour);
1658 #if DEBUG_TRANSPORT
1659       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1660                   "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1661                   mq->message_buf_size,
1662                   GNUNET_i2s (&mq->neighbour_id),
1663                   timeout.rel_value);
1664 #endif
1665       /* FIXME: might want to trigger peerinfo lookup here
1666          (unless that's already pending...) */
1667       return;
1668     }
1669   GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1670                                neighbour->messages_tail,
1671                                mq);
1672   if (mq->specific_address->connected == GNUNET_NO)
1673     mq->specific_address->connect_attempts++;
1674   rl = mq->specific_address->ready_list;
1675   mq->plugin = rl->plugin;
1676   if (!mq->internal_msg)
1677     mq->specific_address->in_transmit = GNUNET_YES;
1678 #if DEBUG_TRANSPORT
1679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1681               mq->message_buf_size,
1682               GNUNET_i2s (&neighbour->id),
1683               (mq->specific_address->addr != NULL)
1684               ? a2s (mq->plugin->short_name,
1685                      mq->specific_address->addr,
1686                      mq->specific_address->addrlen)
1687               : "<inbound>",
1688               rl->plugin->short_name);
1689 #endif
1690   GNUNET_STATISTICS_update (stats,
1691                             gettext_noop ("# bytes in message queue for other peers"),
1692                             - (int64_t) mq->message_buf_size,
1693                             GNUNET_NO);
1694   GNUNET_STATISTICS_update (stats,
1695                             gettext_noop ("# bytes pending with plugins"),
1696                             mq->message_buf_size,
1697                             GNUNET_NO);
1698   ret = rl->plugin->api->send (rl->plugin->api->cls,
1699                                &mq->neighbour_id,
1700                                mq->message_buf,
1701                                mq->message_buf_size,
1702                                mq->priority,
1703                                GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1704                                mq->specific_address->session,
1705                                mq->specific_address->addr,
1706                                mq->specific_address->addrlen,
1707                                force_address,
1708                                &transmit_send_continuation, mq);
1709   if (ret == -1)
1710     {
1711       /* failure, but 'send' would not call continuation in this case,
1712          so we need to do it here! */
1713       transmit_send_continuation (mq,
1714                                   &mq->neighbour_id,
1715                                   GNUNET_SYSERR);
1716     }
1717 }
1718
1719
1720 /**
1721  * Send the specified message to the specified peer.
1722  *
1723  * @param client source of the transmission request (can be NULL)
1724  * @param peer_address ForeignAddressList where we should send this message
1725  * @param priority how important is the message
1726  * @param timeout how long do we have to transmit?
1727  * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1728  * @param message_buf_size total size of all messages in message_buf
1729  * @param is_internal is this an internal message; these are pre-pended and
1730  *                    also do not count for plugins being "ready" to transmit
1731  * @param neighbour handle to the neighbour for transmission
1732  */
1733 static void
1734 transmit_to_peer (struct TransportClient *client,
1735                   struct ForeignAddressList *peer_address,
1736                   unsigned int priority,
1737                   struct GNUNET_TIME_Relative timeout,
1738                   const char *message_buf,
1739                   size_t message_buf_size,
1740                   int is_internal, struct NeighbourList *neighbour)
1741 {
1742   struct MessageQueue *mq;
1743
1744 #if EXTRA_CHECKS
1745   if (client != NULL)
1746     {
1747       /* check for duplicate submission */
1748       mq = neighbour->messages_head;
1749       while (NULL != mq)
1750         {
1751           if (mq->client == client)
1752             {
1753               /* client transmitted to same peer twice
1754                  before getting SEND_OK! */
1755               GNUNET_break (0);
1756               return;
1757             }
1758           mq = mq->next;
1759         }
1760     }
1761 #endif
1762   GNUNET_STATISTICS_update (stats,
1763                             gettext_noop ("# bytes in message queue for other peers"),
1764                             message_buf_size,
1765                             GNUNET_NO);
1766   mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1767   mq->specific_address = peer_address;
1768   mq->client = client;
1769   /* FIXME: this memcpy can be up to 7% of our total runtime! */
1770   memcpy (&mq[1], message_buf, message_buf_size);
1771   mq->message_buf = (const char*) &mq[1];
1772   mq->message_buf_size = message_buf_size;
1773   memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1774   mq->internal_msg = is_internal;
1775   mq->priority = priority;
1776   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1777   if (is_internal)
1778     GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1779                                  neighbour->messages_tail,
1780                                  mq);
1781   else
1782     GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1783                                        neighbour->messages_tail,
1784                                        neighbour->messages_tail,
1785                                        mq);
1786   try_transmission_to_peer (neighbour);
1787 }
1788
1789
1790 /**
1791  * FIXME: document.
1792  */
1793 struct GeneratorContext
1794 {
1795   struct TransportPlugin *plug_pos;
1796   struct OwnAddressList *addr_pos;
1797   struct GNUNET_TIME_Absolute expiration;
1798 };
1799
1800
1801 /**
1802  * FIXME: document.
1803  */
1804 static size_t
1805 address_generator (void *cls, size_t max, void *buf)
1806 {
1807   struct GeneratorContext *gc = cls;
1808   size_t ret;
1809
1810   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1811     {
1812       gc->plug_pos = gc->plug_pos->next;
1813       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1814     }
1815   if (NULL == gc->plug_pos)
1816     {
1817
1818       return 0;
1819     }
1820   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1821                                   gc->expiration,
1822                                   &gc->addr_pos[1],
1823                                   gc->addr_pos->addrlen, buf, max);
1824   gc->addr_pos = gc->addr_pos->next;
1825   return ret;
1826 }
1827
1828
1829 /**
1830  * Construct our HELLO message from all of the addresses of
1831  * all of the transports.
1832  */
1833 static void
1834 refresh_hello ()
1835 {
1836   struct GNUNET_HELLO_Message *hello;
1837   struct TransportClient *cpos;
1838   struct NeighbourList *npos;
1839   struct GeneratorContext gc;
1840
1841   gc.plug_pos = plugins;
1842   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1843   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1844   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1845 #if DEBUG_TRANSPORT
1846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1847               "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1848 #endif
1849   GNUNET_STATISTICS_update (stats,
1850                             gettext_noop ("# refreshed my HELLO"),
1851                             1,
1852                             GNUNET_NO);
1853   cpos = clients;
1854   while (cpos != NULL)
1855     {
1856       transmit_to_client (cpos,
1857                           (const struct GNUNET_MessageHeader *) hello,
1858                           GNUNET_NO);
1859       cpos = cpos->next;
1860     }
1861
1862   GNUNET_free_non_null (our_hello);
1863   our_hello = hello;
1864   GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1865   npos = neighbours;
1866   while (npos != NULL)
1867     {
1868 #if DEBUG_TRANSPORT
1869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1870                   "Transmitting updated `%s' to neighbour `%4s'\n",
1871                   "HELLO", GNUNET_i2s (&npos->id));
1872 #endif
1873       GNUNET_STATISTICS_update (stats,
1874                                 gettext_noop ("# transmitted my HELLO to other peers"),
1875                                 1,
1876                                 GNUNET_NO);
1877       transmit_to_peer (NULL, NULL, 0,
1878                         HELLO_ADDRESS_EXPIRATION,
1879                         (const char *) our_hello,
1880                         GNUNET_HELLO_size(our_hello),
1881                         GNUNET_NO, npos);
1882       npos = npos->next;
1883     }
1884 }
1885
1886
1887 /**
1888  * Task used to clean up expired addresses for a plugin.
1889  *
1890  * @param cls closure
1891  * @param tc context
1892  */
1893 static void
1894 expire_address_task (void *cls,
1895                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1896
1897
1898 /**
1899  * Update the list of addresses for this plugin,
1900  * expiring those that are past their expiration date.
1901  *
1902  * @param plugin addresses of which plugin should be recomputed?
1903  * @param fresh set to GNUNET_YES if a new address was added
1904  *        and we need to regenerate the HELLO even if nobody
1905  *        expired
1906  */
1907 static void
1908 update_addresses (struct TransportPlugin *plugin, 
1909                   int fresh)
1910 {
1911   static struct GNUNET_TIME_Absolute last_update;
1912   struct GNUNET_TIME_Relative min_remaining;
1913   struct GNUNET_TIME_Relative remaining;
1914   struct GNUNET_TIME_Absolute now;
1915   struct OwnAddressList *pos;
1916   struct OwnAddressList *prev;
1917   struct OwnAddressList *next;
1918   int expired;
1919
1920   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1921     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1922   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1923   now = GNUNET_TIME_absolute_get ();
1924   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1925   expired = (GNUNET_TIME_absolute_get_duration (last_update).rel_value > (HELLO_ADDRESS_EXPIRATION.rel_value / 4));
1926   prev = NULL;
1927   pos = plugin->addresses;
1928   while (pos != NULL)
1929     {
1930       next = pos->next;
1931       if (pos->expires.abs_value < now.abs_value)
1932         {
1933           expired = GNUNET_YES;
1934           if (prev == NULL)
1935             plugin->addresses = pos->next;
1936           else
1937             prev->next = pos->next;
1938           GNUNET_free (pos);
1939         }
1940       else
1941         {
1942           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1943           if (remaining.rel_value < min_remaining.rel_value)
1944             min_remaining = remaining;
1945           prev = pos;
1946         }
1947       pos = next;
1948     }
1949
1950   if (expired || fresh)
1951     {
1952       last_update = now;
1953       refresh_hello ();
1954     }
1955   min_remaining = GNUNET_TIME_relative_min (min_remaining,
1956                                             GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1957                                                                          2));
1958   plugin->address_update_task
1959     = GNUNET_SCHEDULER_add_delayed (min_remaining,
1960                                     &expire_address_task, plugin);
1961 }
1962
1963
1964 /**
1965  * Task used to clean up expired addresses for a plugin.
1966  *
1967  * @param cls closure
1968  * @param tc context
1969  */
1970 static void
1971 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1972 {
1973   struct TransportPlugin *plugin = cls;
1974
1975   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1976   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1977     update_addresses (plugin, GNUNET_NO);
1978 }
1979
1980
1981 /**
1982  * Iterator over hash map entries that NULLs the session of validation
1983  * entries that match the given session.
1984  *
1985  * @param cls closure (the 'struct Session*' to match against)
1986  * @param key current key code (peer ID, not used)
1987  * @param value value in the hash map ('struct ValidationEntry*')
1988  * @return GNUNET_YES (we should continue to iterate)
1989  */
1990 static int
1991 remove_session_validations (void *cls,
1992                             const GNUNET_HashCode * key,
1993                             void *value)
1994 {
1995   struct Session *session = cls;
1996   struct ValidationEntry *ve = value;
1997
1998   if (session == ve->session)
1999     ve->session = NULL;
2000   return GNUNET_YES;
2001 }
2002
2003
2004 /**
2005  * We've been disconnected from the other peer (for some
2006  * connection-oriented transport).  Either quickly
2007  * re-establish the connection or signal the disconnect
2008  * to the CORE.
2009  *
2010  * Only signal CORE level disconnect if ALL addresses
2011  * for the peer are exhausted.
2012  *
2013  * @param p overall plugin context
2014  * @param nl neighbour that was disconnected
2015  */
2016 static void
2017 try_fast_reconnect (struct TransportPlugin *p,
2018                     struct NeighbourList *nl)
2019 {
2020   /* FIXME-MW: fast reconnect / transport switching not implemented... */
2021   /* Note: the idea here is to hide problems with transports (or
2022      switching between plugins) from the core to eliminate the need to
2023      re-negotiate session keys and the like; OTOH, we should tell core
2024      quickly (much faster than timeout) `if a connection was lost and
2025      could not be re-established (i.e. other peer went down or is
2026      unable / refuses to communicate);
2027
2028      So we should consider:
2029      1) ideally: our own willingness / need to connect
2030      2) prior failures to connect to this peer (by plugin)
2031      3) ideally: reasons why other peer terminated (as far as knowable)
2032
2033      Most importantly, it must be POSSIBLE for another peer to terminate
2034      a connection for a while (without us instantly re-establishing it).
2035      Similarly, if another peer is gone we should quickly notify CORE.
2036      OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2037      on the other end), we should reconnect in such a way that BOTH CORE
2038      services never even notice.
2039      Furthermore, the same mechanism (or small variation) could be used
2040      to switch to a better-performing plugin (ATS).
2041
2042      Finally, this needs to be tested throughly... */                                                           
2043
2044   /*
2045    * GNUNET_NO in the call below makes transport disconnect the peer,
2046    * even if only a single address (out of say, six) went away.  This
2047    * function must be careful to ONLY disconnect if the peer is gone,
2048    * not just a specifi address.
2049    *
2050    * More specifically, half the places it was used had it WRONG.
2051    */
2052
2053   /* No reconnect, signal disconnect instead! */
2054   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055             "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2056             "try_fast_reconnect");
2057   disconnect_neighbour (nl, GNUNET_YES);
2058 }
2059
2060
2061 /**
2062  * Function that will be called whenever the plugin internally
2063  * cleans up a session pointer and hence the service needs to
2064  * discard all of those sessions as well.  Plugins that do not
2065  * use sessions can simply omit calling this function and always
2066  * use NULL wherever a session pointer is needed.
2067  *
2068  * @param cls closure
2069  * @param peer which peer was the session for
2070  * @param session which session is being destoyed
2071  */
2072 static void
2073 plugin_env_session_end  (void *cls,
2074                          const struct GNUNET_PeerIdentity *peer,
2075                          struct Session *session)
2076 {
2077   struct TransportPlugin *p = cls;
2078   struct NeighbourList *nl;
2079   struct ReadyList *rl;
2080   struct ForeignAddressList *pos;
2081   struct ForeignAddressList *prev;
2082
2083   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2084                                          &remove_session_validations,
2085                                          session);
2086   nl = find_neighbour (peer);
2087   if (nl == NULL)
2088     return; /* was never marked as connected */
2089   rl = nl->plugins;
2090   while (rl != NULL)
2091     {
2092       if (rl->plugin == p)
2093         break;
2094       rl = rl->next;
2095     }
2096   if (rl == NULL)
2097     return; /* was never marked as connected */
2098   prev = NULL;
2099   pos = rl->addresses;
2100   while ( (pos != NULL) &&
2101           (pos->session != session) )
2102     {
2103       prev = pos;
2104       pos = pos->next;
2105     }
2106   if (pos == NULL)
2107     return; /* was never marked as connected */
2108   pos->session = NULL;
2109   if (pos->addrlen != 0)
2110     {
2111       if (nl->received_pong != GNUNET_NO)
2112         try_fast_reconnect (p, nl);
2113       return;
2114     }
2115   /* was inbound connection, free 'pos' */
2116   if (prev == NULL)
2117     rl->addresses = pos->next;
2118   else
2119     prev->next = pos->next;
2120   if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2121     {
2122       GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2123       pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2124     }
2125   GNUNET_free (pos);
2126   if (nl->received_pong == GNUNET_NO)
2127     return; /* nothing to do, never connected... */
2128   /* check if we have any validated addresses left */
2129   pos = rl->addresses;
2130   while (pos != NULL)
2131     {
2132       if (pos->validated)
2133         {
2134           try_fast_reconnect (p, nl);
2135           return;
2136         }
2137       pos = pos->next;
2138     }
2139   /* no valid addresses left, signal disconnect! */
2140
2141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142             "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2143             "plugin_env_session_end");
2144   /* FIXME: This doesn't mean there are no addresses left for this PEER,
2145    * it means there aren't any left for this PLUGIN/PEER combination! So
2146    * calling disconnect_neighbor here with GNUNET_NO forces disconnect
2147    * when it isn't necessary. Using GNUNET_YES at least checks to see
2148    * if there are any addresses that work first, so as not to overdo it.
2149    * --NE
2150    */
2151   disconnect_neighbour (nl, GNUNET_YES);
2152 }
2153
2154
2155 /**
2156  * Function that must be called by each plugin to notify the
2157  * transport service about the addresses under which the transport
2158  * provided by the plugin can be reached.
2159  *
2160  * @param cls closure
2161  * @param name name of the transport that generated the address
2162  * @param addr one of the addresses of the host, NULL for the last address
2163  *        the specific address format depends on the transport
2164  * @param addrlen length of the address
2165  * @param expires when should this address automatically expire?
2166  */
2167 static void
2168 plugin_env_notify_address (void *cls,
2169                            const char *name,
2170                            const void *addr,
2171                            uint16_t addrlen,
2172                            struct GNUNET_TIME_Relative expires)
2173 {
2174   struct TransportPlugin *p = cls;
2175   struct OwnAddressList *al;
2176   struct GNUNET_TIME_Absolute abex;
2177
2178   GNUNET_assert (addr != NULL);
2179   abex = GNUNET_TIME_relative_to_absolute (expires);
2180   GNUNET_assert (p == find_transport (name));
2181   al = p->addresses;
2182   while (al != NULL)
2183     {
2184       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2185         {             
2186           al->expires = abex;
2187           update_addresses (p, GNUNET_NO);
2188           return;
2189         }
2190       al = al->next;
2191     }
2192
2193   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2194   al->next = p->addresses;
2195   p->addresses = al;
2196   al->expires = abex;
2197   al->addrlen = addrlen;
2198   memcpy (&al[1], addr, addrlen);
2199   update_addresses (p, GNUNET_YES);
2200 }
2201
2202
2203 /**
2204  * Notify all of our clients about a peer connecting.
2205  */
2206 static void
2207 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2208                         struct GNUNET_TIME_Relative latency,
2209                         uint32_t distance)
2210 {
2211   struct ConnectInfoMessage cim;
2212   struct TransportClient *cpos;
2213
2214 #if DEBUG_TRANSPORT
2215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216               "Notifying clients about connection from `%s'\n",
2217               GNUNET_i2s (peer));
2218 #endif
2219   GNUNET_STATISTICS_update (stats,
2220                             gettext_noop ("# peers connected"),
2221                             1,
2222                             GNUNET_NO);
2223   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2224   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2225   cim.distance = htonl (distance);
2226   cim.latency = GNUNET_TIME_relative_hton (latency);
2227   cim.ats_count = htonl(0);
2228   cim.ats.type  = htonl(0);
2229   cim.ats.value = htonl(0);
2230   fprintf (stderr,"%lu %u %lu ", sizeof (struct ConnectInfoMessage), ntohl(cim.ats_count), sizeof (struct GNUNET_TRANSPORT_ATS_Information));
2231   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
2232   cpos = clients;
2233   while (cpos != NULL)
2234     {
2235       transmit_to_client (cpos, &cim.header, GNUNET_NO);
2236       cpos = cpos->next;
2237     }
2238 }
2239
2240
2241 /**
2242  * Notify all of our clients about a peer disconnecting.
2243  */
2244 static void
2245 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2246 {
2247   struct DisconnectInfoMessage dim;
2248   struct TransportClient *cpos;
2249
2250 #if DEBUG_TRANSPORT
2251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2252               "Notifying clients about lost connection to `%s'\n",
2253               GNUNET_i2s (peer));
2254 #endif
2255   GNUNET_STATISTICS_update (stats,
2256                             gettext_noop ("# peers connected"),
2257                             -1,
2258                             GNUNET_NO);
2259   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2260   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2261   dim.reserved = htonl (0);
2262   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2263   cpos = clients;
2264   while (cpos != NULL)
2265     {
2266       transmit_to_client (cpos, &dim.header, GNUNET_NO);
2267       cpos = cpos->next;
2268     }
2269 }
2270
2271
2272 /**
2273  * Find a ForeignAddressList entry for the given neighbour
2274  * that matches the given address and transport.
2275  *
2276  * @param neighbour which peer we care about
2277  * @param tname name of the transport plugin
2278  * @param session session to look for, NULL for 'any'; otherwise
2279  *        can be used for the service to "learn" this session ID
2280  *        if 'addr' matches
2281  * @param addr binary address
2282  * @param addrlen length of addr
2283  * @return NULL if no such entry exists
2284  */
2285 static struct ForeignAddressList *
2286 find_peer_address(struct NeighbourList *neighbour,
2287                   const char *tname,
2288                   struct Session *session,
2289                   const char *addr,
2290                   uint16_t addrlen)
2291 {
2292   struct ReadyList *head;
2293   struct ForeignAddressList *pos;
2294
2295   head = neighbour->plugins;
2296   while (head != NULL)
2297     {
2298       if (0 == strcmp (tname, head->plugin->short_name))
2299         break;
2300       head = head->next;
2301     }
2302   if (head == NULL)
2303     return NULL;
2304   pos = head->addresses;
2305   while ( (pos != NULL) &&
2306           ( (pos->addrlen != addrlen) ||
2307             (memcmp(pos->addr, addr, addrlen) != 0) ) )
2308     {
2309       if ( (session != NULL) &&
2310            (pos->session == session) )
2311         return pos;
2312       pos = pos->next;
2313     }
2314   if ( (session != NULL) && (pos != NULL) )
2315     pos->session = session; /* learn it! */
2316   return pos;
2317 }
2318
2319
2320 /**
2321  * Get the peer address struct for the given neighbour and
2322  * address.  If it doesn't yet exist, create it.
2323  *
2324  * @param neighbour which peer we care about
2325  * @param tname name of the transport plugin
2326  * @param session session of the plugin, or NULL for none
2327  * @param addr binary address
2328  * @param addrlen length of addr
2329  * @return NULL if we do not have a transport plugin for 'tname'
2330  */
2331 static struct ForeignAddressList *
2332 add_peer_address (struct NeighbourList *neighbour,
2333                   const char *tname,
2334                   struct Session *session,
2335                   const char *addr,
2336                   uint16_t addrlen)
2337 {
2338   struct ReadyList *head;
2339   struct ForeignAddressList *ret;
2340
2341   ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2342   if (ret != NULL)
2343     return ret;
2344   head = neighbour->plugins;
2345
2346   while (head != NULL)
2347     {
2348       if (0 == strcmp (tname, head->plugin->short_name))
2349         break;
2350       head = head->next;
2351     }
2352   if (head == NULL)
2353     return NULL;
2354   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2355   ret->session = session;
2356   if (addrlen > 0)
2357     {
2358       ret->addr = (const char*) &ret[1];
2359       memcpy (&ret[1], addr, addrlen);
2360     }
2361   else
2362     {
2363       ret->addr = NULL;
2364     }
2365   ret->addrlen = addrlen;
2366   ret->expires = GNUNET_TIME_relative_to_absolute
2367     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2368   ret->latency = GNUNET_TIME_relative_get_forever();
2369   ret->distance = -1;
2370   ret->timeout = GNUNET_TIME_relative_to_absolute
2371     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2372   ret->ready_list = head;
2373   ret->next = head->addresses;
2374   head->addresses = ret;
2375   return ret;
2376 }
2377
2378
2379 /**
2380  * Closure for 'add_validated_address'.
2381  */
2382 struct AddValidatedAddressContext
2383 {
2384   /**
2385    * Entry that has been validated.
2386    */
2387   const struct ValidationEntry *ve;
2388
2389   /**
2390    * Flag set after we have added the address so
2391    * that we terminate the iteration next time.
2392    */
2393   int done;
2394 };
2395
2396
2397 /**
2398  * Callback function used to fill a buffer of max bytes with a list of
2399  * addresses in the format used by HELLOs.  Should use
2400  * "GNUNET_HELLO_add_address" as a helper function.
2401  *
2402  * @param cls the 'struct AddValidatedAddressContext' with the validated address
2403  * @param max maximum number of bytes that can be written to buf
2404  * @param buf where to write the address information
2405  * @return number of bytes written, 0 to signal the
2406  *         end of the iteration.
2407  */
2408 static size_t
2409 add_validated_address (void *cls,
2410                        size_t max, void *buf)
2411 {
2412   struct AddValidatedAddressContext *avac = cls;
2413   const struct ValidationEntry *ve = avac->ve;
2414
2415   if (GNUNET_YES == avac->done)
2416     return 0;
2417   avac->done = GNUNET_YES;
2418   return GNUNET_HELLO_add_address (ve->transport_name,
2419                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2420                                    ve->addr,
2421                                    ve->addrlen,
2422                                    buf,
2423                                    max);
2424 }
2425
2426
2427
2428 /**
2429  * Closure for 'check_address_exists'.
2430  */
2431 struct CheckAddressExistsClosure
2432 {
2433   /**
2434    * Address to check for.
2435    */
2436   const void *addr;
2437
2438   /**
2439    * Name of the transport.
2440    */
2441   const char *tname;
2442
2443   /**
2444    * Session, or NULL.
2445    */
2446   struct Session *session;
2447
2448   /**
2449    * Set to GNUNET_YES if the address exists.
2450    */
2451   int exists;
2452
2453   /**
2454    * Length of addr.
2455    */
2456   uint16_t addrlen;
2457
2458 };
2459
2460
2461 /**
2462  * Iterator over hash map entries.  Checks if the given
2463  * validation entry is for the same address as what is given
2464  * in the closure.
2465  *
2466  * @param cls the 'struct CheckAddressExistsClosure*'
2467  * @param key current key code (ignored)
2468  * @param value value in the hash map ('struct ValidationEntry')
2469  * @return GNUNET_YES if we should continue to
2470  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2471  */
2472 static int
2473 check_address_exists (void *cls,
2474                       const GNUNET_HashCode * key,
2475                       void *value)
2476 {
2477   struct CheckAddressExistsClosure *caec = cls;
2478   struct ValidationEntry *ve = value;
2479
2480   if ( (0 == strcmp (caec->tname,
2481                      ve->transport_name)) &&
2482        (caec->addrlen == ve->addrlen) &&
2483        (0 == memcmp (caec->addr,
2484                      ve->addr,
2485                      caec->addrlen)) )
2486     {
2487       caec->exists = GNUNET_YES;
2488       return GNUNET_NO;
2489     }
2490   if ( (ve->session != NULL) &&
2491        (caec->session == ve->session) )
2492     {
2493       caec->exists = GNUNET_YES;
2494       return GNUNET_NO;
2495     }
2496   return GNUNET_YES;
2497 }
2498
2499
2500
2501 /**
2502  * Iterator to free entries in the validation_map.
2503  *
2504  * @param cls closure (unused)
2505  * @param key current key code
2506  * @param value value in the hash map (validation to abort)
2507  * @return GNUNET_YES (always)
2508  */
2509 static int
2510 abort_validation (void *cls,
2511                   const GNUNET_HashCode * key,
2512                   void *value)
2513 {
2514   struct ValidationEntry *va = value;
2515
2516   if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2517     GNUNET_SCHEDULER_cancel (va->timeout_task);
2518   GNUNET_free (va->transport_name);
2519   if (va->chvc != NULL)
2520     {
2521       va->chvc->ve_count--;
2522       if (va->chvc->ve_count == 0)
2523         {
2524           GNUNET_CONTAINER_DLL_remove (chvc_head,
2525                                        chvc_tail,
2526                                        va->chvc);
2527           GNUNET_free (va->chvc);
2528         }
2529       va->chvc = NULL;
2530     }
2531   GNUNET_free (va);
2532   return GNUNET_YES;
2533 }
2534
2535
2536 /**
2537  * HELLO validation cleanup task (validation failed).
2538  *
2539  * @param cls the 'struct ValidationEntry' that failed
2540  * @param tc scheduler context (unused)
2541  */
2542 static void
2543 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2544 {
2545   struct ValidationEntry *va = cls;
2546   struct GNUNET_PeerIdentity pid;
2547
2548   va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2549   GNUNET_STATISTICS_update (stats,
2550                             gettext_noop ("# address validation timeouts"),
2551                             1,
2552                             GNUNET_NO);
2553   GNUNET_CRYPTO_hash (&va->publicKey,
2554                       sizeof (struct
2555                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2556                       &pid.hashPubKey);
2557   GNUNET_break (GNUNET_OK ==
2558                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2559                                                       &pid.hashPubKey,
2560                                                       va));
2561   abort_validation (NULL, NULL, va);
2562 }
2563
2564
2565 static void
2566 neighbour_timeout_task (void *cls,
2567                        const struct GNUNET_SCHEDULER_TaskContext *tc)
2568 {
2569   struct NeighbourList *n = cls;
2570
2571 #if DEBUG_TRANSPORT
2572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2573               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2574 #endif
2575   GNUNET_STATISTICS_update (stats,
2576                             gettext_noop ("# disconnects due to timeout"),
2577                             1,
2578                             GNUNET_NO);
2579   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2580   disconnect_neighbour (n, GNUNET_NO);
2581 }
2582
2583
2584 /**
2585  * Schedule the job that will cause us to send a PING to the
2586  * foreign address to evaluate its validity and latency.
2587  *
2588  * @param fal address to PING
2589  */
2590 static void
2591 schedule_next_ping (struct ForeignAddressList *fal);
2592
2593
2594 /**
2595  * Add the given address to the list of foreign addresses
2596  * available for the given peer (check for duplicates).
2597  *
2598  * @param cls the respective 'struct NeighbourList' to update
2599  * @param tname name of the transport
2600  * @param expiration expiration time
2601  * @param addr the address
2602  * @param addrlen length of the address
2603  * @return GNUNET_OK (always)
2604  */
2605 static int
2606 add_to_foreign_address_list (void *cls,
2607                              const char *tname,
2608                              struct GNUNET_TIME_Absolute expiration,
2609                              const void *addr,
2610                              uint16_t addrlen)
2611 {
2612   struct NeighbourList *n = cls;
2613   struct ForeignAddressList *fal;
2614   int try;
2615
2616   GNUNET_STATISTICS_update (stats,
2617                             gettext_noop ("# valid peer addresses returned by PEERINFO"),
2618                             1,
2619                             GNUNET_NO);
2620   try = GNUNET_NO;
2621   fal = find_peer_address (n, tname, NULL, addr, addrlen);
2622   if (fal == NULL)
2623     {
2624 #if DEBUG_TRANSPORT_HELLO
2625       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626                   "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2627                   a2s (tname, addr, addrlen),
2628                   tname,
2629                   GNUNET_i2s (&n->id),
2630                   expiration.abs_value);
2631 #endif
2632       fal = add_peer_address (n, tname, NULL, addr, addrlen);
2633       if (fal == NULL)
2634         {
2635           GNUNET_STATISTICS_update (stats,
2636                                     gettext_noop ("# previously validated addresses lacking transport"),
2637                                     1,
2638                                     GNUNET_NO);
2639         }
2640       else
2641         {
2642           fal->expires = GNUNET_TIME_absolute_max (expiration,
2643                                                    fal->expires);
2644           schedule_next_ping (fal);
2645         }
2646       try = GNUNET_YES;
2647     }
2648   else
2649     {
2650       fal->expires = GNUNET_TIME_absolute_max (expiration,
2651                                                fal->expires);
2652     }
2653   if (fal == NULL)
2654     {
2655       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2656                   "Failed to add new address for `%4s'\n",
2657                   GNUNET_i2s (&n->id));
2658       return GNUNET_OK;
2659     }
2660   if (fal->validated == GNUNET_NO)
2661     {
2662       fal->validated = GNUNET_YES;
2663       GNUNET_STATISTICS_update (stats,
2664                                 gettext_noop ("# peer addresses considered valid"),
2665                                 1,
2666                                 GNUNET_NO);
2667     }
2668   if (try == GNUNET_YES)
2669     {
2670       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2671                   "Have new addresses, will try to trigger transmissions.\n");
2672       try_transmission_to_peer (n);
2673     }
2674   return GNUNET_OK;
2675 }
2676
2677
2678 /**
2679  * Add addresses in validated HELLO "h" to the set of addresses
2680  * we have for this peer.
2681  *
2682  * @param cls closure ('struct NeighbourList*')
2683  * @param peer id of the peer, NULL for last call
2684  * @param h hello message for the peer (can be NULL)
2685  */
2686 static void
2687 add_hello_for_peer (void *cls,
2688                     const struct GNUNET_PeerIdentity *peer,
2689                     const struct GNUNET_HELLO_Message *h)
2690 {
2691   struct NeighbourList *n = cls;
2692
2693   if (peer == NULL)
2694     {
2695       GNUNET_STATISTICS_update (stats,
2696                                 gettext_noop ("# outstanding peerinfo iterate requests"),
2697                                 -1,
2698                                 GNUNET_NO);
2699       n->piter = NULL;
2700       return;
2701     }
2702   if (h == NULL)
2703     return; /* no HELLO available */
2704 #if DEBUG_TRANSPORT
2705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2706               "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2707               "HELLO",
2708               GNUNET_i2s (peer));
2709 #endif
2710   if (GNUNET_YES != n->public_key_valid)
2711     {
2712       GNUNET_HELLO_get_key (h, &n->publicKey);
2713       n->public_key_valid = GNUNET_YES;
2714     }
2715   GNUNET_HELLO_iterate_addresses (h,
2716                                   GNUNET_NO,
2717                                   &add_to_foreign_address_list,
2718                                   n);
2719 }
2720
2721
2722 /**
2723  * Create a fresh entry in our neighbour list for the given peer.
2724  * Will try to transmit our current HELLO to the new neighbour.
2725  * Do not call this function directly, use 'setup_peer_check_blacklist.
2726  *
2727  * @param peer the peer for which we create the entry
2728  * @param do_hello should we schedule transmitting a HELLO
2729  * @return the new neighbour list entry
2730  */
2731 static struct NeighbourList *
2732 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2733                      int do_hello)
2734 {
2735   struct NeighbourList *n;
2736   struct TransportPlugin *tp;
2737   struct ReadyList *rl;
2738
2739 #if DEBUG_TRANSPORT
2740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2741               "Setting up state for neighbour `%4s'\n",
2742               GNUNET_i2s (peer));
2743 #endif
2744   GNUNET_assert (our_hello != NULL);
2745   GNUNET_STATISTICS_update (stats,
2746                             gettext_noop ("# active neighbours"),
2747                             1,
2748                             GNUNET_NO);
2749   n = GNUNET_malloc (sizeof (struct NeighbourList));
2750   n->next = neighbours;
2751   neighbours = n;
2752   n->id = *peer;
2753   n->peer_timeout =
2754     GNUNET_TIME_relative_to_absolute
2755     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2756   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2757                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2758                                  MAX_BANDWIDTH_CARRY_S);
2759   tp = plugins;
2760   while (tp != NULL)
2761     {
2762       if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2763         {
2764           rl = GNUNET_malloc (sizeof (struct ReadyList));
2765           rl->neighbour = n;
2766           rl->next = n->plugins;
2767           n->plugins = rl;
2768           rl->plugin = tp;
2769           rl->addresses = NULL;
2770         }
2771       tp = tp->next;
2772     }
2773   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2774   n->distance = -1;
2775   n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2776                                                   &neighbour_timeout_task, n);
2777   if (do_hello)
2778     {
2779       GNUNET_STATISTICS_update (stats,
2780                                 gettext_noop ("# peerinfo new neighbor iterate requests"),
2781                                 1,
2782                                 GNUNET_NO);
2783       GNUNET_STATISTICS_update (stats,
2784                                 gettext_noop ("# outstanding peerinfo iterate requests"),
2785                                 1,
2786                                 GNUNET_NO);
2787       n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2788                                           GNUNET_TIME_UNIT_FOREVER_REL,
2789                                           &add_hello_for_peer, n);
2790
2791       GNUNET_STATISTICS_update (stats,
2792                                 gettext_noop ("# HELLO's sent to new neighbors"),
2793                                 1,
2794                                 GNUNET_NO);
2795       transmit_to_peer (NULL, NULL, 0,
2796                         HELLO_ADDRESS_EXPIRATION,
2797                         (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2798                         GNUNET_NO, n);
2799     }
2800   return n;
2801 }
2802
2803
2804 /**
2805  * Function called after we have checked if communicating
2806  * with a given peer is acceptable.
2807  *
2808  * @param cls closure
2809  * @param n NULL if communication is not acceptable
2810  */
2811 typedef void (*SetupContinuation)(void *cls,
2812                                   struct NeighbourList *n);
2813
2814
2815 /**
2816  * Information kept for each client registered to perform
2817  * blacklisting.
2818  */
2819 struct Blacklisters
2820 {
2821   /**
2822    * This is a linked list.
2823    */
2824   struct Blacklisters *next;
2825
2826   /**
2827    * This is a linked list.
2828    */
2829   struct Blacklisters *prev;
2830
2831   /**
2832    * Client responsible for this entry.
2833    */
2834   struct GNUNET_SERVER_Client *client;
2835
2836   /**
2837    * Blacklist check that we're currently performing.
2838    */
2839   struct BlacklistCheck *bc;
2840
2841 };
2842
2843
2844 /**
2845  * Head of DLL of blacklisting clients.
2846  */
2847 static struct Blacklisters *bl_head;
2848
2849 /**
2850  * Tail of DLL of blacklisting clients.
2851  */
2852 static struct Blacklisters *bl_tail;
2853
2854
2855 /**
2856  * Context we use when performing a blacklist check.
2857  */
2858 struct BlacklistCheck
2859 {
2860
2861   /**
2862    * This is a linked list.
2863    */
2864   struct BlacklistCheck *next;
2865
2866   /**
2867    * This is a linked list.
2868    */
2869   struct BlacklistCheck *prev;
2870
2871   /**
2872    * Peer being checked.
2873    */
2874   struct GNUNET_PeerIdentity peer;
2875
2876   /**
2877    * Option for setup neighbour afterwards.
2878    */
2879   int do_hello;
2880
2881   /**
2882    * Continuation to call with the result.
2883    */
2884   SetupContinuation cont;
2885
2886   /**
2887    * Closure for cont.
2888    */
2889   void *cont_cls;
2890
2891   /**
2892    * Current transmission request handle for this client, or NULL if no
2893    * request is pending.
2894    */
2895   struct GNUNET_CONNECTION_TransmitHandle *th;
2896
2897   /**
2898    * Our current position in the blacklisters list.
2899    */
2900   struct Blacklisters *bl_pos;
2901
2902   /**
2903    * Current task performing the check.
2904    */
2905   GNUNET_SCHEDULER_TaskIdentifier task;
2906
2907 };
2908
2909 /**
2910  * Head of DLL of active blacklisting queries.
2911  */
2912 static struct BlacklistCheck *bc_head;
2913
2914 /**
2915  * Tail of DLL of active blacklisting queries.
2916  */
2917 static struct BlacklistCheck *bc_tail;
2918
2919
2920 /**
2921  * Perform next action in the blacklist check.
2922  *
2923  * @param cls the 'struct BlacklistCheck*'
2924  * @param tc unused
2925  */
2926 static void
2927 do_blacklist_check (void *cls,
2928                     const struct GNUNET_SCHEDULER_TaskContext *tc);
2929
2930
2931 /**
2932  * Transmit blacklist query to the client.
2933  *
2934  * @param cls the 'struct BlacklistCheck'
2935  * @param size number of bytes allowed
2936  * @param buf where to copy the message
2937  * @return number of bytes copied to buf
2938  */
2939 static size_t
2940 transmit_blacklist_message (void *cls,
2941                             size_t size,
2942                             void *buf)
2943 {
2944   struct BlacklistCheck *bc = cls;
2945   struct Blacklisters *bl;
2946   struct BlacklistMessage bm;
2947
2948   bc->th = NULL;
2949   if (size == 0)
2950     {
2951       GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2952       bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
2953                                            bc);
2954       return 0;
2955     }
2956   bl = bc->bl_pos;
2957   bm.header.size = htons (sizeof (struct BlacklistMessage));
2958   bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
2959   bm.is_allowed = htonl (0);
2960   bm.peer = bc->peer;
2961   memcpy (buf, &bm, sizeof (bm));
2962   GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
2963   return sizeof (bm);
2964 }
2965
2966
2967 /**
2968  * Perform next action in the blacklist check.
2969  *
2970  * @param cls the 'struct BlacklistCheck*'
2971  * @param tc unused
2972  */
2973 static void
2974 do_blacklist_check (void *cls,
2975                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2976 {
2977   struct BlacklistCheck *bc = cls;
2978   struct Blacklisters *bl;
2979
2980   bc->task = GNUNET_SCHEDULER_NO_TASK;
2981   bl = bc->bl_pos;
2982   if (bl == NULL)
2983     {
2984       bc->cont (bc->cont_cls,
2985                 setup_new_neighbour (&bc->peer, bc->do_hello));         
2986       GNUNET_free (bc);
2987       return;
2988     }
2989   if (bl->bc == NULL)
2990     {
2991       bl->bc = bc;
2992       bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
2993                                                     sizeof (struct BlacklistMessage),
2994                                                     GNUNET_TIME_UNIT_FOREVER_REL,
2995                                                     &transmit_blacklist_message,
2996                                                     bc);
2997     }
2998 }
2999
3000
3001 /**
3002  * Obtain a 'struct NeighbourList' for the given peer.  If such an entry
3003  * does not yet exist, check the blacklist.  If the blacklist says creating
3004  * one is acceptable, create one and call the continuation; otherwise
3005  * call the continuation with NULL.
3006  *
3007  * @param peer peer to setup or look up a struct NeighbourList for
3008  * @param do_hello should we also schedule sending our HELLO to the peer
3009  *        if this is a new record
3010  * @param cont function to call with the 'struct NeigbhbourList*'
3011  * @param cont_cls closure for cont
3012  */
3013 static void
3014 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3015                             int do_hello,
3016                             SetupContinuation cont,
3017                             void *cont_cls)
3018 {
3019   struct NeighbourList *n;
3020   struct BlacklistCheck *bc;
3021
3022   n = find_neighbour(peer);
3023   if (n != NULL)
3024     {
3025       if (cont != NULL)
3026         cont (cont_cls, n);
3027       return;
3028     }
3029   if (bl_head == NULL)
3030     {
3031       if (cont != NULL)
3032         cont (cont_cls, setup_new_neighbour (peer, do_hello));
3033       else
3034         setup_new_neighbour(peer, do_hello);
3035       return;
3036     }
3037   bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3038   GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3039   bc->peer = *peer;
3040   bc->do_hello = do_hello;
3041   bc->cont = cont;
3042   bc->cont_cls = cont_cls;
3043   bc->bl_pos = bl_head;
3044   bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3045                                        bc);
3046 }
3047
3048
3049 /**
3050  * Function called with the result of querying a new blacklister about
3051  * it being allowed (or not) to continue to talk to an existing neighbour.
3052  *
3053  * @param cls the original 'struct NeighbourList'
3054  * @param n NULL if we need to disconnect
3055  */
3056 static void
3057 confirm_or_drop_neighbour (void *cls,
3058                            struct NeighbourList *n)
3059 {
3060   struct NeighbourList * orig = cls;
3061
3062   if (n == NULL)
3063     {
3064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3065               "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3066               "confirm_or_drop_neighboUr");
3067       disconnect_neighbour (orig, GNUNET_NO);
3068     }
3069 }
3070
3071
3072 /**
3073  * Handle a request to start a blacklist.
3074  *
3075  * @param cls closure (always NULL)
3076  * @param client identification of the client
3077  * @param message the actual message
3078  */
3079 static void
3080 handle_blacklist_init (void *cls,
3081                        struct GNUNET_SERVER_Client *client,
3082                        const struct GNUNET_MessageHeader *message)
3083 {
3084   struct Blacklisters *bl;
3085   struct BlacklistCheck *bc;
3086   struct NeighbourList *n;
3087
3088   bl = bl_head;
3089   while (bl != NULL)
3090     {
3091       if (bl->client == client)
3092         {
3093           GNUNET_break (0);
3094           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3095           return;
3096         }
3097       bl = bl->next;
3098     }
3099   bl = GNUNET_malloc (sizeof (struct Blacklisters));
3100   bl->client = client;
3101   GNUNET_SERVER_client_keep (client);
3102   GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3103   /* confirm that all existing connections are OK! */
3104   n = neighbours;
3105   while (NULL != n)
3106     {
3107       bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3108       GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3109       bc->peer = n->id;
3110       bc->do_hello = GNUNET_NO;
3111       bc->cont = &confirm_or_drop_neighbour;
3112       bc->cont_cls = n;
3113       bc->bl_pos = bl;
3114       if (n == neighbours) /* all would wait for the same client, no need to
3115                               create more than just the first task right now */
3116         bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3117                                              bc);
3118       n = n->next;
3119     }
3120 }
3121
3122
3123 /**
3124  * Handle a request to blacklist a peer.
3125  *
3126  * @param cls closure (always NULL)
3127  * @param client identification of the client
3128  * @param message the actual message
3129  */
3130 static void
3131 handle_blacklist_reply (void *cls,
3132                         struct GNUNET_SERVER_Client *client,
3133                         const struct GNUNET_MessageHeader *message)
3134 {
3135   const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3136   struct Blacklisters *bl;
3137   struct BlacklistCheck *bc;
3138
3139   bl = bl_head;
3140   while ( (bl != NULL) &&
3141           (bl->client != client) )
3142     bl = bl->next;
3143   if (bl == NULL)
3144     {
3145       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3146       return;
3147     }
3148   bc = bl->bc;
3149   bl->bc = NULL;
3150   if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3151     {
3152       bc->cont (bc->cont_cls, NULL);
3153       GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3154       GNUNET_free (bc);
3155     }
3156   else
3157     {
3158       bc->bl_pos = bc->bl_pos->next;
3159       bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3160                                            bc);
3161     }
3162   /* check if any other bc's are waiting for this blacklister */
3163   bc = bc_head;
3164   while (bc != NULL)
3165     {
3166       if ( (bc->bl_pos == bl) &&
3167            (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3168         bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3169                                              bc);
3170       bc = bc->next;
3171     }
3172 }
3173
3174
3175 /**
3176  * Send periodic PING messages to a given foreign address.
3177  *
3178  * @param cls our 'struct PeriodicValidationContext*'
3179  * @param tc task context
3180  */
3181 static void
3182 send_periodic_ping (void *cls,
3183                     const struct GNUNET_SCHEDULER_TaskContext *tc)
3184 {
3185   struct ForeignAddressList *peer_address = cls;
3186   struct TransportPlugin *tp;
3187   struct ValidationEntry *va;
3188   struct NeighbourList *neighbour;
3189   struct TransportPingMessage ping;
3190   struct CheckAddressExistsClosure caec;
3191   char * message_buf;
3192   uint16_t hello_size;
3193   size_t slen;
3194   size_t tsize;
3195
3196   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3197   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3198     return;
3199   tp = peer_address->ready_list->plugin;
3200   neighbour = peer_address->ready_list->neighbour;
3201   if (GNUNET_YES != neighbour->public_key_valid)
3202     {
3203       /* no public key yet, try again later */
3204       schedule_next_ping (peer_address);
3205       return;
3206     }
3207   caec.addr = peer_address->addr;
3208   caec.addrlen = peer_address->addrlen;
3209   caec.tname = tp->short_name;
3210   caec.session = peer_address->session;
3211   caec.exists = GNUNET_NO;
3212   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3213                                          &check_address_exists,
3214                                          &caec);
3215   if (caec.exists == GNUNET_YES)
3216     {
3217       /* During validation attempts we will likely trigger the other
3218          peer trying to validate our address which in turn will cause
3219          it to send us its HELLO, so we expect to hit this case rather
3220          frequently.  Only print something if we are very verbose. */
3221 #if DEBUG_TRANSPORT > 1
3222       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3223                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3224                   (peer_address->addr != NULL)
3225                   ? a2s (tp->short_name,
3226                          peer_address->addr,
3227                          peer_address->addrlen)
3228                   : "<inbound>",
3229                   tp->short_name,
3230                   GNUNET_i2s (&neighbour->id));
3231 #endif
3232       schedule_next_ping (peer_address);
3233       return;
3234     }
3235   va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3236   va->transport_name = GNUNET_strdup (tp->short_name);
3237   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3238                                             UINT_MAX);
3239   va->send_time = GNUNET_TIME_absolute_get();
3240   va->session = peer_address->session;
3241   if (peer_address->addr != NULL)
3242     {
3243       va->addr = (const void*) &va[1];
3244       memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3245       va->addrlen = peer_address->addrlen;
3246     }
3247   memcpy(&va->publicKey,
3248          &neighbour->publicKey,
3249          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3250
3251   va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3252                                                    &timeout_hello_validation,
3253                                                    va);
3254   GNUNET_CONTAINER_multihashmap_put (validation_map,
3255                                      &neighbour->id.hashPubKey,
3256                                      va,
3257                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3258
3259   if (peer_address->validated != GNUNET_YES)
3260     hello_size = GNUNET_HELLO_size(our_hello);
3261   else
3262     hello_size = 0;
3263
3264   tsize = sizeof(struct TransportPingMessage) + hello_size;
3265
3266   if (peer_address->addr != NULL)
3267     {
3268       slen = strlen (tp->short_name) + 1;
3269       tsize += slen + peer_address->addrlen;
3270     }
3271   else
3272     {
3273       slen = 0; /* make gcc happy */
3274     }
3275   message_buf = GNUNET_malloc(tsize);
3276   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3277   ping.challenge = htonl(va->challenge);
3278   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3279   if (peer_address->validated != GNUNET_YES)
3280     {
3281       memcpy(message_buf, our_hello, hello_size);
3282     }
3283
3284   if (peer_address->addr != NULL)
3285     {
3286       ping.header.size = htons(sizeof(struct TransportPingMessage) +
3287                                peer_address->addrlen +
3288                                slen);
3289       memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3290              tp->short_name,
3291              slen);
3292       memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3293              peer_address->addr,
3294              peer_address->addrlen);
3295     }
3296   else
3297     {
3298       ping.header.size = htons(sizeof(struct TransportPingMessage));
3299     }
3300
3301   memcpy(&message_buf[hello_size],
3302          &ping,
3303          sizeof(struct TransportPingMessage));
3304
3305 #if DEBUG_TRANSPORT_REVALIDATION
3306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3307               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3308               (peer_address->addr != NULL)
3309               ? a2s (peer_address->plugin->short_name,
3310                      peer_address->addr,
3311                      peer_address->addrlen)
3312               : "<inbound>",
3313               tp->short_name,
3314               GNUNET_i2s (&neighbour->id),
3315               "HELLO", hello_size,
3316               "PING");
3317 #endif
3318   if (peer_address->validated != GNUNET_YES)
3319     GNUNET_STATISTICS_update (stats,
3320                               gettext_noop ("# PING with HELLO messages sent"),
3321                               1,
3322                               GNUNET_NO);
3323   else
3324     GNUNET_STATISTICS_update (stats,
3325                               gettext_noop ("# PING without HELLO messages sent"),
3326                               1,
3327                               GNUNET_NO);
3328   GNUNET_STATISTICS_update (stats,
3329                             gettext_noop ("# PING messages sent for re-validation"),
3330                             1,
3331                             GNUNET_NO);
3332   transmit_to_peer (NULL, peer_address,
3333                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3334                     HELLO_VERIFICATION_TIMEOUT,
3335                     message_buf, tsize,
3336                     GNUNET_YES, neighbour);
3337   GNUNET_free(message_buf);
3338   schedule_next_ping (peer_address);
3339 }
3340
3341
3342 /**
3343  * Schedule the job that will cause us to send a PING to the
3344  * foreign address to evaluate its validity and latency.
3345  *
3346  * @param fal address to PING
3347  */
3348 static void
3349 schedule_next_ping (struct ForeignAddressList *fal)
3350 {
3351   struct GNUNET_TIME_Relative delay;
3352
3353   if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3354     return;
3355   delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3356   delay.rel_value /= 2; /* do before expiration */
3357   delay = GNUNET_TIME_relative_min (delay,
3358                                     LATENCY_EVALUATION_MAX_DELAY);
3359   if (GNUNET_YES != fal->estimated)
3360     {
3361       delay = GNUNET_TIME_UNIT_ZERO;
3362       fal->estimated = GNUNET_YES;
3363     }                           
3364   if (GNUNET_YES == fal->connected)
3365     {
3366       delay = GNUNET_TIME_relative_min (delay,
3367                                         CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3368     }
3369   /* FIXME: also adjust delay based on how close the last
3370      observed latency is to the latency of the best alternative */
3371   /* bound how fast we can go */
3372   delay = GNUNET_TIME_relative_max (delay,
3373                                     GNUNET_TIME_UNIT_SECONDS);
3374   /* randomize a bit (to avoid doing all at the same time) */
3375   delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3376   fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3377                                                       &send_periodic_ping,
3378                                                       fal);
3379 }
3380
3381
3382
3383
3384 /**
3385  * Function that will be called if we receive some payload
3386  * from another peer.
3387  *
3388  * @param message the payload
3389  * @param n peer who claimed to be the sender
3390  * @param ats ATS information
3391  * @param ats_count numbers of elements following the ats struct (excluding the 0-terminator)
3392  */
3393 static void
3394 handle_payload_message (const struct GNUNET_MessageHeader *message,
3395                         struct NeighbourList *n, struct GNUNET_TRANSPORT_ATS_Information *ats, uint32_t ats_count)
3396 {
3397   struct InboundMessage *im;
3398   struct TransportClient *cpos;
3399   uint16_t msize;
3400
3401   msize = ntohs (message->size);
3402   if (n->received_pong == GNUNET_NO)
3403     {
3404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3405                   "Received message of type %u and size %u from `%4s', but no pong yet!!\n",
3406                   ntohs (message->type),
3407                   ntohs (message->size),
3408                   GNUNET_i2s (&n->id));
3409       GNUNET_free_non_null (n->pre_connect_message_buffer);
3410       n->pre_connect_message_buffer = GNUNET_malloc (msize);
3411       memcpy (n->pre_connect_message_buffer, message, msize);
3412       return;
3413     }
3414
3415 #if DEBUG_TRANSPORT
3416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3417               "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3418               ntohs (message->type),
3419               ntohs (message->size),
3420               GNUNET_i2s (&n->id));
3421 #endif
3422   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3423                                                       (ssize_t) msize))
3424     {
3425       n->quota_violation_count++;
3426 #if DEBUG_TRANSPORT
3427       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,                      
3428                   "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3429                   n->in_tracker.available_bytes_per_s__,
3430                   n->quota_violation_count);
3431 #endif
3432       /* Discount 32k per violation */
3433       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3434                                         - 32 * 1024);           
3435     }
3436   else
3437     {
3438       if (n->quota_violation_count > 0)
3439         {
3440           /* try to add 32k back */
3441           GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3442                                             32 * 1024);
3443           n->quota_violation_count--;
3444         }
3445     }
3446   GNUNET_STATISTICS_update (stats,
3447                             gettext_noop ("# payload received from other peers"),
3448                             msize,
3449                             GNUNET_NO);
3450
3451   /* transmit message to all clients */
3452   fprintf(stderr,"handle_payload_message ats_count %u\n",ats_count);
3453   im = GNUNET_malloc (sizeof (struct InboundMessage) + ats_count * sizeof(struct GNUNET_TRANSPORT_ATS_Information) + msize);
3454   im->header.size = htons (sizeof (struct InboundMessage) +  ats_count * sizeof(struct GNUNET_TRANSPORT_ATS_Information) + msize);
3455   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3456   im->peer = n->id;
3457   im->ats_count = htonl(ats_count);
3458   /* insert ATS elements */
3459   memcpy (&(im->ats), ats, ats_count * sizeof(struct GNUNET_TRANSPORT_ATS_Information));
3460   /* insert ATS terminator */
3461   (&im->ats)[ats_count].type  = htonl(0);
3462   (&im->ats)[ats_count].value = htonl(0);
3463   /* insert msg after terminator */
3464   memcpy (&(&im->ats)[ats_count+1], message, msize);
3465
3466   cpos = clients;
3467   while (cpos != NULL)
3468     {
3469       transmit_to_client (cpos, &im->header, GNUNET_YES);
3470       cpos = cpos->next;
3471     }
3472   GNUNET_free (im);
3473 }
3474
3475
3476 /**
3477  * Iterator over hash map entries.  Checks if the given validation
3478  * entry is for the same challenge as what is given in the PONG.
3479  *
3480  * @param cls the 'struct TransportPongMessage*'
3481  * @param key peer identity
3482  * @param value value in the hash map ('struct ValidationEntry')
3483  * @return GNUNET_YES if we should continue to
3484  *         iterate (mismatch), GNUNET_NO if not (entry matched)
3485  */
3486 static int
3487 check_pending_validation (void *cls,
3488                           const GNUNET_HashCode * key,
3489                           void *value)
3490 {
3491   const struct TransportPongMessage *pong = cls;
3492   struct ValidationEntry *ve = value;
3493   struct AddValidatedAddressContext avac;
3494   unsigned int challenge = ntohl(pong->challenge);
3495   struct GNUNET_HELLO_Message *hello;
3496   struct GNUNET_PeerIdentity target;
3497   struct NeighbourList *n;
3498   struct ForeignAddressList *fal;
3499   struct OwnAddressList *oal;
3500   struct TransportPlugin *tp;
3501   struct GNUNET_MessageHeader *prem;
3502   uint16_t ps;
3503   const char *addr;
3504   size_t slen;
3505   size_t alen;
3506
3507   ps = ntohs (pong->header.size);
3508   if (ps < sizeof (struct TransportPongMessage))
3509     {
3510       GNUNET_break_op (0);
3511       return GNUNET_NO;
3512     }
3513   addr = (const char*) &pong[1];
3514   slen = strlen (ve->transport_name) + 1;
3515   if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
3516        (ve->challenge != challenge) ||
3517        (addr[slen-1] != '\0') ||
3518        (0 != strcmp (addr, ve->transport_name)) ||
3519        (ntohl (pong->purpose.size)
3520         != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3521         sizeof (uint32_t) +
3522         sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3523         sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
3524     {
3525       return GNUNET_YES;
3526     }
3527
3528   alen = ps - sizeof (struct TransportPongMessage) - slen;
3529   switch (ntohl (pong->purpose.purpose))
3530     {
3531     case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
3532       if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
3533            (0 != memcmp (&addr[slen],
3534                          ve->addr,
3535                          ve->addrlen)) )
3536         {
3537           return GNUNET_YES; /* different entry, keep trying! */
3538         }
3539       if (0 != memcmp (&pong->pid,
3540                        key,
3541                        sizeof (struct GNUNET_PeerIdentity)))
3542         {
3543           GNUNET_break_op (0);
3544           return GNUNET_NO;
3545         }
3546       if (GNUNET_OK !=
3547           GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
3548                                     &pong->purpose,
3549                                     &pong->signature,
3550                                     &ve->publicKey))
3551         {
3552           GNUNET_break_op (0);
3553           return GNUNET_NO;
3554         }
3555
3556 #if DEBUG_TRANSPORT
3557       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3558                   "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3559                   GNUNET_h2s (key),
3560                   a2s (ve->transport_name,
3561                        (const struct sockaddr *) ve->addr,
3562                        ve->addrlen),
3563                   ve->transport_name);
3564 #endif
3565       break;
3566     case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
3567       if (0 != memcmp (&pong->pid,
3568                          &my_identity,
3569                          sizeof (struct GNUNET_PeerIdentity)))
3570         {
3571           GNUNET_break_op (0);
3572           return GNUNET_NO;
3573         }
3574       if (ve->addrlen != 0)
3575         {
3576           /* must have been for a different validation entry */
3577           return GNUNET_YES;
3578         }
3579       tp = find_transport (ve->transport_name);
3580       if (tp == NULL)
3581         {
3582           GNUNET_break (0);
3583           return GNUNET_YES;
3584         }
3585       oal = tp->addresses;
3586       while (NULL != oal)
3587         {
3588           if ( (oal->addrlen == alen) &&
3589                (0 == memcmp (&oal[1],
3590                              &addr[slen],
3591                              alen)) )
3592             break;
3593           oal = oal->next;
3594         }
3595       if (oal == NULL)
3596         {
3597           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3598                       _("Not accepting PONG with address `%s' since I cannot confirm having this address.\n"),
3599                       a2s (ve->transport_name,
3600                            &addr[slen],
3601                            alen));
3602           return GNUNET_NO;     
3603         }
3604       if (GNUNET_OK !=
3605           GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
3606                                     &pong->purpose,
3607                                     &pong->signature,
3608                                     &ve->publicKey))
3609         {
3610           GNUNET_break_op (0);
3611           return GNUNET_NO;
3612         }
3613
3614 #if DEBUG_TRANSPORT
3615       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3616                   "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
3617                   GNUNET_h2s (key),
3618                   a2s (ve->transport_name,
3619                        &addr[slen],
3620                        alen),
3621                   ve->transport_name);
3622 #endif
3623       break;
3624     default:
3625       GNUNET_break_op (0);
3626       return GNUNET_NO;
3627     }
3628   if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
3629     {
3630       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3631                   _("Received expired signature.  Check system time.\n"));
3632       return GNUNET_NO;
3633     }
3634   GNUNET_STATISTICS_update (stats,
3635                             gettext_noop ("# address validation successes"),
3636                             1,
3637                             GNUNET_NO);
3638   /* create the updated HELLO */
3639   GNUNET_CRYPTO_hash (&ve->publicKey,
3640                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3641                       &target.hashPubKey);
3642   if (ve->addr != NULL)
3643     {
3644       avac.done = GNUNET_NO;
3645       avac.ve = ve;
3646       hello = GNUNET_HELLO_create (&ve->publicKey,
3647                                    &add_validated_address,
3648                                    &avac);
3649       GNUNET_PEERINFO_add_peer (peerinfo,
3650                                 hello);
3651       GNUNET_free (hello);
3652     }
3653   n = find_neighbour (&target);
3654   if (n != NULL)
3655     {
3656       n->publicKey = ve->publicKey;
3657       n->public_key_valid = GNUNET_YES;
3658       fal = add_peer_address (n,
3659                               ve->transport_name,
3660                               ve->session,
3661                               ve->addr,
3662                               ve->addrlen);
3663       GNUNET_assert (fal != NULL);
3664       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3665       fal->validated = GNUNET_YES;
3666       mark_address_connected (fal);
3667       GNUNET_STATISTICS_update (stats,
3668                                 gettext_noop ("# peer addresses considered valid"),
3669                                 1,
3670                                 GNUNET_NO);
3671       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3672       schedule_next_ping (fal);
3673       if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3674         n->latency = fal->latency;
3675       else
3676         n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
3677
3678       n->distance = fal->distance;
3679       if (GNUNET_NO == n->received_pong)
3680         {
3681           n->received_pong = GNUNET_YES;
3682           notify_clients_connect (&target, n->latency, n->distance);
3683           if (NULL != (prem = n->pre_connect_message_buffer))
3684             {
3685               n->pre_connect_message_buffer = NULL;
3686               struct GNUNET_TRANSPORT_ATS_Information * ats = GNUNET_malloc(2 * sizeof(struct GNUNET_TRANSPORT_ATS_Information));
3687               ats[0].type = htonl(GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
3688               if (n->latency.rel_value <= UINT32_MAX)
3689                   ats[0].value = htonl((uint32_t) n->latency.rel_value);
3690               else
3691                   ats[0].value = htonl(UINT32_MAX);
3692               ats[1].type  = htonl(GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
3693               ats[1].value = htonl(n->distance);
3694               //handle_payload_message (prem, n, NULL, 0);
3695               handle_payload_message (prem, n, ats, 2);
3696               GNUNET_free (ats);
3697               GNUNET_free (prem);
3698             }
3699         }
3700       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3701         {
3702           GNUNET_SCHEDULER_cancel (n->retry_task);
3703           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3704           try_transmission_to_peer (n);
3705         }
3706     }
3707
3708   /* clean up validation entry */
3709   GNUNET_assert (GNUNET_YES ==
3710                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
3711                                                        key,
3712                                                        ve));
3713   abort_validation (NULL, NULL, ve);
3714   return GNUNET_NO;
3715 }
3716
3717
3718 /**
3719  * Function that will be called if we receive a validation
3720  * of an address challenge that we transmitted to another
3721  * peer.  Note that the validation should only be considered
3722  * acceptable if the challenge matches AND if the sender
3723  * address is at least a plausible address for this peer
3724  * (otherwise we may be seeing a MiM attack).
3725  *
3726  * @param cls closure
3727  * @param message the pong message
3728  * @param peer who responded to our challenge
3729  * @param sender_address string describing our sender address (as observed
3730  *         by the other peer in binary format)
3731  * @param sender_address_len number of bytes in 'sender_address'
3732  */
3733 static void
3734 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3735              const struct GNUNET_PeerIdentity *peer,
3736              const char *sender_address,
3737              size_t sender_address_len)
3738 {
3739 #if DEBUG_TRANSPORT > 1
3740   /* we get tons of these that just get discarded, only log
3741      if we are quite verbose */
3742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3743               "Receiving `%s' message from `%4s'.\n", "PONG",
3744               GNUNET_i2s (peer));
3745 #endif
3746   GNUNET_STATISTICS_update (stats,
3747                             gettext_noop ("# PONG messages received"),
3748                             1,
3749                             GNUNET_NO);
3750   if (GNUNET_SYSERR !=
3751       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3752                                                   &peer->hashPubKey,
3753                                                   &check_pending_validation,
3754                                                   (void*) message))
3755     {
3756       /* This is *expected* to happen a lot since we send
3757          PONGs to *all* known addresses of the sender of
3758          the PING, so most likely we get multiple PONGs
3759          per PING, and all but the first PONG will end up
3760          here. So really we should not print anything here
3761          unless we want to be very, very verbose... */
3762 #if DEBUG_TRANSPORT > 2
3763       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3764                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3765                   "PONG",
3766                   GNUNET_i2s (peer),
3767                   "PING");
3768 #endif
3769       return;
3770     }
3771
3772 }
3773
3774
3775 /**
3776  * Try to validate a neighbour's address by sending him our HELLO and a PING.
3777  *
3778  * @param cls the 'struct ValidationEntry*'
3779  * @param neighbour neighbour to validate, NULL if validation failed
3780  */
3781 static void
3782 transmit_hello_and_ping (void *cls,
3783                          struct NeighbourList *neighbour)
3784 {
3785   struct ValidationEntry *va = cls;
3786   struct ForeignAddressList *peer_address;
3787   struct TransportPingMessage ping;
3788   uint16_t hello_size;
3789   size_t tsize;
3790   char * message_buf;
3791   struct GNUNET_PeerIdentity id;
3792   size_t slen;
3793
3794   GNUNET_CRYPTO_hash (&va->publicKey,
3795                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3796                       &id.hashPubKey);
3797   if (neighbour == NULL)
3798     {
3799       /* FIXME: stats... */
3800       GNUNET_break (GNUNET_OK ==
3801                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3802                                                           &id.hashPubKey,
3803                                                           va));
3804       abort_validation (NULL, NULL, va);
3805       return;
3806     }
3807   neighbour->publicKey = va->publicKey;
3808   neighbour->public_key_valid = GNUNET_YES;
3809   peer_address = add_peer_address (neighbour,
3810                                    va->transport_name, NULL,
3811                                    (const void*) &va[1],
3812                                    va->addrlen);
3813   if (peer_address == NULL)
3814     {
3815       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3816                   "Failed to add peer `%4s' for plugin `%s'\n",
3817                   GNUNET_i2s (&neighbour->id),
3818                   va->transport_name);
3819       GNUNET_break (GNUNET_OK ==
3820                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3821                                                           &id.hashPubKey,
3822                                                           va));
3823       abort_validation (NULL, NULL, va);
3824       return;
3825     }
3826   hello_size = GNUNET_HELLO_size(our_hello);
3827   slen = strlen(va->transport_name) + 1;
3828   tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
3829   message_buf = GNUNET_malloc(tsize);
3830   ping.challenge = htonl(va->challenge);
3831   ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
3832   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3833   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3834   memcpy(message_buf, our_hello, hello_size);
3835   memcpy(&message_buf[hello_size],
3836          &ping,
3837          sizeof(struct TransportPingMessage));
3838   memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3839          va->transport_name,
3840          slen);
3841   memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3842          &va[1],
3843          va->addrlen);
3844 #if DEBUG_TRANSPORT
3845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3846               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3847               (va->addrlen == 0)
3848               ? "<inbound>"
3849               : a2s (va->transport_name,
3850                      (const void*) &va[1], va->addrlen),
3851               va->transport_name,
3852               GNUNET_i2s (&neighbour->id),
3853               "HELLO", hello_size,
3854               "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
3855 #endif
3856
3857   GNUNET_STATISTICS_update (stats,
3858                             gettext_noop ("# PING messages sent for initial validation"),
3859                             1,
3860                             GNUNET_NO);
3861   transmit_to_peer (NULL, peer_address,
3862                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3863                     HELLO_VERIFICATION_TIMEOUT,
3864                     message_buf, tsize,
3865                     GNUNET_YES, neighbour);
3866   GNUNET_free(message_buf);
3867 }
3868
3869
3870 /**
3871  * Check if the given address is already being validated; if not,
3872  * append the given address to the list of entries that are being be
3873  * validated and initiate validation.
3874  *
3875  * @param cls closure ('struct CheckHelloValidatedContext *')
3876  * @param tname name of the transport
3877  * @param expiration expiration time
3878  * @param addr the address
3879  * @param addrlen length of the address
3880  * @return GNUNET_OK (always)
3881  */
3882 static int
3883 run_validation (void *cls,
3884                 const char *tname,
3885                 struct GNUNET_TIME_Absolute expiration,
3886                 const void *addr,
3887                 uint16_t addrlen)
3888 {
3889   struct CheckHelloValidatedContext *chvc = cls;
3890   struct GNUNET_PeerIdentity id;
3891   struct TransportPlugin *tp;
3892   struct ValidationEntry *va;
3893   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3894   struct CheckAddressExistsClosure caec;
3895   struct OwnAddressList *oal;
3896
3897   GNUNET_assert (addr != NULL);
3898
3899   GNUNET_STATISTICS_update (stats,
3900                             gettext_noop ("# peer addresses scheduled for validation"),
3901                             1,
3902                             GNUNET_NO);
3903   tp = find_transport (tname);
3904   if (tp == NULL)
3905     {
3906       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3907                   GNUNET_ERROR_TYPE_BULK,
3908                   _
3909                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3910                   tname);
3911       GNUNET_STATISTICS_update (stats,
3912                                 gettext_noop ("# peer addresses not validated (plugin not available)"),
3913                                 1,
3914                                 GNUNET_NO);
3915       return GNUNET_OK;
3916     }
3917   /* check if this is one of our own addresses */
3918   oal = tp->addresses;
3919   while (NULL != oal)
3920     {
3921       if ( (oal->addrlen == addrlen) &&
3922            (0 == memcmp (&oal[1],
3923                          addr,
3924                          addrlen)) )
3925         {
3926           /* not plausible, this address is equivalent to our own address! */
3927           GNUNET_STATISTICS_update (stats,
3928                                     gettext_noop ("# peer addresses not validated (loopback)"),
3929                                     1,
3930                                     GNUNET_NO);
3931           return GNUNET_OK;
3932         }
3933       oal = oal->next;
3934     }
3935   GNUNET_HELLO_get_key (chvc->hello, &pk);
3936   GNUNET_CRYPTO_hash (&pk,
3937                       sizeof (struct
3938                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3939                       &id.hashPubKey);
3940
3941   if (is_blacklisted(&id, tp))
3942     {
3943 #if DEBUG_TRANSPORT
3944       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3945                   "Attempted to validate blacklisted peer `%s' using `%s'!\n",
3946                   GNUNET_i2s(&id),
3947                   tname);
3948 #endif
3949       return GNUNET_OK;
3950     }
3951
3952   caec.addr = addr;
3953   caec.addrlen = addrlen;
3954   caec.session = NULL;
3955   caec.tname = tname;
3956   caec.exists = GNUNET_NO;
3957   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3958                                          &check_address_exists,
3959                                          &caec);
3960   if (caec.exists == GNUNET_YES)
3961     {
3962       /* During validation attempts we will likely trigger the other
3963          peer trying to validate our address which in turn will cause
3964          it to send us its HELLO, so we expect to hit this case rather
3965          frequently.  Only print something if we are very verbose. */
3966 #if DEBUG_TRANSPORT > 1
3967       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3968                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3969                   a2s (tname, addr, addrlen),
3970                   tname,
3971                   GNUNET_i2s (&id));
3972 #endif
3973       GNUNET_STATISTICS_update (stats,
3974                                 gettext_noop ("# peer addresses not validated (in progress)"),
3975                                 1,
3976                                 GNUNET_NO);
3977       return GNUNET_OK;
3978     }
3979   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
3980   va->chvc = chvc;
3981   chvc->ve_count++;
3982   va->transport_name = GNUNET_strdup (tname);
3983   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3984                                             UINT_MAX);
3985   va->send_time = GNUNET_TIME_absolute_get();
3986   va->addr = (const void*) &va[1];
3987   memcpy (&va[1], addr, addrlen);
3988   va->addrlen = addrlen;
3989   GNUNET_HELLO_get_key (chvc->hello,
3990                         &va->publicKey);
3991   va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3992                                                    &timeout_hello_validation,
3993                                                    va);
3994   GNUNET_CONTAINER_multihashmap_put (validation_map,
3995                                      &id.hashPubKey,
3996                                      va,
3997                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3998   setup_peer_check_blacklist (&id, GNUNET_NO,
3999                               &transmit_hello_and_ping,
4000                               va);
4001   return GNUNET_OK;
4002 }
4003
4004
4005 /**
4006  * Check if addresses in validated hello "h" overlap with
4007  * those in "chvc->hello" and validate the rest.
4008  *
4009  * @param cls closure
4010  * @param peer id of the peer, NULL for last call
4011  * @param h hello message for the peer (can be NULL)
4012  */
4013 static void
4014 check_hello_validated (void *cls,
4015                        const struct GNUNET_PeerIdentity *peer,
4016                        const struct GNUNET_HELLO_Message *h)
4017 {
4018   struct CheckHelloValidatedContext *chvc = cls;
4019   struct GNUNET_HELLO_Message *plain_hello;
4020   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
4021   struct GNUNET_PeerIdentity target;
4022   struct NeighbourList *n;
4023
4024   if (peer == NULL)
4025     {
4026       GNUNET_STATISTICS_update (stats,
4027                                 gettext_noop ("# outstanding peerinfo iterate requests"),
4028                                 -1,
4029                                 GNUNET_NO);
4030       chvc->piter = NULL;
4031       if (GNUNET_NO == chvc->hello_known)
4032         {
4033           /* notify PEERINFO about the peer now, so that we at least
4034              have the public key if some other component needs it */
4035           GNUNET_HELLO_get_key (chvc->hello, &pk);
4036           GNUNET_CRYPTO_hash (&pk,
4037                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4038                               &target.hashPubKey);
4039           plain_hello = GNUNET_HELLO_create (&pk,
4040                                              NULL,
4041                                              NULL);
4042           GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4043           GNUNET_free (plain_hello);
4044 #if DEBUG_TRANSPORT_HELLO
4045           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4046                       "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4047                       "HELLO",
4048                       GNUNET_i2s (&target));
4049 #endif
4050           GNUNET_STATISTICS_update (stats,
4051                                     gettext_noop ("# new HELLOs requiring full validation"),
4052                                     1,
4053                                     GNUNET_NO);
4054           GNUNET_HELLO_iterate_addresses (chvc->hello,
4055                                           GNUNET_NO,
4056                                           &run_validation,
4057                                           chvc);
4058         }
4059       else
4060         {
4061           GNUNET_STATISTICS_update (stats,
4062                                     gettext_noop ("# duplicate HELLO (peer known)"),
4063                                     1,
4064                                     GNUNET_NO);
4065         }
4066       chvc->ve_count--;
4067       if (chvc->ve_count == 0)
4068         {
4069           GNUNET_CONTAINER_DLL_remove (chvc_head,
4070                                        chvc_tail,
4071                                        chvc);
4072           GNUNET_free (chvc);   
4073         }
4074       return;
4075     }
4076   if (h == NULL)
4077     return;
4078 #if DEBUG_TRANSPORT_HELLO
4079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4080               "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4081               "HELLO",
4082               GNUNET_i2s (peer));
4083 #endif
4084   chvc->hello_known = GNUNET_YES;
4085   n = find_neighbour (peer);
4086   if (n != NULL)
4087     {
4088 #if DEBUG_TRANSPORT_HELLO
4089       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4090                   "Calling hello_iterate_addresses for %s!\n",
4091                   GNUNET_i2s (peer));
4092 #endif
4093       GNUNET_HELLO_iterate_addresses (h,
4094                                       GNUNET_NO,
4095                                       &add_to_foreign_address_list,
4096                                       n);
4097       try_transmission_to_peer (n);
4098     }
4099   else
4100     {
4101 #if DEBUG_TRANSPORT_HELLO
4102       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4103                   "No existing neighbor record for %s!\n",
4104                   GNUNET_i2s (peer));
4105 #endif
4106       GNUNET_STATISTICS_update (stats,
4107                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4108                                 1,
4109                                 GNUNET_NO);
4110     }
4111   GNUNET_STATISTICS_update (stats,
4112                             gettext_noop ("# HELLO validations (update case)"),
4113                             1,
4114                             GNUNET_NO);
4115   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4116                                       h,
4117                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4118                                       &run_validation,
4119                                       chvc);
4120 }
4121
4122
4123 /**
4124  * Process HELLO-message.
4125  *
4126  * @param plugin transport involved, may be NULL
4127  * @param message the actual message
4128  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4129  */
4130 static int
4131 process_hello (struct TransportPlugin *plugin,
4132                const struct GNUNET_MessageHeader *message)
4133 {
4134   uint16_t hsize;
4135   struct GNUNET_PeerIdentity target;
4136   const struct GNUNET_HELLO_Message *hello;
4137   struct CheckHelloValidatedContext *chvc;
4138   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4139 #if DEBUG_TRANSPORT_HELLO > 2
4140   char *my_id;
4141 #endif
4142   hsize = ntohs (message->size);
4143   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4144       (hsize < sizeof (struct GNUNET_MessageHeader)))
4145     {
4146       GNUNET_break (0);
4147       return GNUNET_SYSERR;
4148     }
4149   GNUNET_STATISTICS_update (stats,
4150                             gettext_noop ("# HELLOs received for validation"),
4151                             1,
4152                             GNUNET_NO);
4153
4154   /* first, check if load is too high */
4155   if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4156     {
4157       GNUNET_STATISTICS_update (stats,
4158                                 gettext_noop ("# HELLOs ignored due to high load"),
4159                                 1,
4160                                 GNUNET_NO);
4161 #if DEBUG_TRANSPORT_HELLO
4162       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4163                   "Ignoring `%s' for `%4s', load too high.\n",
4164                   "HELLO",
4165                   GNUNET_i2s (&target));
4166 #endif
4167       return GNUNET_OK;
4168     }
4169   hello = (const struct GNUNET_HELLO_Message *) message;
4170   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4171     {
4172 #if DEBUG_TRANSPORT_HELLO
4173       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174                   "Unable to get public key from `%s' for `%4s'!\n",
4175                   "HELLO",
4176                   GNUNET_i2s (&target));
4177 #endif
4178       GNUNET_break_op (0);
4179       return GNUNET_SYSERR;
4180     }
4181
4182   GNUNET_CRYPTO_hash (&publicKey,
4183                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4184                       &target.hashPubKey);
4185
4186 #if DEBUG_TRANSPORT_HELLO
4187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4188               "Received `%s' message for `%4s'\n",
4189               "HELLO",
4190               GNUNET_i2s (&target));
4191 #endif
4192
4193   if (0 == memcmp (&my_identity,
4194                    &target,
4195                    sizeof (struct GNUNET_PeerIdentity)))
4196     {
4197       GNUNET_STATISTICS_update (stats,
4198                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4199                                 1,
4200                                 GNUNET_NO);
4201       return GNUNET_OK;
4202     }
4203   chvc = chvc_head;
4204   while (NULL != chvc)
4205     {
4206       if (GNUNET_HELLO_equals (hello,
4207                                chvc->hello,
4208                                GNUNET_TIME_absolute_get ()).abs_value > 0)
4209         {
4210 #if DEBUG_TRANSPORT_HELLO > 2
4211           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4212                       "Received duplicate `%s' message for `%4s'; ignored\n",
4213                       "HELLO",
4214                       GNUNET_i2s (&target));
4215 #endif
4216           return GNUNET_OK; /* validation already pending */
4217         }
4218       if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
4219         GNUNET_break (0 != memcmp (hello, chvc->hello,
4220                                    GNUNET_HELLO_size(hello)));
4221       chvc = chvc->next;
4222     }
4223
4224 #if BREAK_TESTS
4225   struct NeighbourList *temp_neighbor = find_neighbour(&target);
4226   if ((NULL != temp_neighbor))
4227     {
4228       fprintf(stderr, "Already know peer, ignoring hello\n");
4229       return GNUNET_OK;
4230     }
4231 #endif
4232
4233 #if DEBUG_TRANSPORT_HELLO > 2
4234   if (plugin != NULL)
4235     {
4236       my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4237       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4238                   "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4239                   my_id,
4240                   "HELLO",
4241                   GNUNET_i2s (&target),
4242                   plugin->short_name,
4243                   GNUNET_HELLO_size(hello));
4244       GNUNET_free(my_id);
4245     }
4246 #endif
4247   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4248   chvc->ve_count = 1;
4249   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4250   memcpy (&chvc[1], hello, hsize);
4251   GNUNET_CONTAINER_DLL_insert (chvc_head,
4252                                chvc_tail,
4253                                chvc);
4254   /* finally, check if HELLO was previously validated
4255      (continuation will then schedule actual validation) */
4256   GNUNET_STATISTICS_update (stats,
4257                             gettext_noop ("# peerinfo process hello iterate requests"),
4258                             1,
4259                             GNUNET_NO);
4260   GNUNET_STATISTICS_update (stats,
4261                             gettext_noop ("# outstanding peerinfo iterate requests"),
4262                             1,
4263                             GNUNET_NO);
4264   chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4265                                          &target,
4266                                          HELLO_VERIFICATION_TIMEOUT,
4267                                          &check_hello_validated, chvc);
4268   return GNUNET_OK;
4269 }
4270
4271
4272 /**
4273  * The peer specified by the given neighbour has timed-out or a plugin
4274  * has disconnected.  We may either need to do nothing (other plugins
4275  * still up), or trigger a full disconnect and clean up.  This
4276  * function updates our state and does the necessary notifications.
4277  * Also notifies our clients that the neighbour is now officially
4278  * gone.
4279  *
4280  * @param n the neighbour list entry for the peer
4281  * @param check GNUNET_YES to check if ALL addresses for this peer
4282  *              are gone, GNUNET_NO to force a disconnect of the peer
4283  *              regardless of whether other addresses exist.
4284  */
4285 static void
4286 disconnect_neighbour (struct NeighbourList *n, int check)
4287 {
4288   struct ReadyList *rpos;
4289   struct NeighbourList *npos;
4290   struct NeighbourList *nprev;
4291   struct MessageQueue *mq;
4292   struct ForeignAddressList *peer_addresses;
4293   struct ForeignAddressList *peer_pos;
4294
4295   if (GNUNET_YES == check)
4296     {
4297       rpos = n->plugins;
4298       while (NULL != rpos)
4299         {
4300           peer_addresses = rpos->addresses;
4301           while (peer_addresses != NULL)
4302             {
4303               if (GNUNET_YES == peer_addresses->connected)
4304                 {
4305                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4306                             "NOT Disconnecting from `%4s', still have live addresses!\n",
4307                             GNUNET_i2s (&n->id));
4308                   return;             /* still connected */
4309                 }
4310               peer_addresses = peer_addresses->next;
4311             }
4312           rpos = rpos->next;
4313         }
4314     }
4315 #if DEBUG_TRANSPORT
4316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4317               "Disconnecting from `%4s'\n",
4318               GNUNET_i2s (&n->id));
4319 #endif
4320   /* remove n from neighbours list */
4321   nprev = NULL;
4322   npos = neighbours;
4323   while ((npos != NULL) && (npos != n))
4324     {
4325       nprev = npos;
4326       npos = npos->next;
4327     }
4328   GNUNET_assert (npos != NULL);
4329   if (nprev == NULL)
4330     neighbours = n->next;
4331   else
4332     nprev->next = n->next;
4333
4334   /* notify all clients about disconnect */
4335   if (GNUNET_YES == n->received_pong)
4336     notify_clients_disconnect (&n->id);
4337
4338   /* clean up all plugins, cancel connections and pending transmissions */
4339   while (NULL != (rpos = n->plugins))
4340     {
4341       n->plugins = rpos->next;
4342       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4343       while (rpos->addresses != NULL)
4344         {
4345           peer_pos = rpos->addresses;
4346           rpos->addresses = peer_pos->next;
4347           if (peer_pos->connected == GNUNET_YES)
4348             GNUNET_STATISTICS_update (stats,
4349                                       gettext_noop ("# connected addresses"),
4350                                       -1,
4351                                       GNUNET_NO);
4352           if (GNUNET_YES == peer_pos->validated)
4353             GNUNET_STATISTICS_update (stats,
4354                                       gettext_noop ("# peer addresses considered valid"),
4355                                       -1,
4356                                       GNUNET_NO);
4357           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4358             {
4359               GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4360               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4361             }
4362           GNUNET_free(peer_pos);
4363         }
4364       GNUNET_free (rpos);
4365     }
4366
4367   /* free all messages on the queue */
4368   while (NULL != (mq = n->messages_head))
4369     {
4370       GNUNET_STATISTICS_update (stats,
4371                                 gettext_noop ("# bytes in message queue for other peers"),
4372                                 - (int64_t) mq->message_buf_size,
4373                                 GNUNET_NO);
4374       GNUNET_STATISTICS_update (stats,
4375                                 gettext_noop ("# bytes discarded due to disconnect"),
4376                                 mq->message_buf_size,
4377                                 GNUNET_NO);
4378       GNUNET_CONTAINER_DLL_remove (n->messages_head,
4379                                    n->messages_tail,
4380                                    mq);
4381       GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4382                                  &n->id,
4383                                  sizeof(struct GNUNET_PeerIdentity)));
4384       GNUNET_free (mq);
4385     }
4386   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4387     {
4388       GNUNET_SCHEDULER_cancel (n->timeout_task);
4389       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4390     }
4391   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4392     {
4393       GNUNET_SCHEDULER_cancel (n->retry_task);
4394       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4395     }
4396   if (n->piter != NULL)
4397     {
4398       GNUNET_PEERINFO_iterate_cancel (n->piter);
4399       GNUNET_STATISTICS_update (stats,
4400                                 gettext_noop ("# outstanding peerinfo iterate requests"),
4401                                 -1,
4402                                 GNUNET_NO);
4403       n->piter = NULL;
4404     }
4405   /* finally, free n itself */
4406   GNUNET_STATISTICS_update (stats,
4407                             gettext_noop ("# active neighbours"),
4408                             -1,
4409                             GNUNET_NO);
4410   GNUNET_free_non_null (n->pre_connect_message_buffer);
4411   GNUNET_free (n);
4412 }
4413
4414
4415 /**
4416  * We have received a PING message from someone.  Need to send a PONG message
4417  * in response to the peer by any means necessary.
4418  */
4419 static int
4420 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4421             const struct GNUNET_PeerIdentity *peer,
4422             struct Session *session,
4423             const char *sender_address,
4424             uint16_t sender_address_len)
4425 {
4426   struct TransportPlugin *plugin = cls;
4427   struct SessionHeader *session_header = (struct SessionHeader*) session;
4428   struct TransportPingMessage *ping;
4429   struct TransportPongMessage *pong;
4430   struct NeighbourList *n;
4431   struct ReadyList *rl;
4432   struct ForeignAddressList *fal;
4433   struct OwnAddressList *oal;
4434   const char *addr;
4435   size_t alen;
4436   size_t slen;
4437
4438   if (ntohs (message->size) < sizeof (struct TransportPingMessage))
4439     {
4440       GNUNET_break_op (0);
4441       return GNUNET_SYSERR;
4442     }
4443
4444   ping = (struct TransportPingMessage *) message;
4445   if (0 != memcmp (&ping->target,
4446                    plugin->env.my_identity,
4447                    sizeof (struct GNUNET_PeerIdentity)))
4448     {
4449       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4450                   _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
4451                   "PING",
4452                   (sender_address != NULL)
4453                   ? a2s (plugin->short_name,
4454                          (const struct sockaddr *)sender_address,
4455                          sender_address_len)
4456                   : "<inbound>",
4457                   GNUNET_i2s (&ping->target));
4458       return GNUNET_SYSERR;
4459     }
4460 #if DEBUG_PING_PONG
4461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4462               "Processing `%s' from `%s'\n",
4463               "PING",
4464               (sender_address != NULL)
4465               ? a2s (plugin->short_name,
4466                      (const struct sockaddr *)sender_address,
4467                      sender_address_len)
4468               : "<inbound>");
4469 #endif
4470   GNUNET_STATISTICS_update (stats,
4471                             gettext_noop ("# PING messages received"),
4472                             1,
4473                             GNUNET_NO);
4474   addr = (const char*) &ping[1];
4475   alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
4476   slen = strlen (plugin->short_name) + 1;
4477   if (alen == 0)
4478     {
4479       /* peer wants to confirm that we have an outbound connection to him */
4480       if (session == NULL)
4481         {
4482           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4483                       _("Refusing to create PONG since I do not have a session with `%s'.\n"),
4484                       GNUNET_i2s (peer));
4485           return GNUNET_SYSERR;
4486         }
4487       pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4488       pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4489       pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4490       pong->purpose.size =
4491         htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4492                sizeof (uint32_t) +
4493                sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4494                sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
4495       pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
4496       pong->challenge = ping->challenge;
4497       pong->addrlen = htonl(sender_address_len + slen);
4498       memcpy(&pong->pid,
4499              peer,
4500              sizeof(struct GNUNET_PeerIdentity));
4501       memcpy (&pong[1],
4502               plugin->short_name,
4503               slen);
4504       memcpy (&((char*)&pong[1])[slen],
4505               sender_address,
4506               sender_address_len);
4507       if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
4508         {
4509           /* create / update cached sig */
4510 #if DEBUG_TRANSPORT
4511           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4512                       "Creating PONG signature to indicate active connection.\n");
4513 #endif
4514           session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
4515           pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4516           GNUNET_assert (GNUNET_OK ==
4517                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4518                                                  &pong->purpose,
4519                                                  &session_header->pong_signature));
4520         }
4521       else
4522         {
4523           pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4524         }
4525       memcpy (&pong->signature,
4526               &session_header->pong_signature,
4527               sizeof (struct GNUNET_CRYPTO_RsaSignature));
4528
4529
4530     }
4531   else
4532     {
4533       /* peer wants to confirm that this is one of our addresses */
4534       addr += slen;
4535       alen -= slen;
4536       if (GNUNET_OK !=
4537           plugin->api->check_address (plugin->api->cls,
4538                                       addr,
4539                                       alen))
4540         {
4541           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4542                       _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
4543                       a2s (plugin->short_name,
4544                            addr,
4545                            alen));
4546           return GNUNET_NO;
4547         }
4548       oal = plugin->addresses;
4549       while (NULL != oal)
4550         {
4551           if ( (oal->addrlen == alen) &&
4552                (0 == memcmp (addr,
4553                              &oal[1],
4554                              alen)) )
4555             break;
4556           oal = oal->next;
4557         }
4558       pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
4559       pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
4560       pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4561       pong->purpose.size =
4562         htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4563                sizeof (uint32_t) +
4564                sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4565                sizeof (struct GNUNET_PeerIdentity) + alen + slen);
4566       pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
4567       pong->challenge = ping->challenge;
4568       pong->addrlen = htonl(alen + slen);
4569       memcpy(&pong->pid,
4570              &my_identity,
4571              sizeof(struct GNUNET_PeerIdentity));
4572       memcpy (&pong[1], plugin->short_name, slen);
4573       memcpy (&((char*)&pong[1])[slen], addr, alen);
4574       if ( (oal != NULL) &&
4575            (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
4576         {
4577           /* create / update cached sig */
4578 #if DEBUG_TRANSPORT
4579           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4580                       "Creating PONG signature to indicate ownership.\n");
4581 #endif
4582           oal->pong_sig_expires = GNUNET_TIME_absolute_min (oal->expires,
4583                                                             GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4584           pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4585           GNUNET_assert (GNUNET_OK ==
4586                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4587                                                  &pong->purpose,
4588                                                  &oal->pong_signature));        
4589           memcpy (&pong->signature,
4590                   &oal->pong_signature,
4591                   sizeof (struct GNUNET_CRYPTO_RsaSignature));
4592         }
4593       else if (oal == NULL)
4594         {
4595           /* not using cache (typically DV-only) */
4596           pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4597           GNUNET_assert (GNUNET_OK ==
4598                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4599                                                  &pong->purpose,
4600                                                  &pong->signature));    
4601         }
4602       else
4603         {
4604           /* can used cached version */
4605           pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4606           memcpy (&pong->signature,
4607                   &oal->pong_signature,
4608                   sizeof (struct GNUNET_CRYPTO_RsaSignature));
4609         }
4610     }
4611   n = find_neighbour(peer);
4612   GNUNET_assert (n != NULL);
4613   /* first try reliable response transmission */
4614   rl = n->plugins;
4615   while (rl != NULL)
4616     {
4617       fal = rl->addresses;
4618       while (fal != NULL)
4619         {
4620           if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4621                                            peer,
4622                                            (const char*) pong,
4623                                            ntohs (pong->header.size),
4624                                            TRANSPORT_PONG_PRIORITY,
4625                                            HELLO_VERIFICATION_TIMEOUT,
4626                                            fal->session,
4627                                            fal->addr,
4628                                            fal->addrlen,
4629                                            GNUNET_SYSERR,
4630                                            NULL, NULL))
4631             {
4632               /* done! */
4633               GNUNET_STATISTICS_update (stats,
4634                                         gettext_noop ("# PONGs unicast via reliable transport"),
4635                                         1,
4636                                         GNUNET_NO);
4637               GNUNET_free (pong);
4638               return GNUNET_OK;
4639             }
4640           fal = fal->next;
4641         }
4642       rl = rl->next;
4643     }
4644   /* no reliable method found, do multicast */
4645   GNUNET_STATISTICS_update (stats,
4646                             gettext_noop ("# PONGs multicast to all available addresses"),
4647                             1,
4648                             GNUNET_NO);
4649   rl = n->plugins;
4650   while (rl != NULL)
4651     {
4652       fal = rl->addresses;
4653       while (fal != NULL)
4654         {
4655           transmit_to_peer(NULL, fal,
4656                            TRANSPORT_PONG_PRIORITY,
4657                            HELLO_VERIFICATION_TIMEOUT,
4658                            (const char *)pong,
4659                            ntohs(pong->header.size),
4660                            GNUNET_YES,
4661                            n);
4662           fal = fal->next;
4663         }
4664       rl = rl->next;
4665     }
4666   GNUNET_free(pong);
4667   return GNUNET_OK;
4668 }
4669
4670
4671 /**
4672  * Function called by the plugin for each received message.
4673  * Update data volumes, possibly notify plugins about
4674  * reducing the rate at which they read from the socket
4675  * and generally forward to our receive callback.
4676  *
4677  * @param cls the "struct TransportPlugin *" we gave to the plugin
4678  * @param peer (claimed) identity of the other peer
4679  * @param message the message, NULL if we only care about
4680  *                learning about the delay until we should receive again
4681  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
4682  * @param session identifier used for this session (can be NULL)
4683  * @param sender_address binary address of the sender (if observed)
4684  * @param sender_address_len number of bytes in sender_address
4685  * @return how long in ms the plugin should wait until receiving more data
4686  *         (plugins that do not support this, can ignore the return value)
4687  */
4688 static struct GNUNET_TIME_Relative
4689 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4690                     const struct GNUNET_MessageHeader *message,
4691                     uint32_t distance,
4692                     struct Session *session,
4693                     const char *sender_address,
4694                     uint16_t sender_address_len)
4695 {
4696   struct TransportPlugin *plugin = cls;
4697   struct ReadyList *service_context;
4698   struct ForeignAddressList *peer_address;
4699   uint16_t msize;
4700   struct NeighbourList *n;
4701   struct GNUNET_TRANSPORT_ATS_Information * ats;
4702   struct GNUNET_TIME_Relative ret;
4703   if (is_blacklisted (peer, plugin))
4704     return GNUNET_TIME_UNIT_FOREVER_REL;
4705
4706   n = find_neighbour (peer);
4707   if (n == NULL)
4708     n = setup_new_neighbour (peer, GNUNET_YES);
4709   service_context = n->plugins;
4710   while ((service_context != NULL) && (plugin != service_context->plugin))
4711     service_context = service_context->next;
4712   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4713   peer_address = NULL;
4714   if (message != NULL)
4715     {
4716       if ( (session != NULL) ||
4717            (sender_address != NULL) )
4718         peer_address = add_peer_address (n,
4719                                          plugin->short_name,
4720                                          session,
4721                                          sender_address,
4722                                          sender_address_len);
4723       if (peer_address != NULL)
4724         {
4725           peer_address->distance = distance;
4726           if (GNUNET_YES == peer_address->validated)
4727             mark_address_connected (peer_address);
4728           peer_address->timeout
4729             =
4730             GNUNET_TIME_relative_to_absolute
4731             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4732           schedule_next_ping (peer_address);
4733         }
4734       /* update traffic received amount ... */
4735       msize = ntohs (message->size);
4736       GNUNET_STATISTICS_update (stats,
4737                                 gettext_noop ("# bytes received from other peers"),
4738                                 msize,
4739                                 GNUNET_NO);
4740       n->distance = distance;
4741       n->peer_timeout =
4742         GNUNET_TIME_relative_to_absolute
4743         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4744       GNUNET_SCHEDULER_cancel (n->timeout_task);
4745       n->timeout_task =
4746         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4747                                       &neighbour_timeout_task, n);
4748       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4749         {
4750           /* dropping message due to frequent inbound volume violations! */
4751           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4752                       GNUNET_ERROR_TYPE_BULK,
4753                       _
4754                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4755                       n->in_tracker.available_bytes_per_s__,
4756                       n->quota_violation_count);
4757           GNUNET_STATISTICS_update (stats,
4758                                     gettext_noop ("# bandwidth quota violations by other peers"),
4759                                     1,
4760                                     GNUNET_NO);
4761           return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4762         }
4763
4764 #if DEBUG_PING_PONG
4765           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4766                       "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4767                       ntohs (message->type),
4768                       ntohs (message->size),
4769                       GNUNET_i2s (peer));
4770 #endif
4771       switch (ntohs (message->type))
4772         {
4773         case GNUNET_MESSAGE_TYPE_HELLO:
4774           GNUNET_STATISTICS_update (stats,
4775                                     gettext_noop ("# HELLO messages received from other peers"),
4776                                     1,
4777                                     GNUNET_NO);
4778           process_hello (plugin, message);
4779           break;
4780         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4781           handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
4782           break;
4783         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4784           handle_pong (plugin, message, peer, sender_address, sender_address_len);
4785           break;
4786         default:
4787           ats = GNUNET_malloc(2 * sizeof(struct GNUNET_TRANSPORT_ATS_Information));
4788           ats[0].type = htonl(GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
4789           if (n->latency.rel_value <= UINT32_MAX)
4790                   ats[0].value = htonl((uint32_t) n->latency.rel_value);
4791           else
4792                   ats[0].value = htonl(UINT32_MAX);
4793           ats[1].type  = htonl(GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
4794           ats[1].value = htonl(n->distance);
4795           //handle_payload_message (message, n, NULL, 0);
4796           handle_payload_message (message, n, ats, 2);
4797           GNUNET_free(ats);
4798           break;
4799         }
4800     }
4801   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4802   if (ret.rel_value > 0)
4803     {
4804       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4805                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4806                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
4807                   (unsigned int) n->in_tracker.available_bytes_per_s__,
4808                   (unsigned long long) ret.rel_value);
4809       GNUNET_STATISTICS_update (stats,
4810                                 gettext_noop ("# ms throttling suggested"),
4811                                 (int64_t) ret.rel_value,
4812                                 GNUNET_NO);
4813     }
4814   return ret;
4815 }
4816
4817 /**
4818  * Handle START-message.  This is the first message sent to us
4819  * by any client which causes us to add it to our list.
4820  *
4821  * @param cls closure (always NULL)
4822  * @param client identification of the client
4823  * @param message the actual message
4824  */
4825 static void
4826 handle_start (void *cls,
4827               struct GNUNET_SERVER_Client *client,
4828               const struct GNUNET_MessageHeader *message)
4829 {
4830   const struct StartMessage *start;
4831   struct TransportClient *c;
4832   struct ConnectInfoMessage cim;
4833   struct NeighbourList *n;
4834
4835   start = (const struct StartMessage*) message;
4836 #if DEBUG_TRANSPORT
4837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4838               "Received `%s' request from client\n", "START");
4839 #endif
4840   c = clients;
4841   while (c != NULL)
4842     {
4843       if (c->client == client)
4844         {
4845           /* client already on our list! */
4846           GNUNET_break (0);
4847           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4848           return;
4849         }
4850       c = c->next;
4851     }
4852   if ( (GNUNET_NO != ntohl (start->do_check)) &&
4853        (0 != memcmp (&start->self,
4854                      &my_identity,
4855                      sizeof (struct GNUNET_PeerIdentity))) )
4856     {
4857       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4858                   _("Rejecting control connection from peer `%s', which is not me!\n"),
4859                   GNUNET_i2s (&start->self));
4860       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4861       return;
4862     }
4863   c = GNUNET_malloc (sizeof (struct TransportClient));
4864   c->next = clients;
4865   clients = c;
4866   c->client = client;
4867   if (our_hello != NULL)
4868     {
4869 #if DEBUG_TRANSPORT
4870       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4871                   "Sending our own `%s' to new client\n", "HELLO");
4872 #endif
4873       transmit_to_client (c,
4874                           (const struct GNUNET_MessageHeader *) our_hello,
4875                           GNUNET_NO);
4876       /* tell new client about all existing connections */
4877       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
4878       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4879       cim.ats_count = htonl(0);
4880       cim.ats.type  = htonl(0);
4881       cim.ats.value = htonl(0);
4882       n = neighbours;
4883       while (n != NULL)
4884         {
4885           if (GNUNET_YES == n->received_pong)
4886             {
4887               cim.id = n->id;
4888               cim.latency = GNUNET_TIME_relative_hton (n->latency);
4889               cim.distance = htonl (n->distance);
4890               fprintf (stderr,"%lu %u %lu ", sizeof (struct ConnectInfoMessage), ntohl(cim.ats_count), sizeof (struct GNUNET_TRANSPORT_ATS_Information));
4891               transmit_to_client (c, &cim.header, GNUNET_NO);
4892             }
4893             n = n->next;
4894         }
4895     }
4896   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4897 }
4898
4899
4900 /**
4901  * Handle HELLO-message.
4902  *
4903  * @param cls closure (always NULL)
4904  * @param client identification of the client
4905  * @param message the actual message
4906  */
4907 static void
4908 handle_hello (void *cls,
4909               struct GNUNET_SERVER_Client *client,
4910               const struct GNUNET_MessageHeader *message)
4911 {
4912   int ret;
4913
4914   GNUNET_STATISTICS_update (stats,
4915                             gettext_noop ("# HELLOs received from clients"),
4916                             1,
4917                             GNUNET_NO);
4918   ret = process_hello (NULL, message);
4919   GNUNET_SERVER_receive_done (client, ret);
4920 }
4921
4922
4923 /**
4924  * Closure for 'transmit_client_message'; followed by
4925  * 'msize' bytes of the actual message.
4926  */
4927 struct TransmitClientMessageContext
4928 {
4929   /**
4930    * Client on whom's behalf we are sending.
4931    */
4932   struct GNUNET_SERVER_Client *client;
4933
4934   /**
4935    * Timeout for the transmission.
4936    */
4937   struct GNUNET_TIME_Absolute timeout;
4938
4939   /**
4940    * Message priority.
4941    */
4942   uint32_t priority;
4943
4944   /**
4945    * Size of the message in bytes.
4946    */
4947   uint16_t msize;
4948 };
4949
4950
4951 /**
4952  * Schedule transmission of a message we got from a client to a peer.
4953  *
4954  * @param cls the 'struct TransmitClientMessageContext*'
4955  * @param n destination, or NULL on error (in that case, drop the message)
4956  */
4957 static void
4958 transmit_client_message (void *cls,
4959                          struct NeighbourList *n)
4960 {
4961   struct TransmitClientMessageContext *tcmc = cls;
4962   struct TransportClient *tc;
4963
4964   tc = clients;
4965   while ((tc != NULL) && (tc->client != tcmc->client))
4966     tc = tc->next;
4967
4968   if (n != NULL)
4969     {
4970       transmit_to_peer (tc, NULL, tcmc->priority,
4971                         GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
4972                         (char *)&tcmc[1],
4973                         tcmc->msize, GNUNET_NO, n);
4974     }
4975   GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
4976   GNUNET_SERVER_client_drop (tcmc->client);
4977   GNUNET_free (tcmc);
4978 }
4979
4980
4981 /**
4982  * Handle SEND-message.
4983  *
4984  * @param cls closure (always NULL)
4985  * @param client identification of the client
4986  * @param message the actual message
4987  */
4988 static void
4989 handle_send (void *cls,
4990              struct GNUNET_SERVER_Client *client,
4991              const struct GNUNET_MessageHeader *message)
4992 {
4993   const struct OutboundMessage *obm;
4994   const struct GNUNET_MessageHeader *obmm;
4995   struct TransmitClientMessageContext *tcmc;
4996   uint16_t size;
4997   uint16_t msize;
4998
4999   size = ntohs (message->size);
5000   if (size <
5001       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
5002     {
5003       GNUNET_break (0);
5004       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5005       return;
5006     }
5007   GNUNET_STATISTICS_update (stats,
5008                             gettext_noop ("# payload received for other peers"),
5009                             size,
5010                             GNUNET_NO);
5011   obm = (const struct OutboundMessage *) message;
5012   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
5013   msize = size - sizeof (struct OutboundMessage);
5014
5015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5016               "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
5017               "SEND", GNUNET_i2s (&obm->peer),
5018               ntohs (obmm->type),
5019               msize);
5020
5021   tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
5022   tcmc->client = client;
5023   tcmc->priority = ntohl (obm->priority);
5024   tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
5025   tcmc->msize = msize;
5026   /* FIXME: this memcpy can be up to 7% of our total runtime */
5027   memcpy (&tcmc[1], obmm, msize);
5028   GNUNET_SERVER_client_keep (client);
5029   setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
5030                               &transmit_client_message,
5031                               tcmc);
5032 }
5033
5034
5035 /**
5036  * Handle request connect message
5037  *
5038  * @param cls closure (always NULL)
5039  * @param client identification of the client
5040  * @param message the actual message
5041  */
5042 static void
5043 handle_request_connect (void *cls,
5044                         struct GNUNET_SERVER_Client *client,
5045                         const struct GNUNET_MessageHeader *message)
5046 {
5047   const struct TransportRequestConnectMessage *trcm =
5048     (const struct TransportRequestConnectMessage *) message;
5049
5050   GNUNET_STATISTICS_update (stats,
5051                             gettext_noop ("# REQUEST CONNECT messages received"),
5052                             1,
5053                             GNUNET_NO);
5054   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a request connect message for peer %s\n", GNUNET_i2s(&trcm->peer));
5055   setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5056                               NULL, NULL);
5057   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5058 }
5059
5060 /**
5061  * Handle SET_QUOTA-message.
5062  *
5063  * @param cls closure (always NULL)
5064  * @param client identification of the client
5065  * @param message the actual message
5066  */
5067 static void
5068 handle_set_quota (void *cls,
5069                   struct GNUNET_SERVER_Client *client,
5070                   const struct GNUNET_MessageHeader *message)
5071 {
5072   const struct QuotaSetMessage *qsm =
5073     (const struct QuotaSetMessage *) message;
5074   struct NeighbourList *n;
5075
5076   GNUNET_STATISTICS_update (stats,
5077                             gettext_noop ("# SET QUOTA messages received"),
5078                             1,
5079                             GNUNET_NO);
5080   n = find_neighbour (&qsm->peer);
5081   if (n == NULL)
5082     {
5083       GNUNET_SERVER_receive_done (client, GNUNET_OK);
5084       GNUNET_STATISTICS_update (stats,
5085                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5086                                 1,
5087                                 GNUNET_NO);
5088       return;
5089     }
5090 #if DEBUG_TRANSPORT
5091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5092               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5093               "SET_QUOTA",
5094               (unsigned int) ntohl (qsm->quota.value__),
5095               (unsigned int) n->in_tracker.available_bytes_per_s__,
5096               GNUNET_i2s (&qsm->peer));
5097 #endif
5098   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5099                                          qsm->quota);
5100   if (0 == ntohl (qsm->quota.value__))
5101     {
5102       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5103                 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5104                 "SET_QUOTA");
5105       disconnect_neighbour (n, GNUNET_NO);
5106     }
5107   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5108 }
5109
5110
5111 /**
5112  * Take the given address and append it to the set of results sent back to
5113  * the client.
5114  *
5115  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5116  * @param address the resolved name, NULL to indicate the last response
5117  */
5118 static void
5119 transmit_address_to_client (void *cls, const char *address)
5120 {
5121   struct GNUNET_SERVER_TransmitContext *tc = cls;
5122   size_t slen;
5123
5124   if (NULL == address)
5125     slen = 0;
5126   else
5127     slen = strlen (address) + 1;
5128
5129   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5130                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5131   if (NULL == address)
5132     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5133 }
5134
5135
5136 /**
5137  * Handle AddressLookup-message.
5138  *
5139  * @param cls closure (always NULL)
5140  * @param client identification of the client
5141  * @param message the actual message
5142  */
5143 static void
5144 handle_address_lookup (void *cls,
5145                        struct GNUNET_SERVER_Client *client,
5146                        const struct GNUNET_MessageHeader *message)
5147 {
5148   const struct AddressLookupMessage *alum;
5149   struct TransportPlugin *lsPlugin;
5150   const char *nameTransport;
5151   const char *address;
5152   uint16_t size;
5153   struct GNUNET_SERVER_TransmitContext *tc;
5154   struct GNUNET_TIME_Absolute timeout;
5155   struct GNUNET_TIME_Relative rtimeout;
5156   int32_t numeric;
5157
5158   size = ntohs (message->size);
5159   if (size < sizeof (struct AddressLookupMessage))
5160     {
5161       GNUNET_break_op (0);
5162       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5163       return;
5164     }
5165   alum = (const struct AddressLookupMessage *) message;
5166   uint32_t addressLen = ntohl (alum->addrlen);
5167   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5168     {
5169       GNUNET_break_op (0);
5170       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5171       return;
5172     }
5173   address = (const char *) &alum[1];
5174   nameTransport = (const char *) &address[addressLen];
5175   if (nameTransport
5176       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5177     {
5178       GNUNET_break_op (0);
5179       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5180       return;
5181     }
5182   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5183   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5184   numeric = ntohl (alum->numeric_only);
5185   lsPlugin = find_transport (nameTransport);
5186   if (NULL == lsPlugin)
5187     {
5188       tc = GNUNET_SERVER_transmit_context_create (client);
5189       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5190                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5191       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5192       return;
5193     }
5194   tc = GNUNET_SERVER_transmit_context_create (client);
5195   lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5196                                          nameTransport,
5197                                          address, addressLen,
5198                                          numeric,
5199                                          rtimeout,
5200                                          &transmit_address_to_client, tc);
5201 }
5202
5203
5204 /**
5205  * Setup the environment for this plugin.
5206  */
5207 static void
5208 create_environment (struct TransportPlugin *plug)
5209 {
5210   plug->env.cfg = cfg;
5211   plug->env.my_identity = &my_identity;
5212   plug->env.our_hello = &our_hello;
5213   plug->env.cls = plug;
5214   plug->env.receive = &plugin_env_receive;
5215   plug->env.notify_address = &plugin_env_notify_address;
5216   plug->env.session_end = &plugin_env_session_end;
5217   plug->env.max_connections = max_connect_per_transport;
5218   plug->env.stats = stats;
5219 }
5220
5221
5222 /**
5223  * Start the specified transport (load the plugin).
5224  */
5225 static void
5226 start_transport (struct GNUNET_SERVER_Handle *server,
5227                  const char *name)
5228 {
5229   struct TransportPlugin *plug;
5230   char *libname;
5231
5232   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5233               _("Loading `%s' transport plugin\n"), name);
5234   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
5235   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
5236   create_environment (plug);
5237   plug->short_name = GNUNET_strdup (name);
5238   plug->lib_name = libname;
5239   plug->next = plugins;
5240   plugins = plug;
5241   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
5242   if (plug->api == NULL)
5243     {
5244       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5245                   _("Failed to load transport plugin for `%s'\n"), name);
5246       GNUNET_free (plug->short_name);
5247       plugins = plug->next;
5248       GNUNET_free (libname);
5249       GNUNET_free (plug);
5250     }
5251 }
5252
5253
5254 /**
5255  * Called whenever a client is disconnected.  Frees our
5256  * resources associated with that client.
5257  *
5258  * @param cls closure
5259  * @param client identification of the client
5260  */
5261 static void
5262 client_disconnect_notification (void *cls,
5263                                 struct GNUNET_SERVER_Client *client)
5264 {
5265   struct TransportClient *pos;
5266   struct TransportClient *prev;
5267   struct ClientMessageQueueEntry *mqe;
5268   struct Blacklisters *bl;
5269   struct BlacklistCheck *bc;
5270
5271   if (client == NULL)
5272     return;
5273 #if DEBUG_TRANSPORT
5274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5275               "Client disconnected, cleaning up.\n");
5276 #endif
5277   /* clean up blacklister */
5278   bl = bl_head;
5279   while (bl != NULL)
5280     {
5281       if (bl->client == client)
5282         {
5283           bc = bc_head;
5284           while (bc != NULL)
5285             {
5286               if (bc->bl_pos == bl)
5287                 {
5288                   bc->bl_pos = bl->next;
5289                   if (bc->th != NULL)
5290                     {
5291                       GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
5292                       bc->th = NULL;            
5293                     }
5294                   if (bc->task == GNUNET_SCHEDULER_NO_TASK)
5295                     bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
5296                                                          bc);
5297                   break;
5298                 }
5299               bc = bc->next;
5300             }
5301           GNUNET_CONTAINER_DLL_remove (bl_head,
5302                                        bl_tail,
5303                                        bl);
5304           GNUNET_SERVER_client_drop (bl->client);
5305           GNUNET_free (bl);
5306           break;
5307         }
5308       bl = bl->next;
5309     }
5310   /* clean up 'normal' clients */
5311   prev = NULL;
5312   pos = clients;
5313   while ((pos != NULL) && (pos->client != client))
5314     {
5315       prev = pos;
5316       pos = pos->next;
5317     }
5318   if (pos == NULL)
5319     return;
5320   while (NULL != (mqe = pos->message_queue_head))
5321     {
5322       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
5323                                    pos->message_queue_tail,
5324                                    mqe);
5325       pos->message_count--;
5326       GNUNET_free (mqe);
5327     }
5328   if (prev == NULL)
5329     clients = pos->next;
5330   else
5331     prev->next = pos->next;
5332   if (GNUNET_YES == pos->tcs_pending)
5333     {
5334       pos->client = NULL;
5335       return;
5336     }
5337   if (pos->th != NULL)
5338     {
5339       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
5340       pos->th = NULL;
5341     }
5342   GNUNET_break (0 == pos->message_count);
5343   GNUNET_free (pos);
5344 }
5345
5346
5347 /**
5348  * Function called when the service shuts down.  Unloads our plugins
5349  * and cancels pending validations.
5350  *
5351  * @param cls closure, unused
5352  * @param tc task context (unused)
5353  */
5354 static void
5355 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5356 {
5357   struct TransportPlugin *plug;
5358   struct OwnAddressList *al;
5359   struct CheckHelloValidatedContext *chvc;
5360
5361   while (neighbours != NULL)
5362     {
5363       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5364               "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
5365               "SHUTDOWN_TASK");
5366       disconnect_neighbour (neighbours, GNUNET_NO);
5367     }
5368 #if DEBUG_TRANSPORT
5369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5370               "Transport service is unloading plugins...\n");
5371 #endif
5372   while (NULL != (plug = plugins))
5373     {
5374       plugins = plug->next;
5375       if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
5376         {
5377           GNUNET_SCHEDULER_cancel (plug->address_update_task);
5378           plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
5379         }
5380       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
5381       GNUNET_free (plug->lib_name);
5382       GNUNET_free (plug->short_name);
5383       while (NULL != (al = plug->addresses))
5384         {
5385           plug->addresses = al->next;
5386           GNUNET_free (al);
5387         }
5388       GNUNET_free (plug);
5389     }
5390   if (my_private_key != NULL)
5391     GNUNET_CRYPTO_rsa_key_free (my_private_key);
5392   GNUNET_free_non_null (our_hello);
5393
5394   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
5395                                          &abort_validation,
5396                                          NULL);
5397   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5398   validation_map = NULL;
5399
5400   /* free 'chvc' data structure */
5401   while (NULL != (chvc = chvc_head))
5402     {
5403       chvc_head = chvc->next;
5404       if (chvc->piter != NULL)
5405         {
5406           GNUNET_PEERINFO_iterate_cancel (chvc->piter);
5407           GNUNET_STATISTICS_update (stats,
5408                                     gettext_noop ("# outstanding peerinfo iterate requests"),
5409                                     -1,
5410                                     GNUNET_NO);
5411         }
5412       else
5413         GNUNET_break (0);
5414       GNUNET_assert (chvc->ve_count == 0);
5415       GNUNET_free (chvc);
5416     }
5417   chvc_tail = NULL;
5418
5419   if (stats != NULL)
5420     {
5421       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5422       stats = NULL;
5423     }
5424   if (peerinfo != NULL)
5425     {
5426       GNUNET_PEERINFO_disconnect (peerinfo);
5427       peerinfo = NULL;
5428     }
5429   /* Can we assume those are gone by now, or do we need to clean up
5430      explicitly!? */
5431   GNUNET_break (bl_head == NULL);
5432   GNUNET_break (bc_head == NULL);
5433 }
5434
5435
5436 /**
5437  * Initiate transport service.
5438  *
5439  * @param cls closure
5440  * @param server the initialized server
5441  * @param c configuration to use
5442  */
5443 static void
5444 run (void *cls,
5445      struct GNUNET_SERVER_Handle *server,
5446      const struct GNUNET_CONFIGURATION_Handle *c)
5447 {
5448   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
5449     {&handle_start, NULL,
5450      GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
5451     {&handle_hello, NULL,
5452      GNUNET_MESSAGE_TYPE_HELLO, 0},
5453     {&handle_send, NULL,
5454      GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
5455     {&handle_request_connect, NULL,
5456      GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
5457     {&handle_set_quota, NULL,
5458      GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
5459     {&handle_address_lookup, NULL,
5460      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
5461      0},
5462     {&handle_blacklist_init, NULL,
5463      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
5464     {&handle_blacklist_reply, NULL,
5465      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
5466     {NULL, NULL, 0, 0}
5467   };
5468   char *plugs;
5469   char *pos;
5470   int no_transports;
5471   unsigned long long tneigh;
5472   char *keyfile;
5473
5474   cfg = c;
5475   stats = GNUNET_STATISTICS_create ("transport", cfg);
5476   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
5477   /* parse configuration */
5478   if ((GNUNET_OK !=
5479        GNUNET_CONFIGURATION_get_value_number (c,
5480                                               "TRANSPORT",
5481                                               "NEIGHBOUR_LIMIT",
5482                                               &tneigh)) ||
5483       (GNUNET_OK !=
5484        GNUNET_CONFIGURATION_get_value_filename (c,
5485                                                 "GNUNETD",
5486                                                 "HOSTKEY", &keyfile)))
5487     {
5488       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5489                   _
5490                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
5491       GNUNET_SCHEDULER_shutdown ();
5492       if (stats != NULL)
5493         {
5494           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5495           stats = NULL;
5496         }
5497       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5498       validation_map = NULL;
5499       return;
5500     }
5501   max_connect_per_transport = (uint32_t) tneigh;
5502   peerinfo = GNUNET_PEERINFO_connect (cfg);
5503   if (peerinfo == NULL)
5504     {
5505       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5506                   _("Could not access PEERINFO service.  Exiting.\n")); 
5507       GNUNET_SCHEDULER_shutdown ();
5508       if (stats != NULL)
5509         {
5510           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5511           stats = NULL;
5512         }
5513       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5514       validation_map = NULL;
5515       GNUNET_free (keyfile);
5516       return;
5517     }
5518   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
5519   GNUNET_free (keyfile);
5520   if (my_private_key == NULL)
5521     {
5522       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5523                   _
5524                   ("Transport service could not access hostkey.  Exiting.\n"));
5525       GNUNET_SCHEDULER_shutdown ();
5526       if (stats != NULL)
5527         {
5528           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5529           stats = NULL;
5530         }
5531       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5532       validation_map = NULL;
5533       return;
5534     }
5535   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
5536   GNUNET_CRYPTO_hash (&my_public_key,
5537                       sizeof (my_public_key), &my_identity.hashPubKey);
5538   /* setup notification */
5539   GNUNET_SERVER_disconnect_notify (server,
5540                                    &client_disconnect_notification, NULL);
5541   /* load plugins... */
5542   no_transports = 1;
5543   if (GNUNET_OK ==
5544       GNUNET_CONFIGURATION_get_value_string (c,
5545                                              "TRANSPORT", "PLUGINS", &plugs))
5546     {
5547       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5548                   _("Starting transport plugins `%s'\n"), plugs);
5549       pos = strtok (plugs, " ");
5550       while (pos != NULL)
5551         {
5552           start_transport (server, pos);
5553           no_transports = 0;
5554           pos = strtok (NULL, " ");
5555         }
5556       GNUNET_free (plugs);
5557     }
5558   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5559                                 &shutdown_task, NULL);
5560   if (no_transports)
5561     refresh_hello ();
5562
5563 #if DEBUG_TRANSPORT
5564   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
5565 #endif
5566   /* If we have a blacklist file, read from it */
5567   read_blacklist_file(cfg);
5568   /* process client requests */
5569   GNUNET_SERVER_add_handlers (server, handlers);
5570 }
5571
5572
5573 /**
5574  * The main function for the transport service.
5575  *
5576  * @param argc number of arguments from the command line
5577  * @param argv command line arguments
5578  * @return 0 ok, 1 on error
5579  */
5580 int
5581 main (int argc, char *const *argv)
5582 {
5583   a2s (NULL, NULL, 0); /* make compiler happy */
5584   return (GNUNET_OK ==
5585           GNUNET_SERVICE_run (argc,
5586                               argv,
5587                               "transport",
5588                               GNUNET_SERVICE_OPTION_NONE,
5589                               &run, NULL)) ? 0 : 1;
5590 }
5591
5592 /* end of gnunet-service-transport.c */