style
[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, int fresh)
1909 {
1910   static struct GNUNET_TIME_Absolute last_update;
1911   struct GNUNET_TIME_Relative min_remaining;
1912   struct GNUNET_TIME_Relative remaining;
1913   struct GNUNET_TIME_Absolute now;
1914   struct OwnAddressList *pos;
1915   struct OwnAddressList *prev;
1916   struct OwnAddressList *next;
1917   int expired;
1918
1919   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1920     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1921   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1922   now = GNUNET_TIME_absolute_get ();
1923   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1924   expired = (GNUNET_TIME_absolute_get_duration (last_update).rel_value > (HELLO_ADDRESS_EXPIRATION.rel_value / 4));
1925   prev = NULL;
1926   pos = plugin->addresses;
1927   while (pos != NULL)
1928     {
1929       next = pos->next;
1930       if (pos->expires.abs_value < now.abs_value)
1931         {
1932           expired = GNUNET_YES;
1933           if (prev == NULL)
1934             plugin->addresses = pos->next;
1935           else
1936             prev->next = pos->next;
1937           GNUNET_free (pos);
1938         }
1939       else
1940         {
1941           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1942           if (remaining.rel_value < min_remaining.rel_value)
1943             min_remaining = remaining;
1944           prev = pos;
1945         }
1946       pos = next;
1947     }
1948
1949   if (expired || fresh)
1950     {
1951       last_update = now;
1952       refresh_hello ();
1953     }
1954   min_remaining = GNUNET_TIME_relative_min (min_remaining,
1955                                             GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1956                                                                          2));
1957   plugin->address_update_task
1958     = GNUNET_SCHEDULER_add_delayed (min_remaining,
1959                                     &expire_address_task, plugin);
1960 }
1961
1962
1963 /**
1964  * Task used to clean up expired addresses for a plugin.
1965  *
1966  * @param cls closure
1967  * @param tc context
1968  */
1969 static void
1970 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1971 {
1972   struct TransportPlugin *plugin = cls;
1973
1974   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1975   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1976     update_addresses (plugin, GNUNET_NO);
1977 }
1978
1979
1980 /**
1981  * Iterator over hash map entries that NULLs the session of validation
1982  * entries that match the given session.
1983  *
1984  * @param cls closure (the 'struct Session*' to match against)
1985  * @param key current key code (peer ID, not used)
1986  * @param value value in the hash map ('struct ValidationEntry*')
1987  * @return GNUNET_YES (we should continue to iterate)
1988  */
1989 static int
1990 remove_session_validations (void *cls,
1991                             const GNUNET_HashCode * key,
1992                             void *value)
1993 {
1994   struct Session *session = cls;
1995   struct ValidationEntry *ve = value;
1996
1997   if (session == ve->session)
1998     ve->session = NULL;
1999   return GNUNET_YES;
2000 }
2001
2002
2003 /**
2004  * We've been disconnected from the other peer (for some
2005  * connection-oriented transport).  Either quickly
2006  * re-establish the connection or signal the disconnect
2007  * to the CORE.
2008  *
2009  * Only signal CORE level disconnect if ALL addresses
2010  * for the peer are exhausted.
2011  *
2012  * @param p overall plugin context
2013  * @param nl neighbour that was disconnected
2014  */
2015 static void
2016 try_fast_reconnect (struct TransportPlugin *p,
2017                     struct NeighbourList *nl)
2018 {
2019   /* FIXME-MW: fast reconnect / transport switching not implemented... */
2020   /* Note: the idea here is to hide problems with transports (or
2021      switching between plugins) from the core to eliminate the need to
2022      re-negotiate session keys and the like; OTOH, we should tell core
2023      quickly (much faster than timeout) `if a connection was lost and
2024      could not be re-established (i.e. other peer went down or is
2025      unable / refuses to communicate);
2026
2027      So we should consider:
2028      1) ideally: our own willingness / need to connect
2029      2) prior failures to connect to this peer (by plugin)
2030      3) ideally: reasons why other peer terminated (as far as knowable)
2031
2032      Most importantly, it must be POSSIBLE for another peer to terminate
2033      a connection for a while (without us instantly re-establishing it).
2034      Similarly, if another peer is gone we should quickly notify CORE.
2035      OTOH, if there was a minor glitch (i.e. crash of gnunet-service-transport
2036      on the other end), we should reconnect in such a way that BOTH CORE
2037      services never even notice.
2038      Furthermore, the same mechanism (or small variation) could be used
2039      to switch to a better-performing plugin (ATS).
2040
2041      Finally, this needs to be tested throughly... */                                                           
2042
2043   /*
2044    * GNUNET_NO in the call below makes transport disconnect the peer,
2045    * even if only a single address (out of say, six) went away.  This
2046    * function must be careful to ONLY disconnect if the peer is gone,
2047    * not just a specifi address.
2048    *
2049    * More specifically, half the places it was used had it WRONG.
2050    */
2051
2052   /* No reconnect, signal disconnect instead! */
2053   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054             "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2055             "try_fast_reconnect");
2056   disconnect_neighbour (nl, GNUNET_YES);
2057 }
2058
2059
2060 /**
2061  * Function that will be called whenever the plugin internally
2062  * cleans up a session pointer and hence the service needs to
2063  * discard all of those sessions as well.  Plugins that do not
2064  * use sessions can simply omit calling this function and always
2065  * use NULL wherever a session pointer is needed.
2066  *
2067  * @param cls closure
2068  * @param peer which peer was the session for
2069  * @param session which session is being destoyed
2070  */
2071 static void
2072 plugin_env_session_end  (void *cls,
2073                          const struct GNUNET_PeerIdentity *peer,
2074                          struct Session *session)
2075 {
2076   struct TransportPlugin *p = cls;
2077   struct NeighbourList *nl;
2078   struct ReadyList *rl;
2079   struct ForeignAddressList *pos;
2080   struct ForeignAddressList *prev;
2081
2082   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2083                                          &remove_session_validations,
2084                                          session);
2085   nl = find_neighbour (peer);
2086   if (nl == NULL)
2087     return; /* was never marked as connected */
2088   rl = nl->plugins;
2089   while (rl != NULL)
2090     {
2091       if (rl->plugin == p)
2092         break;
2093       rl = rl->next;
2094     }
2095   if (rl == NULL)
2096     return; /* was never marked as connected */
2097   prev = NULL;
2098   pos = rl->addresses;
2099   while ( (pos != NULL) &&
2100           (pos->session != session) )
2101     {
2102       prev = pos;
2103       pos = pos->next;
2104     }
2105   if (pos == NULL)
2106     return; /* was never marked as connected */
2107   pos->session = NULL;
2108   if (pos->addrlen != 0)
2109     {
2110       if (nl->received_pong != GNUNET_NO)
2111         try_fast_reconnect (p, nl);
2112       return;
2113     }
2114   /* was inbound connection, free 'pos' */
2115   if (prev == NULL)
2116     rl->addresses = pos->next;
2117   else
2118     prev->next = pos->next;
2119   if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2120     {
2121       GNUNET_SCHEDULER_cancel (pos->revalidate_task);
2122       pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2123     }
2124   GNUNET_free (pos);
2125   if (nl->received_pong == GNUNET_NO)
2126     return; /* nothing to do, never connected... */
2127   /* check if we have any validated addresses left */
2128   pos = rl->addresses;
2129   while (pos != NULL)
2130     {
2131       if (pos->validated)
2132         {
2133           try_fast_reconnect (p, nl);
2134           return;
2135         }
2136       pos = pos->next;
2137     }
2138   /* no valid addresses left, signal disconnect! */
2139
2140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141             "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&nl->id),
2142             "plugin_env_session_end");
2143   /* FIXME: This doesn't mean there are no addresses left for this PEER,
2144    * it means there aren't any left for this PLUGIN/PEER combination! So
2145    * calling disconnect_neighbor here with GNUNET_NO forces disconnect
2146    * when it isn't necessary. Using GNUNET_YES at least checks to see
2147    * if there are any addresses that work first, so as not to overdo it.
2148    * --NE
2149    */
2150   disconnect_neighbour (nl, GNUNET_YES);
2151 }
2152
2153
2154 /**
2155  * Function that must be called by each plugin to notify the
2156  * transport service about the addresses under which the transport
2157  * provided by the plugin can be reached.
2158  *
2159  * @param cls closure
2160  * @param name name of the transport that generated the address
2161  * @param addr one of the addresses of the host, NULL for the last address
2162  *        the specific address format depends on the transport
2163  * @param addrlen length of the address
2164  * @param expires when should this address automatically expire?
2165  */
2166 static void
2167 plugin_env_notify_address (void *cls,
2168                            const char *name,
2169                            const void *addr,
2170                            uint16_t addrlen,
2171                            struct GNUNET_TIME_Relative expires)
2172 {
2173   struct TransportPlugin *p = cls;
2174   struct OwnAddressList *al;
2175   struct GNUNET_TIME_Absolute abex;
2176
2177   GNUNET_assert (addr != NULL);
2178   abex = GNUNET_TIME_relative_to_absolute (expires);
2179   GNUNET_assert (p == find_transport (name));
2180   al = p->addresses;
2181   while (al != NULL)
2182     {
2183       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2184         {
2185           if (al->expires.abs_value < abex.abs_value)
2186             al->expires = abex;
2187           return;
2188         }
2189       al = al->next;
2190     }
2191
2192   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2193   al->next = p->addresses;
2194   p->addresses = al;
2195   al->expires = abex;
2196   al->addrlen = addrlen;
2197   memcpy (&al[1], addr, addrlen);
2198   update_addresses (p, GNUNET_YES);
2199 }
2200
2201
2202 /**
2203  * Notify all of our clients about a peer connecting.
2204  */
2205 static void
2206 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2207                         struct GNUNET_TIME_Relative latency,
2208                         uint32_t distance)
2209 {
2210   struct ConnectInfoMessage cim;
2211   struct TransportClient *cpos;
2212
2213 #if DEBUG_TRANSPORT
2214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215               "Notifying clients about connection from `%s'\n",
2216               GNUNET_i2s (peer));
2217 #endif
2218   GNUNET_STATISTICS_update (stats,
2219                             gettext_noop ("# peers connected"),
2220                             1,
2221                             GNUNET_NO);
2222   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2223   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2224   cim.distance = htonl (distance);
2225   cim.latency = GNUNET_TIME_relative_hton (latency);
2226   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
2227   cpos = clients;
2228   while (cpos != NULL)
2229     {
2230       transmit_to_client (cpos, &cim.header, GNUNET_NO);
2231       cpos = cpos->next;
2232     }
2233 }
2234
2235
2236 /**
2237  * Notify all of our clients about a peer disconnecting.
2238  */
2239 static void
2240 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2241 {
2242   struct DisconnectInfoMessage dim;
2243   struct TransportClient *cpos;
2244
2245 #if DEBUG_TRANSPORT
2246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2247               "Notifying clients about lost connection to `%s'\n",
2248               GNUNET_i2s (peer));
2249 #endif
2250   GNUNET_STATISTICS_update (stats,
2251                             gettext_noop ("# peers connected"),
2252                             -1,
2253                             GNUNET_NO);
2254   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2255   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2256   dim.reserved = htonl (0);
2257   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2258   cpos = clients;
2259   while (cpos != NULL)
2260     {
2261       transmit_to_client (cpos, &dim.header, GNUNET_NO);
2262       cpos = cpos->next;
2263     }
2264 }
2265
2266
2267 /**
2268  * Find a ForeignAddressList entry for the given neighbour
2269  * that matches the given address and transport.
2270  *
2271  * @param neighbour which peer we care about
2272  * @param tname name of the transport plugin
2273  * @param session session to look for, NULL for 'any'; otherwise
2274  *        can be used for the service to "learn" this session ID
2275  *        if 'addr' matches
2276  * @param addr binary address
2277  * @param addrlen length of addr
2278  * @return NULL if no such entry exists
2279  */
2280 static struct ForeignAddressList *
2281 find_peer_address(struct NeighbourList *neighbour,
2282                   const char *tname,
2283                   struct Session *session,
2284                   const char *addr,
2285                   uint16_t addrlen)
2286 {
2287   struct ReadyList *head;
2288   struct ForeignAddressList *pos;
2289
2290   head = neighbour->plugins;
2291   while (head != NULL)
2292     {
2293       if (0 == strcmp (tname, head->plugin->short_name))
2294         break;
2295       head = head->next;
2296     }
2297   if (head == NULL)
2298     return NULL;
2299   pos = head->addresses;
2300   while ( (pos != NULL) &&
2301           ( (pos->addrlen != addrlen) ||
2302             (memcmp(pos->addr, addr, addrlen) != 0) ) )
2303     {
2304       if ( (session != NULL) &&
2305            (pos->session == session) )
2306         return pos;
2307       pos = pos->next;
2308     }
2309   if ( (session != NULL) && (pos != NULL) )
2310     pos->session = session; /* learn it! */
2311   return pos;
2312 }
2313
2314
2315 /**
2316  * Get the peer address struct for the given neighbour and
2317  * address.  If it doesn't yet exist, create it.
2318  *
2319  * @param neighbour which peer we care about
2320  * @param tname name of the transport plugin
2321  * @param session session of the plugin, or NULL for none
2322  * @param addr binary address
2323  * @param addrlen length of addr
2324  * @return NULL if we do not have a transport plugin for 'tname'
2325  */
2326 static struct ForeignAddressList *
2327 add_peer_address (struct NeighbourList *neighbour,
2328                   const char *tname,
2329                   struct Session *session,
2330                   const char *addr,
2331                   uint16_t addrlen)
2332 {
2333   struct ReadyList *head;
2334   struct ForeignAddressList *ret;
2335
2336   ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2337   if (ret != NULL)
2338     return ret;
2339   head = neighbour->plugins;
2340
2341   while (head != NULL)
2342     {
2343       if (0 == strcmp (tname, head->plugin->short_name))
2344         break;
2345       head = head->next;
2346     }
2347   if (head == NULL)
2348     return NULL;
2349   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2350   ret->session = session;
2351   if (addrlen > 0)
2352     {
2353       ret->addr = (const char*) &ret[1];
2354       memcpy (&ret[1], addr, addrlen);
2355     }
2356   else
2357     {
2358       ret->addr = NULL;
2359     }
2360   ret->addrlen = addrlen;
2361   ret->expires = GNUNET_TIME_relative_to_absolute
2362     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2363   ret->latency = GNUNET_TIME_relative_get_forever();
2364   ret->distance = -1;
2365   ret->timeout = GNUNET_TIME_relative_to_absolute
2366     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2367   ret->ready_list = head;
2368   ret->next = head->addresses;
2369   head->addresses = ret;
2370   return ret;
2371 }
2372
2373
2374 /**
2375  * Closure for 'add_validated_address'.
2376  */
2377 struct AddValidatedAddressContext
2378 {
2379   /**
2380    * Entry that has been validated.
2381    */
2382   const struct ValidationEntry *ve;
2383
2384   /**
2385    * Flag set after we have added the address so
2386    * that we terminate the iteration next time.
2387    */
2388   int done;
2389 };
2390
2391
2392 /**
2393  * Callback function used to fill a buffer of max bytes with a list of
2394  * addresses in the format used by HELLOs.  Should use
2395  * "GNUNET_HELLO_add_address" as a helper function.
2396  *
2397  * @param cls the 'struct AddValidatedAddressContext' with the validated address
2398  * @param max maximum number of bytes that can be written to buf
2399  * @param buf where to write the address information
2400  * @return number of bytes written, 0 to signal the
2401  *         end of the iteration.
2402  */
2403 static size_t
2404 add_validated_address (void *cls,
2405                        size_t max, void *buf)
2406 {
2407   struct AddValidatedAddressContext *avac = cls;
2408   const struct ValidationEntry *ve = avac->ve;
2409
2410   if (GNUNET_YES == avac->done)
2411     return 0;
2412   avac->done = GNUNET_YES;
2413   return GNUNET_HELLO_add_address (ve->transport_name,
2414                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2415                                    ve->addr,
2416                                    ve->addrlen,
2417                                    buf,
2418                                    max);
2419 }
2420
2421
2422
2423 /**
2424  * Closure for 'check_address_exists'.
2425  */
2426 struct CheckAddressExistsClosure
2427 {
2428   /**
2429    * Address to check for.
2430    */
2431   const void *addr;
2432
2433   /**
2434    * Name of the transport.
2435    */
2436   const char *tname;
2437
2438   /**
2439    * Session, or NULL.
2440    */
2441   struct Session *session;
2442
2443   /**
2444    * Set to GNUNET_YES if the address exists.
2445    */
2446   int exists;
2447
2448   /**
2449    * Length of addr.
2450    */
2451   uint16_t addrlen;
2452
2453 };
2454
2455
2456 /**
2457  * Iterator over hash map entries.  Checks if the given
2458  * validation entry is for the same address as what is given
2459  * in the closure.
2460  *
2461  * @param cls the 'struct CheckAddressExistsClosure*'
2462  * @param key current key code (ignored)
2463  * @param value value in the hash map ('struct ValidationEntry')
2464  * @return GNUNET_YES if we should continue to
2465  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2466  */
2467 static int
2468 check_address_exists (void *cls,
2469                       const GNUNET_HashCode * key,
2470                       void *value)
2471 {
2472   struct CheckAddressExistsClosure *caec = cls;
2473   struct ValidationEntry *ve = value;
2474
2475   if ( (0 == strcmp (caec->tname,
2476                      ve->transport_name)) &&
2477        (caec->addrlen == ve->addrlen) &&
2478        (0 == memcmp (caec->addr,
2479                      ve->addr,
2480                      caec->addrlen)) )
2481     {
2482       caec->exists = GNUNET_YES;
2483       return GNUNET_NO;
2484     }
2485   if ( (ve->session != NULL) &&
2486        (caec->session == ve->session) )
2487     {
2488       caec->exists = GNUNET_YES;
2489       return GNUNET_NO;
2490     }
2491   return GNUNET_YES;
2492 }
2493
2494
2495
2496 /**
2497  * Iterator to free entries in the validation_map.
2498  *
2499  * @param cls closure (unused)
2500  * @param key current key code
2501  * @param value value in the hash map (validation to abort)
2502  * @return GNUNET_YES (always)
2503  */
2504 static int
2505 abort_validation (void *cls,
2506                   const GNUNET_HashCode * key,
2507                   void *value)
2508 {
2509   struct ValidationEntry *va = value;
2510
2511   if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2512     GNUNET_SCHEDULER_cancel (va->timeout_task);
2513   GNUNET_free (va->transport_name);
2514   if (va->chvc != NULL)
2515     {
2516       va->chvc->ve_count--;
2517       if (va->chvc->ve_count == 0)
2518         {
2519           GNUNET_CONTAINER_DLL_remove (chvc_head,
2520                                        chvc_tail,
2521                                        va->chvc);
2522           GNUNET_free (va->chvc);
2523         }
2524       va->chvc = NULL;
2525     }
2526   GNUNET_free (va);
2527   return GNUNET_YES;
2528 }
2529
2530
2531 /**
2532  * HELLO validation cleanup task (validation failed).
2533  *
2534  * @param cls the 'struct ValidationEntry' that failed
2535  * @param tc scheduler context (unused)
2536  */
2537 static void
2538 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2539 {
2540   struct ValidationEntry *va = cls;
2541   struct GNUNET_PeerIdentity pid;
2542
2543   va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2544   GNUNET_STATISTICS_update (stats,
2545                             gettext_noop ("# address validation timeouts"),
2546                             1,
2547                             GNUNET_NO);
2548   GNUNET_CRYPTO_hash (&va->publicKey,
2549                       sizeof (struct
2550                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2551                       &pid.hashPubKey);
2552   GNUNET_break (GNUNET_OK ==
2553                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2554                                                       &pid.hashPubKey,
2555                                                       va));
2556   abort_validation (NULL, NULL, va);
2557 }
2558
2559
2560 static void
2561 neighbour_timeout_task (void *cls,
2562                        const struct GNUNET_SCHEDULER_TaskContext *tc)
2563 {
2564   struct NeighbourList *n = cls;
2565
2566 #if DEBUG_TRANSPORT
2567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2568               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2569 #endif
2570   GNUNET_STATISTICS_update (stats,
2571                             gettext_noop ("# disconnects due to timeout"),
2572                             1,
2573                             GNUNET_NO);
2574   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2575   disconnect_neighbour (n, GNUNET_NO);
2576 }
2577
2578
2579 /**
2580  * Schedule the job that will cause us to send a PING to the
2581  * foreign address to evaluate its validity and latency.
2582  *
2583  * @param fal address to PING
2584  */
2585 static void
2586 schedule_next_ping (struct ForeignAddressList *fal);
2587
2588
2589 /**
2590  * Add the given address to the list of foreign addresses
2591  * available for the given peer (check for duplicates).
2592  *
2593  * @param cls the respective 'struct NeighbourList' to update
2594  * @param tname name of the transport
2595  * @param expiration expiration time
2596  * @param addr the address
2597  * @param addrlen length of the address
2598  * @return GNUNET_OK (always)
2599  */
2600 static int
2601 add_to_foreign_address_list (void *cls,
2602                              const char *tname,
2603                              struct GNUNET_TIME_Absolute expiration,
2604                              const void *addr,
2605                              uint16_t addrlen)
2606 {
2607   struct NeighbourList *n = cls;
2608   struct ForeignAddressList *fal;
2609   int try;
2610
2611   GNUNET_STATISTICS_update (stats,
2612                             gettext_noop ("# valid peer addresses returned by PEERINFO"),
2613                             1,
2614                             GNUNET_NO);
2615   try = GNUNET_NO;
2616   fal = find_peer_address (n, tname, NULL, addr, addrlen);
2617   if (fal == NULL)
2618     {
2619 #if DEBUG_TRANSPORT_HELLO
2620       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2621                   "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2622                   a2s (tname, addr, addrlen),
2623                   tname,
2624                   GNUNET_i2s (&n->id),
2625                   expiration.abs_value);
2626 #endif
2627       fal = add_peer_address (n, tname, NULL, addr, addrlen);
2628       if (fal == NULL)
2629         {
2630           GNUNET_STATISTICS_update (stats,
2631                                     gettext_noop ("# previously validated addresses lacking transport"),
2632                                     1,
2633                                     GNUNET_NO);
2634         }
2635       else
2636         {
2637           fal->expires = GNUNET_TIME_absolute_max (expiration,
2638                                                    fal->expires);
2639           schedule_next_ping (fal);
2640         }
2641       try = GNUNET_YES;
2642     }
2643   else
2644     {
2645       fal->expires = GNUNET_TIME_absolute_max (expiration,
2646                                                fal->expires);
2647     }
2648   if (fal == NULL)
2649     {
2650       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2651                   "Failed to add new address for `%4s'\n",
2652                   GNUNET_i2s (&n->id));
2653       return GNUNET_OK;
2654     }
2655   if (fal->validated == GNUNET_NO)
2656     {
2657       fal->validated = GNUNET_YES;
2658       GNUNET_STATISTICS_update (stats,
2659                                 gettext_noop ("# peer addresses considered valid"),
2660                                 1,
2661                                 GNUNET_NO);
2662     }
2663   if (try == GNUNET_YES)
2664     {
2665       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2666                   "Have new addresses, will try to trigger transmissions.\n");
2667       try_transmission_to_peer (n);
2668     }
2669   return GNUNET_OK;
2670 }
2671
2672
2673 /**
2674  * Add addresses in validated HELLO "h" to the set of addresses
2675  * we have for this peer.
2676  *
2677  * @param cls closure ('struct NeighbourList*')
2678  * @param peer id of the peer, NULL for last call
2679  * @param h hello message for the peer (can be NULL)
2680  */
2681 static void
2682 add_hello_for_peer (void *cls,
2683                     const struct GNUNET_PeerIdentity *peer,
2684                     const struct GNUNET_HELLO_Message *h)
2685 {
2686   struct NeighbourList *n = cls;
2687
2688   if (peer == NULL)
2689     {
2690       GNUNET_STATISTICS_update (stats,
2691                                 gettext_noop ("# outstanding peerinfo iterate requests"),
2692                                 -1,
2693                                 GNUNET_NO);
2694       n->piter = NULL;
2695       return;
2696     }
2697   if (h == NULL)
2698     return; /* no HELLO available */
2699 #if DEBUG_TRANSPORT
2700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701               "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2702               "HELLO",
2703               GNUNET_i2s (peer));
2704 #endif
2705   if (GNUNET_YES != n->public_key_valid)
2706     {
2707       GNUNET_HELLO_get_key (h, &n->publicKey);
2708       n->public_key_valid = GNUNET_YES;
2709     }
2710   GNUNET_HELLO_iterate_addresses (h,
2711                                   GNUNET_NO,
2712                                   &add_to_foreign_address_list,
2713                                   n);
2714 }
2715
2716
2717 /**
2718  * Create a fresh entry in our neighbour list for the given peer.
2719  * Will try to transmit our current HELLO to the new neighbour.
2720  * Do not call this function directly, use 'setup_peer_check_blacklist.
2721  *
2722  * @param peer the peer for which we create the entry
2723  * @param do_hello should we schedule transmitting a HELLO
2724  * @return the new neighbour list entry
2725  */
2726 static struct NeighbourList *
2727 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2728                      int do_hello)
2729 {
2730   struct NeighbourList *n;
2731   struct TransportPlugin *tp;
2732   struct ReadyList *rl;
2733
2734 #if DEBUG_TRANSPORT
2735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736               "Setting up state for neighbour `%4s'\n",
2737               GNUNET_i2s (peer));
2738 #endif
2739   GNUNET_assert (our_hello != NULL);
2740   GNUNET_STATISTICS_update (stats,
2741                             gettext_noop ("# active neighbours"),
2742                             1,
2743                             GNUNET_NO);
2744   n = GNUNET_malloc (sizeof (struct NeighbourList));
2745   n->next = neighbours;
2746   neighbours = n;
2747   n->id = *peer;
2748   n->peer_timeout =
2749     GNUNET_TIME_relative_to_absolute
2750     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2751   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2752                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2753                                  MAX_BANDWIDTH_CARRY_S);
2754   tp = plugins;
2755   while (tp != NULL)
2756     {
2757       if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2758         {
2759           rl = GNUNET_malloc (sizeof (struct ReadyList));
2760           rl->neighbour = n;
2761           rl->next = n->plugins;
2762           n->plugins = rl;
2763           rl->plugin = tp;
2764           rl->addresses = NULL;
2765         }
2766       tp = tp->next;
2767     }
2768   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2769   n->distance = -1;
2770   n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2771                                                   &neighbour_timeout_task, n);
2772   if (do_hello)
2773     {
2774       GNUNET_STATISTICS_update (stats,
2775                                 gettext_noop ("# peerinfo new neighbor iterate requests"),
2776                                 1,
2777                                 GNUNET_NO);
2778       GNUNET_STATISTICS_update (stats,
2779                                 gettext_noop ("# outstanding peerinfo iterate requests"),
2780                                 1,
2781                                 GNUNET_NO);
2782       n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2783                                           GNUNET_TIME_UNIT_FOREVER_REL,
2784                                           &add_hello_for_peer, n);
2785
2786       GNUNET_STATISTICS_update (stats,
2787                                 gettext_noop ("# HELLO's sent to new neighbors"),
2788                                 1,
2789                                 GNUNET_NO);
2790       transmit_to_peer (NULL, NULL, 0,
2791                         HELLO_ADDRESS_EXPIRATION,
2792                         (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2793                         GNUNET_NO, n);
2794     }
2795   return n;
2796 }
2797
2798
2799 /**
2800  * Function called after we have checked if communicating
2801  * with a given peer is acceptable.
2802  *
2803  * @param cls closure
2804  * @param n NULL if communication is not acceptable
2805  */
2806 typedef void (*SetupContinuation)(void *cls,
2807                                   struct NeighbourList *n);
2808
2809
2810 /**
2811  * Information kept for each client registered to perform
2812  * blacklisting.
2813  */
2814 struct Blacklisters
2815 {
2816   /**
2817    * This is a linked list.
2818    */
2819   struct Blacklisters *next;
2820
2821   /**
2822    * This is a linked list.
2823    */
2824   struct Blacklisters *prev;
2825
2826   /**
2827    * Client responsible for this entry.
2828    */
2829   struct GNUNET_SERVER_Client *client;
2830
2831   /**
2832    * Blacklist check that we're currently performing.
2833    */
2834   struct BlacklistCheck *bc;
2835
2836 };
2837
2838
2839 /**
2840  * Head of DLL of blacklisting clients.
2841  */
2842 static struct Blacklisters *bl_head;
2843
2844 /**
2845  * Tail of DLL of blacklisting clients.
2846  */
2847 static struct Blacklisters *bl_tail;
2848
2849
2850 /**
2851  * Context we use when performing a blacklist check.
2852  */
2853 struct BlacklistCheck
2854 {
2855
2856   /**
2857    * This is a linked list.
2858    */
2859   struct BlacklistCheck *next;
2860
2861   /**
2862    * This is a linked list.
2863    */
2864   struct BlacklistCheck *prev;
2865
2866   /**
2867    * Peer being checked.
2868    */
2869   struct GNUNET_PeerIdentity peer;
2870
2871   /**
2872    * Option for setup neighbour afterwards.
2873    */
2874   int do_hello;
2875
2876   /**
2877    * Continuation to call with the result.
2878    */
2879   SetupContinuation cont;
2880
2881   /**
2882    * Closure for cont.
2883    */
2884   void *cont_cls;
2885
2886   /**
2887    * Current transmission request handle for this client, or NULL if no
2888    * request is pending.
2889    */
2890   struct GNUNET_CONNECTION_TransmitHandle *th;
2891
2892   /**
2893    * Our current position in the blacklisters list.
2894    */
2895   struct Blacklisters *bl_pos;
2896
2897   /**
2898    * Current task performing the check.
2899    */
2900   GNUNET_SCHEDULER_TaskIdentifier task;
2901
2902 };
2903
2904 /**
2905  * Head of DLL of active blacklisting queries.
2906  */
2907 static struct BlacklistCheck *bc_head;
2908
2909 /**
2910  * Tail of DLL of active blacklisting queries.
2911  */
2912 static struct BlacklistCheck *bc_tail;
2913
2914
2915 /**
2916  * Perform next action in the blacklist check.
2917  *
2918  * @param cls the 'struct BlacklistCheck*'
2919  * @param tc unused
2920  */
2921 static void
2922 do_blacklist_check (void *cls,
2923                     const struct GNUNET_SCHEDULER_TaskContext *tc);
2924
2925
2926 /**
2927  * Transmit blacklist query to the client.
2928  *
2929  * @param cls the 'struct BlacklistCheck'
2930  * @param size number of bytes allowed
2931  * @param buf where to copy the message
2932  * @return number of bytes copied to buf
2933  */
2934 static size_t
2935 transmit_blacklist_message (void *cls,
2936                             size_t size,
2937                             void *buf)
2938 {
2939   struct BlacklistCheck *bc = cls;
2940   struct Blacklisters *bl;
2941   struct BlacklistMessage bm;
2942
2943   bc->th = NULL;
2944   if (size == 0)
2945     {
2946       GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2947       bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
2948                                            bc);
2949       return 0;
2950     }
2951   bl = bc->bl_pos;
2952   bm.header.size = htons (sizeof (struct BlacklistMessage));
2953   bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
2954   bm.is_allowed = htonl (0);
2955   bm.peer = bc->peer;
2956   memcpy (buf, &bm, sizeof (bm));
2957   GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
2958   return sizeof (bm);
2959 }
2960
2961
2962 /**
2963  * Perform next action in the blacklist check.
2964  *
2965  * @param cls the 'struct BlacklistCheck*'
2966  * @param tc unused
2967  */
2968 static void
2969 do_blacklist_check (void *cls,
2970                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2971 {
2972   struct BlacklistCheck *bc = cls;
2973   struct Blacklisters *bl;
2974
2975   bc->task = GNUNET_SCHEDULER_NO_TASK;
2976   bl = bc->bl_pos;
2977   if (bl == NULL)
2978     {
2979       bc->cont (bc->cont_cls,
2980                 setup_new_neighbour (&bc->peer, bc->do_hello));         
2981       GNUNET_free (bc);
2982       return;
2983     }
2984   if (bl->bc == NULL)
2985     {
2986       bl->bc = bc;
2987       bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
2988                                                     sizeof (struct BlacklistMessage),
2989                                                     GNUNET_TIME_UNIT_FOREVER_REL,
2990                                                     &transmit_blacklist_message,
2991                                                     bc);
2992     }
2993 }
2994
2995
2996 /**
2997  * Obtain a 'struct NeighbourList' for the given peer.  If such an entry
2998  * does not yet exist, check the blacklist.  If the blacklist says creating
2999  * one is acceptable, create one and call the continuation; otherwise
3000  * call the continuation with NULL.
3001  *
3002  * @param peer peer to setup or look up a struct NeighbourList for
3003  * @param do_hello should we also schedule sending our HELLO to the peer
3004  *        if this is a new record
3005  * @param cont function to call with the 'struct NeigbhbourList*'
3006  * @param cont_cls closure for cont
3007  */
3008 static void
3009 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
3010                             int do_hello,
3011                             SetupContinuation cont,
3012                             void *cont_cls)
3013 {
3014   struct NeighbourList *n;
3015   struct BlacklistCheck *bc;
3016
3017   n = find_neighbour(peer);
3018   if (n != NULL)
3019     {
3020       if (cont != NULL)
3021         cont (cont_cls, n);
3022       return;
3023     }
3024   if (bl_head == NULL)
3025     {
3026       if (cont != NULL)
3027         cont (cont_cls, setup_new_neighbour (peer, do_hello));
3028       else
3029         setup_new_neighbour(peer, do_hello);
3030       return;
3031     }
3032   bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3033   GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3034   bc->peer = *peer;
3035   bc->do_hello = do_hello;
3036   bc->cont = cont;
3037   bc->cont_cls = cont_cls;
3038   bc->bl_pos = bl_head;
3039   bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3040                                        bc);
3041 }
3042
3043
3044 /**
3045  * Function called with the result of querying a new blacklister about
3046  * it being allowed (or not) to continue to talk to an existing neighbour.
3047  *
3048  * @param cls the original 'struct NeighbourList'
3049  * @param n NULL if we need to disconnect
3050  */
3051 static void
3052 confirm_or_drop_neighbour (void *cls,
3053                            struct NeighbourList *n)
3054 {
3055   struct NeighbourList * orig = cls;
3056
3057   if (n == NULL)
3058     {
3059       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3060               "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&orig->id),
3061               "confirm_or_drop_neighboUr");
3062       disconnect_neighbour (orig, GNUNET_NO);
3063     }
3064 }
3065
3066
3067 /**
3068  * Handle a request to start a blacklist.
3069  *
3070  * @param cls closure (always NULL)
3071  * @param client identification of the client
3072  * @param message the actual message
3073  */
3074 static void
3075 handle_blacklist_init (void *cls,
3076                        struct GNUNET_SERVER_Client *client,
3077                        const struct GNUNET_MessageHeader *message)
3078 {
3079   struct Blacklisters *bl;
3080   struct BlacklistCheck *bc;
3081   struct NeighbourList *n;
3082
3083   bl = bl_head;
3084   while (bl != NULL)
3085     {
3086       if (bl->client == client)
3087         {
3088           GNUNET_break (0);
3089           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3090           return;
3091         }
3092       bl = bl->next;
3093     }
3094   bl = GNUNET_malloc (sizeof (struct Blacklisters));
3095   bl->client = client;
3096   GNUNET_SERVER_client_keep (client);
3097   GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
3098   /* confirm that all existing connections are OK! */
3099   n = neighbours;
3100   while (NULL != n)
3101     {
3102       bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
3103       GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
3104       bc->peer = n->id;
3105       bc->do_hello = GNUNET_NO;
3106       bc->cont = &confirm_or_drop_neighbour;
3107       bc->cont_cls = n;
3108       bc->bl_pos = bl;
3109       if (n == neighbours) /* all would wait for the same client, no need to
3110                               create more than just the first task right now */
3111         bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3112                                              bc);
3113       n = n->next;
3114     }
3115 }
3116
3117
3118 /**
3119  * Handle a request to blacklist a peer.
3120  *
3121  * @param cls closure (always NULL)
3122  * @param client identification of the client
3123  * @param message the actual message
3124  */
3125 static void
3126 handle_blacklist_reply (void *cls,
3127                         struct GNUNET_SERVER_Client *client,
3128                         const struct GNUNET_MessageHeader *message)
3129 {
3130   const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3131   struct Blacklisters *bl;
3132   struct BlacklistCheck *bc;
3133
3134   bl = bl_head;
3135   while ( (bl != NULL) &&
3136           (bl->client != client) )
3137     bl = bl->next;
3138   if (bl == NULL)
3139     {
3140       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3141       return;
3142     }
3143   bc = bl->bc;
3144   bl->bc = NULL;
3145   if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3146     {
3147       bc->cont (bc->cont_cls, NULL);
3148       GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3149       GNUNET_free (bc);
3150     }
3151   else
3152     {
3153       bc->bl_pos = bc->bl_pos->next;
3154       bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3155                                            bc);
3156     }
3157   /* check if any other bc's are waiting for this blacklister */
3158   bc = bc_head;
3159   while (bc != NULL)
3160     {
3161       if ( (bc->bl_pos == bl) &&
3162            (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3163         bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
3164                                              bc);
3165       bc = bc->next;
3166     }
3167 }
3168
3169
3170 /**
3171  * Send periodic PING messages to a given foreign address.
3172  *
3173  * @param cls our 'struct PeriodicValidationContext*'
3174  * @param tc task context
3175  */
3176 static void
3177 send_periodic_ping (void *cls,
3178                     const struct GNUNET_SCHEDULER_TaskContext *tc)
3179 {
3180   struct ForeignAddressList *peer_address = cls;
3181   struct TransportPlugin *tp;
3182   struct ValidationEntry *va;
3183   struct NeighbourList *neighbour;
3184   struct TransportPingMessage ping;
3185   struct CheckAddressExistsClosure caec;
3186   char * message_buf;
3187   uint16_t hello_size;
3188   size_t slen;
3189   size_t tsize;
3190
3191   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3192   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3193     return;
3194   tp = peer_address->ready_list->plugin;
3195   neighbour = peer_address->ready_list->neighbour;
3196   if (GNUNET_YES != neighbour->public_key_valid)
3197     {
3198       /* no public key yet, try again later */
3199       schedule_next_ping (peer_address);
3200       return;
3201     }
3202   caec.addr = peer_address->addr;
3203   caec.addrlen = peer_address->addrlen;
3204   caec.tname = tp->short_name;
3205   caec.session = peer_address->session;
3206   caec.exists = GNUNET_NO;
3207   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3208                                          &check_address_exists,
3209                                          &caec);
3210   if (caec.exists == GNUNET_YES)
3211     {
3212       /* During validation attempts we will likely trigger the other
3213          peer trying to validate our address which in turn will cause
3214          it to send us its HELLO, so we expect to hit this case rather
3215          frequently.  Only print something if we are very verbose. */
3216 #if DEBUG_TRANSPORT > 1
3217       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3218                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3219                   (peer_address->addr != NULL)
3220                   ? a2s (tp->short_name,
3221                          peer_address->addr,
3222                          peer_address->addrlen)
3223                   : "<inbound>",
3224                   tp->short_name,
3225                   GNUNET_i2s (&neighbour->id));
3226 #endif
3227       schedule_next_ping (peer_address);
3228       return;
3229     }
3230   va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3231   va->transport_name = GNUNET_strdup (tp->short_name);
3232   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3233                                             UINT_MAX);
3234   va->send_time = GNUNET_TIME_absolute_get();
3235   va->session = peer_address->session;
3236   if (peer_address->addr != NULL)
3237     {
3238       va->addr = (const void*) &va[1];
3239       memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3240       va->addrlen = peer_address->addrlen;
3241     }
3242   memcpy(&va->publicKey,
3243          &neighbour->publicKey,
3244          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3245
3246   va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3247                                                    &timeout_hello_validation,
3248                                                    va);
3249   GNUNET_CONTAINER_multihashmap_put (validation_map,
3250                                      &neighbour->id.hashPubKey,
3251                                      va,
3252                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3253
3254   if (peer_address->validated != GNUNET_YES)
3255     hello_size = GNUNET_HELLO_size(our_hello);
3256   else
3257     hello_size = 0;
3258
3259   tsize = sizeof(struct TransportPingMessage) + hello_size;
3260
3261   if (peer_address->addr != NULL)
3262     {
3263       slen = strlen (tp->short_name) + 1;
3264       tsize += slen + peer_address->addrlen;
3265     }
3266   else
3267     {
3268       slen = 0; /* make gcc happy */
3269     }
3270   message_buf = GNUNET_malloc(tsize);
3271   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3272   ping.challenge = htonl(va->challenge);
3273   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3274   if (peer_address->validated != GNUNET_YES)
3275     {
3276       memcpy(message_buf, our_hello, hello_size);
3277     }
3278
3279   if (peer_address->addr != NULL)
3280     {
3281       ping.header.size = htons(sizeof(struct TransportPingMessage) +
3282                                peer_address->addrlen +
3283                                slen);
3284       memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3285              tp->short_name,
3286              slen);
3287       memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3288              peer_address->addr,
3289              peer_address->addrlen);
3290     }
3291   else
3292     {
3293       ping.header.size = htons(sizeof(struct TransportPingMessage));
3294     }
3295
3296   memcpy(&message_buf[hello_size],
3297          &ping,
3298          sizeof(struct TransportPingMessage));
3299
3300 #if DEBUG_TRANSPORT_REVALIDATION
3301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3302               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s'\n",
3303               (peer_address->addr != NULL)
3304               ? a2s (peer_address->plugin->short_name,
3305                      peer_address->addr,
3306                      peer_address->addrlen)
3307               : "<inbound>",
3308               tp->short_name,
3309               GNUNET_i2s (&neighbour->id),
3310               "HELLO", hello_size,
3311               "PING");
3312 #endif
3313   if (peer_address->validated != GNUNET_YES)
3314     GNUNET_STATISTICS_update (stats,
3315                               gettext_noop ("# PING with HELLO messages sent"),
3316                               1,
3317                               GNUNET_NO);
3318   else
3319     GNUNET_STATISTICS_update (stats,
3320                               gettext_noop ("# PING without HELLO messages sent"),
3321                               1,
3322                               GNUNET_NO);
3323   GNUNET_STATISTICS_update (stats,
3324                             gettext_noop ("# PING messages sent for re-validation"),
3325                             1,
3326                             GNUNET_NO);
3327   transmit_to_peer (NULL, peer_address,
3328                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3329                     HELLO_VERIFICATION_TIMEOUT,
3330                     message_buf, tsize,
3331                     GNUNET_YES, neighbour);
3332   GNUNET_free(message_buf);
3333   schedule_next_ping (peer_address);
3334 }
3335
3336
3337 /**
3338  * Schedule the job that will cause us to send a PING to the
3339  * foreign address to evaluate its validity and latency.
3340  *
3341  * @param fal address to PING
3342  */
3343 static void
3344 schedule_next_ping (struct ForeignAddressList *fal)
3345 {
3346   struct GNUNET_TIME_Relative delay;
3347
3348   if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3349     return;
3350   delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3351   delay.rel_value /= 2; /* do before expiration */
3352   delay = GNUNET_TIME_relative_min (delay,
3353                                     LATENCY_EVALUATION_MAX_DELAY);
3354   if (GNUNET_YES != fal->estimated)
3355     {
3356       delay = GNUNET_TIME_UNIT_ZERO;
3357       fal->estimated = GNUNET_YES;
3358     }                           
3359   if (GNUNET_YES == fal->connected)
3360     {
3361       delay = GNUNET_TIME_relative_min (delay,
3362                                         CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3363     }
3364   /* FIXME: also adjust delay based on how close the last
3365      observed latency is to the latency of the best alternative */
3366   /* bound how fast we can go */
3367   delay = GNUNET_TIME_relative_max (delay,
3368                                     GNUNET_TIME_UNIT_SECONDS);
3369   /* randomize a bit (to avoid doing all at the same time) */
3370   delay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3371   fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(delay,
3372                                                       &send_periodic_ping,
3373                                                       fal);
3374 }
3375
3376
3377
3378
3379 /**
3380  * Function that will be called if we receive some payload
3381  * from another peer.
3382  *
3383  * @param message the payload
3384  * @param n peer who claimed to be the sender
3385  */
3386 static void
3387 handle_payload_message (const struct GNUNET_MessageHeader *message,
3388                         struct NeighbourList *n)
3389 {
3390   struct InboundMessage *im;
3391   struct TransportClient *cpos;
3392   uint16_t msize;
3393
3394   msize = ntohs (message->size);
3395   if (n->received_pong == GNUNET_NO)
3396     {
3397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3398                   "Received message of type %u and size %u from `%4s', but no pong yet!!\n",
3399                   ntohs (message->type),
3400                   ntohs (message->size),
3401                   GNUNET_i2s (&n->id));
3402       GNUNET_free_non_null (n->pre_connect_message_buffer);
3403       n->pre_connect_message_buffer = GNUNET_malloc (msize);
3404       memcpy (n->pre_connect_message_buffer, message, msize);
3405       return;
3406     }
3407
3408 #if DEBUG_TRANSPORT
3409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410               "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3411               ntohs (message->type),
3412               ntohs (message->size),
3413               GNUNET_i2s (&n->id));
3414 #endif
3415   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3416                                                       (ssize_t) msize))
3417     {
3418       n->quota_violation_count++;
3419 #if DEBUG_TRANSPORT
3420       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,                      
3421                   "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
3422                   n->in_tracker.available_bytes_per_s__,
3423                   n->quota_violation_count);
3424 #endif
3425       /* Discount 32k per violation */
3426       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3427                                         - 32 * 1024);           
3428     }
3429   else
3430     {
3431       if (n->quota_violation_count > 0)
3432         {
3433           /* try to add 32k back */
3434           GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3435                                             32 * 1024);
3436           n->quota_violation_count--;
3437         }
3438     }
3439   GNUNET_STATISTICS_update (stats,
3440                             gettext_noop ("# payload received from other peers"),
3441                             msize,
3442                             GNUNET_NO);
3443   /* transmit message to all clients */
3444   im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3445   im->header.size = htons (sizeof (struct InboundMessage) + msize);
3446   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3447   im->latency = GNUNET_TIME_relative_hton (n->latency);
3448   im->peer = n->id;
3449   im->distance = ntohl(n->distance);
3450   memcpy (&im[1], message, msize);
3451   cpos = clients;
3452   while (cpos != NULL)
3453     {
3454       transmit_to_client (cpos, &im->header, GNUNET_YES);
3455       cpos = cpos->next;
3456     }
3457   GNUNET_free (im);
3458 }
3459
3460
3461 /**
3462  * Iterator over hash map entries.  Checks if the given validation
3463  * entry is for the same challenge as what is given in the PONG.
3464  *
3465  * @param cls the 'struct TransportPongMessage*'
3466  * @param key peer identity
3467  * @param value value in the hash map ('struct ValidationEntry')
3468  * @return GNUNET_YES if we should continue to
3469  *         iterate (mismatch), GNUNET_NO if not (entry matched)
3470  */
3471 static int
3472 check_pending_validation (void *cls,
3473                           const GNUNET_HashCode * key,
3474                           void *value)
3475 {
3476   const struct TransportPongMessage *pong = cls;
3477   struct ValidationEntry *ve = value;
3478   struct AddValidatedAddressContext avac;
3479   unsigned int challenge = ntohl(pong->challenge);
3480   struct GNUNET_HELLO_Message *hello;
3481   struct GNUNET_PeerIdentity target;
3482   struct NeighbourList *n;
3483   struct ForeignAddressList *fal;
3484   struct OwnAddressList *oal;
3485   struct TransportPlugin *tp;
3486   struct GNUNET_MessageHeader *prem;
3487   uint16_t ps;
3488   const char *addr;
3489   size_t slen;
3490   size_t alen;
3491
3492   ps = ntohs (pong->header.size);
3493   if (ps < sizeof (struct TransportPongMessage))
3494     {
3495       GNUNET_break_op (0);
3496       return GNUNET_NO;
3497     }
3498   addr = (const char*) &pong[1];
3499   slen = strlen (ve->transport_name) + 1;
3500   if ( (ps - sizeof (struct TransportPongMessage) < slen) ||
3501        (ve->challenge != challenge) ||
3502        (addr[slen-1] != '\0') ||
3503        (0 != strcmp (addr, ve->transport_name)) ||
3504        (ntohl (pong->purpose.size)
3505         != sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3506         sizeof (uint32_t) +
3507         sizeof (struct GNUNET_TIME_AbsoluteNBO) +
3508         sizeof (struct GNUNET_PeerIdentity) + ps - sizeof (struct TransportPongMessage)) )
3509     {
3510       return GNUNET_YES;
3511     }
3512
3513   alen = ps - sizeof (struct TransportPongMessage) - slen;
3514   switch (ntohl (pong->purpose.purpose))
3515     {
3516     case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN:
3517       if ( (ve->addrlen + slen != ntohl (pong->addrlen)) ||
3518            (0 != memcmp (&addr[slen],
3519                          ve->addr,
3520                          ve->addrlen)) )
3521         {
3522           return GNUNET_YES; /* different entry, keep trying! */
3523         }
3524       if (0 != memcmp (&pong->pid,
3525                        key,
3526                        sizeof (struct GNUNET_PeerIdentity)))
3527         {
3528           GNUNET_break_op (0);
3529           return GNUNET_NO;
3530         }
3531       if (GNUNET_OK !=
3532           GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
3533                                     &pong->purpose,
3534                                     &pong->signature,
3535                                     &ve->publicKey))
3536         {
3537           GNUNET_break_op (0);
3538           return GNUNET_NO;
3539         }
3540
3541 #if DEBUG_TRANSPORT
3542       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3543                   "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3544                   GNUNET_h2s (key),
3545                   a2s (ve->transport_name,
3546                        (const struct sockaddr *) ve->addr,
3547                        ve->addrlen),
3548                   ve->transport_name);
3549 #endif
3550       break;
3551     case GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING:
3552       if (0 != memcmp (&pong->pid,
3553                          &my_identity,
3554                          sizeof (struct GNUNET_PeerIdentity)))
3555         {
3556           GNUNET_break_op (0);
3557           return GNUNET_NO;
3558         }
3559       if (ve->addrlen != 0)
3560         {
3561           /* must have been for a different validation entry */
3562           return GNUNET_YES;
3563         }
3564       tp = find_transport (ve->transport_name);
3565       if (tp == NULL)
3566         {
3567           GNUNET_break (0);
3568           return GNUNET_YES;
3569         }
3570       oal = tp->addresses;
3571       while (NULL != oal)
3572         {
3573           if ( (oal->addrlen == alen) &&
3574                (0 == memcmp (&oal[1],
3575                              &addr[slen],
3576                              alen)) )
3577             break;
3578           oal = oal->next;
3579         }
3580       if (oal == NULL)
3581         {
3582           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3583                       _("Not accepting PONG with address `%s' since I cannot confirm having this address.\n"),
3584                       a2s (ve->transport_name,
3585                            &addr[slen],
3586                            alen));
3587           return GNUNET_NO;     
3588         }
3589       if (GNUNET_OK !=
3590           GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING,
3591                                     &pong->purpose,
3592                                     &pong->signature,
3593                                     &ve->publicKey))
3594         {
3595           GNUNET_break_op (0);
3596           return GNUNET_NO;
3597         }
3598
3599 #if DEBUG_TRANSPORT
3600       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3601                   "Confirmed that peer `%4s' is talking to us using address `%s' (%s) for us.\n",
3602                   GNUNET_h2s (key),
3603                   a2s (ve->transport_name,
3604                        &addr[slen],
3605                        alen),
3606                   ve->transport_name);
3607 #endif
3608       break;
3609     default:
3610       GNUNET_break_op (0);
3611       return GNUNET_NO;
3612     }
3613   if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
3614     {
3615       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3616                   _("Received expired signature.  Check system time.\n"));
3617       return GNUNET_NO;
3618     }
3619   GNUNET_STATISTICS_update (stats,
3620                             gettext_noop ("# address validation successes"),
3621                             1,
3622                             GNUNET_NO);
3623   /* create the updated HELLO */
3624   GNUNET_CRYPTO_hash (&ve->publicKey,
3625                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3626                       &target.hashPubKey);
3627   if (ve->addr != NULL)
3628     {
3629       avac.done = GNUNET_NO;
3630       avac.ve = ve;
3631       hello = GNUNET_HELLO_create (&ve->publicKey,
3632                                    &add_validated_address,
3633                                    &avac);
3634       GNUNET_PEERINFO_add_peer (peerinfo,
3635                                 hello);
3636       GNUNET_free (hello);
3637     }
3638   n = find_neighbour (&target);
3639   if (n != NULL)
3640     {
3641       n->publicKey = ve->publicKey;
3642       n->public_key_valid = GNUNET_YES;
3643       fal = add_peer_address (n,
3644                               ve->transport_name,
3645                               ve->session,
3646                               ve->addr,
3647                               ve->addrlen);
3648       GNUNET_assert (fal != NULL);
3649       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3650       fal->validated = GNUNET_YES;
3651       mark_address_connected (fal);
3652       GNUNET_STATISTICS_update (stats,
3653                                 gettext_noop ("# peer addresses considered valid"),
3654                                 1,
3655                                 GNUNET_NO);
3656       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3657       schedule_next_ping (fal);
3658       if (n->latency.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
3659         n->latency = fal->latency;
3660       else
3661         n->latency.rel_value = (fal->latency.rel_value + n->latency.rel_value) / 2;
3662
3663       n->distance = fal->distance;
3664       if (GNUNET_NO == n->received_pong)
3665         {
3666           n->received_pong = GNUNET_YES;
3667           notify_clients_connect (&target, n->latency, n->distance);
3668           if (NULL != (prem = n->pre_connect_message_buffer))
3669             {
3670               n->pre_connect_message_buffer = NULL;
3671               handle_payload_message (prem, n);
3672               GNUNET_free (prem);
3673             }
3674         }
3675       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3676         {
3677           GNUNET_SCHEDULER_cancel (n->retry_task);
3678           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3679           try_transmission_to_peer (n);
3680         }
3681     }
3682
3683   /* clean up validation entry */
3684   GNUNET_assert (GNUNET_YES ==
3685                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
3686                                                        key,
3687                                                        ve));
3688   abort_validation (NULL, NULL, ve);
3689   return GNUNET_NO;
3690 }
3691
3692
3693 /**
3694  * Function that will be called if we receive a validation
3695  * of an address challenge that we transmitted to another
3696  * peer.  Note that the validation should only be considered
3697  * acceptable if the challenge matches AND if the sender
3698  * address is at least a plausible address for this peer
3699  * (otherwise we may be seeing a MiM attack).
3700  *
3701  * @param cls closure
3702  * @param message the pong message
3703  * @param peer who responded to our challenge
3704  * @param sender_address string describing our sender address (as observed
3705  *         by the other peer in binary format)
3706  * @param sender_address_len number of bytes in 'sender_address'
3707  */
3708 static void
3709 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3710              const struct GNUNET_PeerIdentity *peer,
3711              const char *sender_address,
3712              size_t sender_address_len)
3713 {
3714 #if DEBUG_TRANSPORT > 1
3715   /* we get tons of these that just get discarded, only log
3716      if we are quite verbose */
3717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3718               "Receiving `%s' message from `%4s'.\n", "PONG",
3719               GNUNET_i2s (peer));
3720 #endif
3721   GNUNET_STATISTICS_update (stats,
3722                             gettext_noop ("# PONG messages received"),
3723                             1,
3724                             GNUNET_NO);
3725   if (GNUNET_SYSERR !=
3726       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3727                                                   &peer->hashPubKey,
3728                                                   &check_pending_validation,
3729                                                   (void*) message))
3730     {
3731       /* This is *expected* to happen a lot since we send
3732          PONGs to *all* known addresses of the sender of
3733          the PING, so most likely we get multiple PONGs
3734          per PING, and all but the first PONG will end up
3735          here. So really we should not print anything here
3736          unless we want to be very, very verbose... */
3737 #if DEBUG_TRANSPORT > 2
3738       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3739                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3740                   "PONG",
3741                   GNUNET_i2s (peer),
3742                   "PING");
3743 #endif
3744       return;
3745     }
3746
3747 }
3748
3749
3750 /**
3751  * Try to validate a neighbour's address by sending him our HELLO and a PING.
3752  *
3753  * @param cls the 'struct ValidationEntry*'
3754  * @param neighbour neighbour to validate, NULL if validation failed
3755  */
3756 static void
3757 transmit_hello_and_ping (void *cls,
3758                          struct NeighbourList *neighbour)
3759 {
3760   struct ValidationEntry *va = cls;
3761   struct ForeignAddressList *peer_address;
3762   struct TransportPingMessage ping;
3763   uint16_t hello_size;
3764   size_t tsize;
3765   char * message_buf;
3766   struct GNUNET_PeerIdentity id;
3767   size_t slen;
3768
3769   GNUNET_CRYPTO_hash (&va->publicKey,
3770                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3771                       &id.hashPubKey);
3772   if (neighbour == NULL)
3773     {
3774       /* FIXME: stats... */
3775       GNUNET_break (GNUNET_OK ==
3776                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3777                                                           &id.hashPubKey,
3778                                                           va));
3779       abort_validation (NULL, NULL, va);
3780       return;
3781     }
3782   neighbour->publicKey = va->publicKey;
3783   neighbour->public_key_valid = GNUNET_YES;
3784   peer_address = add_peer_address (neighbour,
3785                                    va->transport_name, NULL,
3786                                    (const void*) &va[1],
3787                                    va->addrlen);
3788   if (peer_address == NULL)
3789     {
3790       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3791                   "Failed to add peer `%4s' for plugin `%s'\n",
3792                   GNUNET_i2s (&neighbour->id),
3793                   va->transport_name);
3794       GNUNET_break (GNUNET_OK ==
3795                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3796                                                           &id.hashPubKey,
3797                                                           va));
3798       abort_validation (NULL, NULL, va);
3799       return;
3800     }
3801   hello_size = GNUNET_HELLO_size(our_hello);
3802   slen = strlen(va->transport_name) + 1;
3803   tsize = sizeof(struct TransportPingMessage) + hello_size + va->addrlen + slen;
3804   message_buf = GNUNET_malloc(tsize);
3805   ping.challenge = htonl(va->challenge);
3806   ping.header.size = htons(sizeof(struct TransportPingMessage) + slen + va->addrlen);
3807   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3808   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3809   memcpy(message_buf, our_hello, hello_size);
3810   memcpy(&message_buf[hello_size],
3811          &ping,
3812          sizeof(struct TransportPingMessage));
3813   memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage)],
3814          va->transport_name,
3815          slen);
3816   memcpy(&message_buf[hello_size + sizeof (struct TransportPingMessage) + slen],
3817          &va[1],
3818          va->addrlen);
3819 #if DEBUG_TRANSPORT
3820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3821               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3822               (va->addrlen == 0)
3823               ? "<inbound>"
3824               : a2s (va->transport_name,
3825                      (const void*) &va[1], va->addrlen),
3826               va->transport_name,
3827               GNUNET_i2s (&neighbour->id),
3828               "HELLO", hello_size,
3829               "PING", sizeof (struct TransportPingMessage) + va->addrlen + slen);
3830 #endif
3831
3832   GNUNET_STATISTICS_update (stats,
3833                             gettext_noop ("# PING messages sent for initial validation"),
3834                             1,
3835                             GNUNET_NO);
3836   transmit_to_peer (NULL, peer_address,
3837                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3838                     HELLO_VERIFICATION_TIMEOUT,
3839                     message_buf, tsize,
3840                     GNUNET_YES, neighbour);
3841   GNUNET_free(message_buf);
3842 }
3843
3844
3845 /**
3846  * Check if the given address is already being validated; if not,
3847  * append the given address to the list of entries that are being be
3848  * validated and initiate validation.
3849  *
3850  * @param cls closure ('struct CheckHelloValidatedContext *')
3851  * @param tname name of the transport
3852  * @param expiration expiration time
3853  * @param addr the address
3854  * @param addrlen length of the address
3855  * @return GNUNET_OK (always)
3856  */
3857 static int
3858 run_validation (void *cls,
3859                 const char *tname,
3860                 struct GNUNET_TIME_Absolute expiration,
3861                 const void *addr,
3862                 uint16_t addrlen)
3863 {
3864   struct CheckHelloValidatedContext *chvc = cls;
3865   struct GNUNET_PeerIdentity id;
3866   struct TransportPlugin *tp;
3867   struct ValidationEntry *va;
3868   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3869   struct CheckAddressExistsClosure caec;
3870   struct OwnAddressList *oal;
3871
3872   GNUNET_assert (addr != NULL);
3873
3874   GNUNET_STATISTICS_update (stats,
3875                             gettext_noop ("# peer addresses scheduled for validation"),
3876                             1,
3877                             GNUNET_NO);
3878   tp = find_transport (tname);
3879   if (tp == NULL)
3880     {
3881       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3882                   GNUNET_ERROR_TYPE_BULK,
3883                   _
3884                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3885                   tname);
3886       GNUNET_STATISTICS_update (stats,
3887                                 gettext_noop ("# peer addresses not validated (plugin not available)"),
3888                                 1,
3889                                 GNUNET_NO);
3890       return GNUNET_OK;
3891     }
3892   /* check if this is one of our own addresses */
3893   oal = tp->addresses;
3894   while (NULL != oal)
3895     {
3896       if ( (oal->addrlen == addrlen) &&
3897            (0 == memcmp (&oal[1],
3898                          addr,
3899                          addrlen)) )
3900         {
3901           /* not plausible, this address is equivalent to our own address! */
3902           GNUNET_STATISTICS_update (stats,
3903                                     gettext_noop ("# peer addresses not validated (loopback)"),
3904                                     1,
3905                                     GNUNET_NO);
3906           return GNUNET_OK;
3907         }
3908       oal = oal->next;
3909     }
3910   GNUNET_HELLO_get_key (chvc->hello, &pk);
3911   GNUNET_CRYPTO_hash (&pk,
3912                       sizeof (struct
3913                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3914                       &id.hashPubKey);
3915
3916   if (is_blacklisted(&id, tp))
3917     {
3918 #if DEBUG_TRANSPORT
3919       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920                   "Attempted to validate blacklisted peer `%s' using `%s'!\n",
3921                   GNUNET_i2s(&id),
3922                   tname);
3923 #endif
3924       return GNUNET_OK;
3925     }
3926
3927   caec.addr = addr;
3928   caec.addrlen = addrlen;
3929   caec.session = NULL;
3930   caec.tname = tname;
3931   caec.exists = GNUNET_NO;
3932   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3933                                          &check_address_exists,
3934                                          &caec);
3935   if (caec.exists == GNUNET_YES)
3936     {
3937       /* During validation attempts we will likely trigger the other
3938          peer trying to validate our address which in turn will cause
3939          it to send us its HELLO, so we expect to hit this case rather
3940          frequently.  Only print something if we are very verbose. */
3941 #if DEBUG_TRANSPORT > 1
3942       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3943                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3944                   a2s (tname, addr, addrlen),
3945                   tname,
3946                   GNUNET_i2s (&id));
3947 #endif
3948       GNUNET_STATISTICS_update (stats,
3949                                 gettext_noop ("# peer addresses not validated (in progress)"),
3950                                 1,
3951                                 GNUNET_NO);
3952       return GNUNET_OK;
3953     }
3954   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
3955   va->chvc = chvc;
3956   chvc->ve_count++;
3957   va->transport_name = GNUNET_strdup (tname);
3958   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
3959                                             UINT_MAX);
3960   va->send_time = GNUNET_TIME_absolute_get();
3961   va->addr = (const void*) &va[1];
3962   memcpy (&va[1], addr, addrlen);
3963   va->addrlen = addrlen;
3964   GNUNET_HELLO_get_key (chvc->hello,
3965                         &va->publicKey);
3966   va->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_VERIFICATION_TIMEOUT,
3967                                                    &timeout_hello_validation,
3968                                                    va);
3969   GNUNET_CONTAINER_multihashmap_put (validation_map,
3970                                      &id.hashPubKey,
3971                                      va,
3972                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3973   setup_peer_check_blacklist (&id, GNUNET_NO,
3974                               &transmit_hello_and_ping,
3975                               va);
3976   return GNUNET_OK;
3977 }
3978
3979
3980 /**
3981  * Check if addresses in validated hello "h" overlap with
3982  * those in "chvc->hello" and validate the rest.
3983  *
3984  * @param cls closure
3985  * @param peer id of the peer, NULL for last call
3986  * @param h hello message for the peer (can be NULL)
3987  */
3988 static void
3989 check_hello_validated (void *cls,
3990                        const struct GNUNET_PeerIdentity *peer,
3991                        const struct GNUNET_HELLO_Message *h)
3992 {
3993   struct CheckHelloValidatedContext *chvc = cls;
3994   struct GNUNET_HELLO_Message *plain_hello;
3995   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3996   struct GNUNET_PeerIdentity target;
3997   struct NeighbourList *n;
3998
3999   if (peer == NULL)
4000     {
4001       GNUNET_STATISTICS_update (stats,
4002                                 gettext_noop ("# outstanding peerinfo iterate requests"),
4003                                 -1,
4004                                 GNUNET_NO);
4005       chvc->piter = NULL;
4006       if (GNUNET_NO == chvc->hello_known)
4007         {
4008           /* notify PEERINFO about the peer now, so that we at least
4009              have the public key if some other component needs it */
4010           GNUNET_HELLO_get_key (chvc->hello, &pk);
4011           GNUNET_CRYPTO_hash (&pk,
4012                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4013                               &target.hashPubKey);
4014           plain_hello = GNUNET_HELLO_create (&pk,
4015                                              NULL,
4016                                              NULL);
4017           GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
4018           GNUNET_free (plain_hello);
4019 #if DEBUG_TRANSPORT_HELLO
4020           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4021                       "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
4022                       "HELLO",
4023                       GNUNET_i2s (&target));
4024 #endif
4025           GNUNET_STATISTICS_update (stats,
4026                                     gettext_noop ("# new HELLOs requiring full validation"),
4027                                     1,
4028                                     GNUNET_NO);
4029           GNUNET_HELLO_iterate_addresses (chvc->hello,
4030                                           GNUNET_NO,
4031                                           &run_validation,
4032                                           chvc);
4033         }
4034       else
4035         {
4036           GNUNET_STATISTICS_update (stats,
4037                                     gettext_noop ("# duplicate HELLO (peer known)"),
4038                                     1,
4039                                     GNUNET_NO);
4040         }
4041       chvc->ve_count--;
4042       if (chvc->ve_count == 0)
4043         {
4044           GNUNET_CONTAINER_DLL_remove (chvc_head,
4045                                        chvc_tail,
4046                                        chvc);
4047           GNUNET_free (chvc);   
4048         }
4049       return;
4050     }
4051   if (h == NULL)
4052     return;
4053 #if DEBUG_TRANSPORT_HELLO
4054   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4055               "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
4056               "HELLO",
4057               GNUNET_i2s (peer));
4058 #endif
4059   chvc->hello_known = GNUNET_YES;
4060   n = find_neighbour (peer);
4061   if (n != NULL)
4062     {
4063 #if DEBUG_TRANSPORT_HELLO
4064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4065                   "Calling hello_iterate_addresses for %s!\n",
4066                   GNUNET_i2s (peer));
4067 #endif
4068       GNUNET_HELLO_iterate_addresses (h,
4069                                       GNUNET_NO,
4070                                       &add_to_foreign_address_list,
4071                                       n);
4072       try_transmission_to_peer (n);
4073     }
4074   else
4075     {
4076 #if DEBUG_TRANSPORT_HELLO
4077       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078                   "No existing neighbor record for %s!\n",
4079                   GNUNET_i2s (peer));
4080 #endif
4081       GNUNET_STATISTICS_update (stats,
4082                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
4083                                 1,
4084                                 GNUNET_NO);
4085     }
4086   GNUNET_STATISTICS_update (stats,
4087                             gettext_noop ("# HELLO validations (update case)"),
4088                             1,
4089                             GNUNET_NO);
4090   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
4091                                       h,
4092                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
4093                                       &run_validation,
4094                                       chvc);
4095 }
4096
4097
4098 /**
4099  * Process HELLO-message.
4100  *
4101  * @param plugin transport involved, may be NULL
4102  * @param message the actual message
4103  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
4104  */
4105 static int
4106 process_hello (struct TransportPlugin *plugin,
4107                const struct GNUNET_MessageHeader *message)
4108 {
4109   uint16_t hsize;
4110   struct GNUNET_PeerIdentity target;
4111   const struct GNUNET_HELLO_Message *hello;
4112   struct CheckHelloValidatedContext *chvc;
4113   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
4114 #if DEBUG_TRANSPORT_HELLO > 2
4115   char *my_id;
4116 #endif
4117   hsize = ntohs (message->size);
4118   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
4119       (hsize < sizeof (struct GNUNET_MessageHeader)))
4120     {
4121       GNUNET_break (0);
4122       return GNUNET_SYSERR;
4123     }
4124   GNUNET_STATISTICS_update (stats,
4125                             gettext_noop ("# HELLOs received for validation"),
4126                             1,
4127                             GNUNET_NO);
4128
4129   /* first, check if load is too high */
4130   if (GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
4131     {
4132       GNUNET_STATISTICS_update (stats,
4133                                 gettext_noop ("# HELLOs ignored due to high load"),
4134                                 1,
4135                                 GNUNET_NO);
4136 #if DEBUG_TRANSPORT_HELLO
4137       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4138                   "Ignoring `%s' for `%4s', load too high.\n",
4139                   "HELLO",
4140                   GNUNET_i2s (&target));
4141 #endif
4142       return GNUNET_OK;
4143     }
4144   hello = (const struct GNUNET_HELLO_Message *) message;
4145   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
4146     {
4147 #if DEBUG_TRANSPORT_HELLO
4148       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4149                   "Unable to get public key from `%s' for `%4s'!\n",
4150                   "HELLO",
4151                   GNUNET_i2s (&target));
4152 #endif
4153       GNUNET_break_op (0);
4154       return GNUNET_SYSERR;
4155     }
4156
4157   GNUNET_CRYPTO_hash (&publicKey,
4158                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
4159                       &target.hashPubKey);
4160
4161 #if DEBUG_TRANSPORT_HELLO
4162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4163               "Received `%s' message for `%4s'\n",
4164               "HELLO",
4165               GNUNET_i2s (&target));
4166 #endif
4167
4168   if (0 == memcmp (&my_identity,
4169                    &target,
4170                    sizeof (struct GNUNET_PeerIdentity)))
4171     {
4172       GNUNET_STATISTICS_update (stats,
4173                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
4174                                 1,
4175                                 GNUNET_NO);
4176       return GNUNET_OK;
4177     }
4178   chvc = chvc_head;
4179   while (NULL != chvc)
4180     {
4181       if (GNUNET_HELLO_equals (hello,
4182                                chvc->hello,
4183                                GNUNET_TIME_absolute_get ()).abs_value > 0)
4184         {
4185 #if DEBUG_TRANSPORT_HELLO > 2
4186           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4187                       "Received duplicate `%s' message for `%4s'; ignored\n",
4188                       "HELLO",
4189                       GNUNET_i2s (&target));
4190 #endif
4191           return GNUNET_OK; /* validation already pending */
4192         }
4193       if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
4194         GNUNET_break (0 != memcmp (hello, chvc->hello,
4195                                    GNUNET_HELLO_size(hello)));
4196       chvc = chvc->next;
4197     }
4198
4199 #if BREAK_TESTS
4200   struct NeighbourList *temp_neighbor = find_neighbour(&target);
4201   if ((NULL != temp_neighbor))
4202     {
4203       fprintf(stderr, "Already know peer, ignoring hello\n");
4204       return GNUNET_OK;
4205     }
4206 #endif
4207
4208 #if DEBUG_TRANSPORT_HELLO > 2
4209   if (plugin != NULL)
4210     {
4211       my_id = GNUNET_strdup(GNUNET_i2s(plugin->env.my_identity));
4212       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4213                   "%s: Starting validation of `%s' message for `%4s' via '%s' of size %u\n",
4214                   my_id,
4215                   "HELLO",
4216                   GNUNET_i2s (&target),
4217                   plugin->short_name,
4218                   GNUNET_HELLO_size(hello));
4219       GNUNET_free(my_id);
4220     }
4221 #endif
4222   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
4223   chvc->ve_count = 1;
4224   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
4225   memcpy (&chvc[1], hello, hsize);
4226   GNUNET_CONTAINER_DLL_insert (chvc_head,
4227                                chvc_tail,
4228                                chvc);
4229   /* finally, check if HELLO was previously validated
4230      (continuation will then schedule actual validation) */
4231   GNUNET_STATISTICS_update (stats,
4232                             gettext_noop ("# peerinfo process hello iterate requests"),
4233                             1,
4234                             GNUNET_NO);
4235   GNUNET_STATISTICS_update (stats,
4236                             gettext_noop ("# outstanding peerinfo iterate requests"),
4237                             1,
4238                             GNUNET_NO);
4239   chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
4240                                          &target,
4241                                          HELLO_VERIFICATION_TIMEOUT,
4242                                          &check_hello_validated, chvc);
4243   return GNUNET_OK;
4244 }
4245
4246
4247 /**
4248  * The peer specified by the given neighbour has timed-out or a plugin
4249  * has disconnected.  We may either need to do nothing (other plugins
4250  * still up), or trigger a full disconnect and clean up.  This
4251  * function updates our state and does the necessary notifications.
4252  * Also notifies our clients that the neighbour is now officially
4253  * gone.
4254  *
4255  * @param n the neighbour list entry for the peer
4256  * @param check GNUNET_YES to check if ALL addresses for this peer
4257  *              are gone, GNUNET_NO to force a disconnect of the peer
4258  *              regardless of whether other addresses exist.
4259  */
4260 static void
4261 disconnect_neighbour (struct NeighbourList *n, int check)
4262 {
4263   struct ReadyList *rpos;
4264   struct NeighbourList *npos;
4265   struct NeighbourList *nprev;
4266   struct MessageQueue *mq;
4267   struct ForeignAddressList *peer_addresses;
4268   struct ForeignAddressList *peer_pos;
4269
4270   if (GNUNET_YES == check)
4271     {
4272       rpos = n->plugins;
4273       while (NULL != rpos)
4274         {
4275           peer_addresses = rpos->addresses;
4276           while (peer_addresses != NULL)
4277             {
4278               if (GNUNET_YES == peer_addresses->connected)
4279                 {
4280                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4281                             "NOT Disconnecting from `%4s', still have live addresses!\n",
4282                             GNUNET_i2s (&n->id));
4283                   return;             /* still connected */
4284                 }
4285               peer_addresses = peer_addresses->next;
4286             }
4287           rpos = rpos->next;
4288         }
4289     }
4290 #if DEBUG_TRANSPORT
4291   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4292               "Disconnecting from `%4s'\n",
4293               GNUNET_i2s (&n->id));
4294 #endif
4295   /* remove n from neighbours list */
4296   nprev = NULL;
4297   npos = neighbours;
4298   while ((npos != NULL) && (npos != n))
4299     {
4300       nprev = npos;
4301       npos = npos->next;
4302     }
4303   GNUNET_assert (npos != NULL);
4304   if (nprev == NULL)
4305     neighbours = n->next;
4306   else
4307     nprev->next = n->next;
4308
4309   /* notify all clients about disconnect */
4310   if (GNUNET_YES == n->received_pong)
4311     notify_clients_disconnect (&n->id);
4312
4313   /* clean up all plugins, cancel connections and pending transmissions */
4314   while (NULL != (rpos = n->plugins))
4315     {
4316       n->plugins = rpos->next;
4317       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
4318       while (rpos->addresses != NULL)
4319         {
4320           peer_pos = rpos->addresses;
4321           rpos->addresses = peer_pos->next;
4322           if (peer_pos->connected == GNUNET_YES)
4323             GNUNET_STATISTICS_update (stats,
4324                                       gettext_noop ("# connected addresses"),
4325                                       -1,
4326                                       GNUNET_NO);
4327           if (GNUNET_YES == peer_pos->validated)
4328             GNUNET_STATISTICS_update (stats,
4329                                       gettext_noop ("# peer addresses considered valid"),
4330                                       -1,
4331                                       GNUNET_NO);
4332           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
4333             {
4334               GNUNET_SCHEDULER_cancel (peer_pos->revalidate_task);
4335               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
4336             }
4337           GNUNET_free(peer_pos);
4338         }
4339       GNUNET_free (rpos);
4340     }
4341
4342   /* free all messages on the queue */
4343   while (NULL != (mq = n->messages_head))
4344     {
4345       GNUNET_STATISTICS_update (stats,
4346                                 gettext_noop ("# bytes in message queue for other peers"),
4347                                 - (int64_t) mq->message_buf_size,
4348                                 GNUNET_NO);
4349       GNUNET_STATISTICS_update (stats,
4350                                 gettext_noop ("# bytes discarded due to disconnect"),
4351                                 mq->message_buf_size,
4352                                 GNUNET_NO);
4353       GNUNET_CONTAINER_DLL_remove (n->messages_head,
4354                                    n->messages_tail,
4355                                    mq);
4356       GNUNET_assert (0 == memcmp(&mq->neighbour_id,
4357                                  &n->id,
4358                                  sizeof(struct GNUNET_PeerIdentity)));
4359       GNUNET_free (mq);
4360     }
4361   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4362     {
4363       GNUNET_SCHEDULER_cancel (n->timeout_task);
4364       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4365     }
4366   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4367     {
4368       GNUNET_SCHEDULER_cancel (n->retry_task);
4369       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4370     }
4371   if (n->piter != NULL)
4372     {
4373       GNUNET_PEERINFO_iterate_cancel (n->piter);
4374       GNUNET_STATISTICS_update (stats,
4375                                 gettext_noop ("# outstanding peerinfo iterate requests"),
4376                                 -1,
4377                                 GNUNET_NO);
4378       n->piter = NULL;
4379     }
4380   /* finally, free n itself */
4381   GNUNET_STATISTICS_update (stats,
4382                             gettext_noop ("# active neighbours"),
4383                             -1,
4384                             GNUNET_NO);
4385   GNUNET_free_non_null (n->pre_connect_message_buffer);
4386   GNUNET_free (n);
4387 }
4388
4389
4390 /**
4391  * We have received a PING message from someone.  Need to send a PONG message
4392  * in response to the peer by any means necessary.
4393  */
4394 static int
4395 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4396             const struct GNUNET_PeerIdentity *peer,
4397             struct Session *session,
4398             const char *sender_address,
4399             uint16_t sender_address_len)
4400 {
4401   struct TransportPlugin *plugin = cls;
4402   struct SessionHeader *session_header = (struct SessionHeader*) session;
4403   struct TransportPingMessage *ping;
4404   struct TransportPongMessage *pong;
4405   struct NeighbourList *n;
4406   struct ReadyList *rl;
4407   struct ForeignAddressList *fal;
4408   struct OwnAddressList *oal;
4409   const char *addr;
4410   size_t alen;
4411   size_t slen;
4412
4413   if (ntohs (message->size) < sizeof (struct TransportPingMessage))
4414     {
4415       GNUNET_break_op (0);
4416       return GNUNET_SYSERR;
4417     }
4418
4419   ping = (struct TransportPingMessage *) message;
4420   if (0 != memcmp (&ping->target,
4421                    plugin->env.my_identity,
4422                    sizeof (struct GNUNET_PeerIdentity)))
4423     {
4424       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4425                   _("Received `%s' message from `%s' destined for `%s' which is not me!\n"),
4426                   "PING",
4427                   (sender_address != NULL)
4428                   ? a2s (plugin->short_name,
4429                          (const struct sockaddr *)sender_address,
4430                          sender_address_len)
4431                   : "<inbound>",
4432                   GNUNET_i2s (&ping->target));
4433       return GNUNET_SYSERR;
4434     }
4435 #if DEBUG_PING_PONG
4436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4437               "Processing `%s' from `%s'\n",
4438               "PING",
4439               (sender_address != NULL)
4440               ? a2s (plugin->short_name,
4441                      (const struct sockaddr *)sender_address,
4442                      sender_address_len)
4443               : "<inbound>");
4444 #endif
4445   GNUNET_STATISTICS_update (stats,
4446                             gettext_noop ("# PING messages received"),
4447                             1,
4448                             GNUNET_NO);
4449   addr = (const char*) &ping[1];
4450   alen = ntohs (message->size) - sizeof (struct TransportPingMessage);
4451   slen = strlen (plugin->short_name) + 1;
4452   if (alen == 0)
4453     {
4454       /* peer wants to confirm that we have an outbound connection to him */
4455       if (session == NULL)
4456         {
4457           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4458                       _("Refusing to create PONG since I do not have a session with `%s'.\n"),
4459                       GNUNET_i2s (peer));
4460           return GNUNET_SYSERR;
4461         }
4462       pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4463       pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len + slen);
4464       pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4465       pong->purpose.size =
4466         htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4467                sizeof (uint32_t) +
4468                sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4469                sizeof (struct GNUNET_PeerIdentity) + sender_address_len + slen);
4470       pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING);
4471       pong->challenge = ping->challenge;
4472       pong->addrlen = htonl(sender_address_len + slen);
4473       memcpy(&pong->pid,
4474              peer,
4475              sizeof(struct GNUNET_PeerIdentity));
4476       memcpy (&pong[1],
4477               plugin->short_name,
4478               slen);
4479       memcpy (&((char*)&pong[1])[slen],
4480               sender_address,
4481               sender_address_len);
4482       if (GNUNET_TIME_absolute_get_remaining (session_header->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
4483         {
4484           /* create / update cached sig */
4485 #if DEBUG_TRANSPORT
4486           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4487                       "Creating PONG signature to indicate active connection.\n");
4488 #endif
4489           session_header->pong_sig_expires = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
4490           pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4491           GNUNET_assert (GNUNET_OK ==
4492                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4493                                                  &pong->purpose,
4494                                                  &session_header->pong_signature));
4495         }
4496       else
4497         {
4498           pong->expiration = GNUNET_TIME_absolute_hton (session_header->pong_sig_expires);
4499         }
4500       memcpy (&pong->signature,
4501               &session_header->pong_signature,
4502               sizeof (struct GNUNET_CRYPTO_RsaSignature));
4503
4504
4505     }
4506   else
4507     {
4508       /* peer wants to confirm that this is one of our addresses */
4509       addr += slen;
4510       alen -= slen;
4511       if (GNUNET_OK !=
4512           plugin->api->check_address (plugin->api->cls,
4513                                       addr,
4514                                       alen))
4515         {
4516           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4517                       _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
4518                       a2s (plugin->short_name,
4519                            addr,
4520                            alen));
4521           return GNUNET_NO;
4522         }
4523       oal = plugin->addresses;
4524       while (NULL != oal)
4525         {
4526           if ( (oal->addrlen == alen) &&
4527                (0 == memcmp (addr,
4528                              &oal[1],
4529                              alen)) )
4530             break;
4531           oal = oal->next;
4532         }
4533       pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
4534       pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
4535       pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4536       pong->purpose.size =
4537         htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4538                sizeof (uint32_t) +
4539                sizeof (struct GNUNET_TIME_AbsoluteNBO) +
4540                sizeof (struct GNUNET_PeerIdentity) + alen + slen);
4541       pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
4542       pong->challenge = ping->challenge;
4543       pong->addrlen = htonl(alen + slen);
4544       memcpy(&pong->pid,
4545              &my_identity,
4546              sizeof(struct GNUNET_PeerIdentity));
4547       memcpy (&pong[1], plugin->short_name, slen);
4548       memcpy (&((char*)&pong[1])[slen], addr, alen);
4549       if ( (oal != NULL) &&
4550            (GNUNET_TIME_absolute_get_remaining (oal->pong_sig_expires).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4) )
4551         {
4552           /* create / update cached sig */
4553 #if DEBUG_TRANSPORT
4554           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4555                       "Creating PONG signature to indicate ownership.\n");
4556 #endif
4557           oal->pong_sig_expires = GNUNET_TIME_absolute_min (oal->expires,
4558                                                             GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4559           pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4560           GNUNET_assert (GNUNET_OK ==
4561                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4562                                                  &pong->purpose,
4563                                                  &oal->pong_signature));        
4564           memcpy (&pong->signature,
4565                   &oal->pong_signature,
4566                   sizeof (struct GNUNET_CRYPTO_RsaSignature));
4567         }
4568       else if (oal == NULL)
4569         {
4570           /* not using cache (typically DV-only) */
4571           pong->expiration = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME));
4572           GNUNET_assert (GNUNET_OK ==
4573                          GNUNET_CRYPTO_rsa_sign (my_private_key,
4574                                                  &pong->purpose,
4575                                                  &pong->signature));    
4576         }
4577       else
4578         {
4579           /* can used cached version */
4580           pong->expiration = GNUNET_TIME_absolute_hton (oal->pong_sig_expires);
4581           memcpy (&pong->signature,
4582                   &oal->pong_signature,
4583                   sizeof (struct GNUNET_CRYPTO_RsaSignature));
4584         }
4585     }
4586   n = find_neighbour(peer);
4587   GNUNET_assert (n != NULL);
4588   /* first try reliable response transmission */
4589   rl = n->plugins;
4590   while (rl != NULL)
4591     {
4592       fal = rl->addresses;
4593       while (fal != NULL)
4594         {
4595           if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4596                                            peer,
4597                                            (const char*) pong,
4598                                            ntohs (pong->header.size),
4599                                            TRANSPORT_PONG_PRIORITY,
4600                                            HELLO_VERIFICATION_TIMEOUT,
4601                                            fal->session,
4602                                            fal->addr,
4603                                            fal->addrlen,
4604                                            GNUNET_SYSERR,
4605                                            NULL, NULL))
4606             {
4607               /* done! */
4608               GNUNET_STATISTICS_update (stats,
4609                                         gettext_noop ("# PONGs unicast via reliable transport"),
4610                                         1,
4611                                         GNUNET_NO);
4612               GNUNET_free (pong);
4613               return GNUNET_OK;
4614             }
4615           fal = fal->next;
4616         }
4617       rl = rl->next;
4618     }
4619   /* no reliable method found, do multicast */
4620   GNUNET_STATISTICS_update (stats,
4621                             gettext_noop ("# PONGs multicast to all available addresses"),
4622                             1,
4623                             GNUNET_NO);
4624   rl = n->plugins;
4625   while (rl != NULL)
4626     {
4627       fal = rl->addresses;
4628       while (fal != NULL)
4629         {
4630           transmit_to_peer(NULL, fal,
4631                            TRANSPORT_PONG_PRIORITY,
4632                            HELLO_VERIFICATION_TIMEOUT,
4633                            (const char *)pong,
4634                            ntohs(pong->header.size),
4635                            GNUNET_YES,
4636                            n);
4637           fal = fal->next;
4638         }
4639       rl = rl->next;
4640     }
4641   GNUNET_free(pong);
4642   return GNUNET_OK;
4643 }
4644
4645
4646 /**
4647  * Function called by the plugin for each received message.
4648  * Update data volumes, possibly notify plugins about
4649  * reducing the rate at which they read from the socket
4650  * and generally forward to our receive callback.
4651  *
4652  * @param cls the "struct TransportPlugin *" we gave to the plugin
4653  * @param peer (claimed) identity of the other peer
4654  * @param message the message, NULL if we only care about
4655  *                learning about the delay until we should receive again
4656  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
4657  * @param session identifier used for this session (can be NULL)
4658  * @param sender_address binary address of the sender (if observed)
4659  * @param sender_address_len number of bytes in sender_address
4660  * @return how long in ms the plugin should wait until receiving more data
4661  *         (plugins that do not support this, can ignore the return value)
4662  */
4663 static struct GNUNET_TIME_Relative
4664 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4665                     const struct GNUNET_MessageHeader *message,
4666                     uint32_t distance,
4667                     struct Session *session,
4668                     const char *sender_address,
4669                     uint16_t sender_address_len)
4670 {
4671   struct TransportPlugin *plugin = cls;
4672   struct ReadyList *service_context;
4673   struct ForeignAddressList *peer_address;
4674   uint16_t msize;
4675   struct NeighbourList *n;
4676   struct GNUNET_TIME_Relative ret;
4677   if (is_blacklisted (peer, plugin))
4678     return GNUNET_TIME_UNIT_FOREVER_REL;
4679
4680   n = find_neighbour (peer);
4681   if (n == NULL)
4682     n = setup_new_neighbour (peer, GNUNET_YES);
4683   service_context = n->plugins;
4684   while ((service_context != NULL) && (plugin != service_context->plugin))
4685     service_context = service_context->next;
4686   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4687   peer_address = NULL;
4688   if (message != NULL)
4689     {
4690       if ( (session != NULL) ||
4691            (sender_address != NULL) )
4692         peer_address = add_peer_address (n,
4693                                          plugin->short_name,
4694                                          session,
4695                                          sender_address,
4696                                          sender_address_len);
4697       if (peer_address != NULL)
4698         {
4699           peer_address->distance = distance;
4700           if (GNUNET_YES == peer_address->validated)
4701             mark_address_connected (peer_address);
4702           peer_address->timeout
4703             =
4704             GNUNET_TIME_relative_to_absolute
4705             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4706           schedule_next_ping (peer_address);
4707         }
4708       /* update traffic received amount ... */
4709       msize = ntohs (message->size);
4710       GNUNET_STATISTICS_update (stats,
4711                                 gettext_noop ("# bytes received from other peers"),
4712                                 msize,
4713                                 GNUNET_NO);
4714       n->distance = distance;
4715       n->peer_timeout =
4716         GNUNET_TIME_relative_to_absolute
4717         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4718       GNUNET_SCHEDULER_cancel (n->timeout_task);
4719       n->timeout_task =
4720         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4721                                       &neighbour_timeout_task, n);
4722       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4723         {
4724           /* dropping message due to frequent inbound volume violations! */
4725           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4726                       GNUNET_ERROR_TYPE_BULK,
4727                       _
4728                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"),
4729                       n->in_tracker.available_bytes_per_s__,
4730                       n->quota_violation_count);
4731           GNUNET_STATISTICS_update (stats,
4732                                     gettext_noop ("# bandwidth quota violations by other peers"),
4733                                     1,
4734                                     GNUNET_NO);
4735           return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4736         }
4737
4738 #if DEBUG_PING_PONG
4739           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4740                       "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4741                       ntohs (message->type),
4742                       ntohs (message->size),
4743                       GNUNET_i2s (peer));
4744 #endif
4745       switch (ntohs (message->type))
4746         {
4747         case GNUNET_MESSAGE_TYPE_HELLO:
4748           GNUNET_STATISTICS_update (stats,
4749                                     gettext_noop ("# HELLO messages received from other peers"),
4750                                     1,
4751                                     GNUNET_NO);
4752           process_hello (plugin, message);
4753           break;
4754         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4755           handle_ping (plugin, message, peer, session, sender_address, sender_address_len);
4756           break;
4757         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4758           handle_pong (plugin, message, peer, sender_address, sender_address_len);
4759           break;
4760         default:
4761           handle_payload_message (message, n);
4762           break;
4763         }
4764     }
4765   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4766   if (ret.rel_value > 0)
4767     {
4768       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4769                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4770                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
4771                   (unsigned int) n->in_tracker.available_bytes_per_s__,
4772                   (unsigned long long) ret.rel_value);
4773       GNUNET_STATISTICS_update (stats,
4774                                 gettext_noop ("# ms throttling suggested"),
4775                                 (int64_t) ret.rel_value,
4776                                 GNUNET_NO);
4777     }
4778   return ret;
4779 }
4780
4781 /**
4782  * Handle START-message.  This is the first message sent to us
4783  * by any client which causes us to add it to our list.
4784  *
4785  * @param cls closure (always NULL)
4786  * @param client identification of the client
4787  * @param message the actual message
4788  */
4789 static void
4790 handle_start (void *cls,
4791               struct GNUNET_SERVER_Client *client,
4792               const struct GNUNET_MessageHeader *message)
4793 {
4794   const struct StartMessage *start;
4795   struct TransportClient *c;
4796   struct ConnectInfoMessage cim;
4797   struct NeighbourList *n;
4798
4799   start = (const struct StartMessage*) message;
4800 #if DEBUG_TRANSPORT
4801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4802               "Received `%s' request from client\n", "START");
4803 #endif
4804   c = clients;
4805   while (c != NULL)
4806     {
4807       if (c->client == client)
4808         {
4809           /* client already on our list! */
4810           GNUNET_break (0);
4811           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4812           return;
4813         }
4814       c = c->next;
4815     }
4816   if ( (GNUNET_NO != ntohl (start->do_check)) &&
4817        (0 != memcmp (&start->self,
4818                      &my_identity,
4819                      sizeof (struct GNUNET_PeerIdentity))) )
4820     {
4821       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4822                   _("Rejecting control connection from peer `%s', which is not me!\n"),
4823                   GNUNET_i2s (&start->self));
4824       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4825       return;
4826     }
4827   c = GNUNET_malloc (sizeof (struct TransportClient));
4828   c->next = clients;
4829   clients = c;
4830   c->client = client;
4831   if (our_hello != NULL)
4832     {
4833 #if DEBUG_TRANSPORT
4834       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4835                   "Sending our own `%s' to new client\n", "HELLO");
4836 #endif
4837       transmit_to_client (c,
4838                           (const struct GNUNET_MessageHeader *) our_hello,
4839                           GNUNET_NO);
4840       /* tell new client about all existing connections */
4841       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
4842       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4843       n = neighbours;
4844       while (n != NULL)
4845         {
4846           if (GNUNET_YES == n->received_pong)
4847             {
4848               cim.id = n->id;
4849               cim.latency = GNUNET_TIME_relative_hton (n->latency);
4850               cim.distance = htonl (n->distance);
4851               transmit_to_client (c, &cim.header, GNUNET_NO);
4852             }
4853             n = n->next;
4854         }
4855     }
4856   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4857 }
4858
4859
4860 /**
4861  * Handle HELLO-message.
4862  *
4863  * @param cls closure (always NULL)
4864  * @param client identification of the client
4865  * @param message the actual message
4866  */
4867 static void
4868 handle_hello (void *cls,
4869               struct GNUNET_SERVER_Client *client,
4870               const struct GNUNET_MessageHeader *message)
4871 {
4872   int ret;
4873
4874   GNUNET_STATISTICS_update (stats,
4875                             gettext_noop ("# HELLOs received from clients"),
4876                             1,
4877                             GNUNET_NO);
4878   ret = process_hello (NULL, message);
4879   GNUNET_SERVER_receive_done (client, ret);
4880 }
4881
4882
4883 /**
4884  * Closure for 'transmit_client_message'; followed by
4885  * 'msize' bytes of the actual message.
4886  */
4887 struct TransmitClientMessageContext
4888 {
4889   /**
4890    * Client on whom's behalf we are sending.
4891    */
4892   struct GNUNET_SERVER_Client *client;
4893
4894   /**
4895    * Timeout for the transmission.
4896    */
4897   struct GNUNET_TIME_Absolute timeout;
4898
4899   /**
4900    * Message priority.
4901    */
4902   uint32_t priority;
4903
4904   /**
4905    * Size of the message in bytes.
4906    */
4907   uint16_t msize;
4908 };
4909
4910
4911 /**
4912  * Schedule transmission of a message we got from a client to a peer.
4913  *
4914  * @param cls the 'struct TransmitClientMessageContext*'
4915  * @param n destination, or NULL on error (in that case, drop the message)
4916  */
4917 static void
4918 transmit_client_message (void *cls,
4919                          struct NeighbourList *n)
4920 {
4921   struct TransmitClientMessageContext *tcmc = cls;
4922   struct TransportClient *tc;
4923
4924   tc = clients;
4925   while ((tc != NULL) && (tc->client != tcmc->client))
4926     tc = tc->next;
4927
4928   if (n != NULL)
4929     {
4930       transmit_to_peer (tc, NULL, tcmc->priority,
4931                         GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
4932                         (char *)&tcmc[1],
4933                         tcmc->msize, GNUNET_NO, n);
4934     }
4935   GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
4936   GNUNET_SERVER_client_drop (tcmc->client);
4937   GNUNET_free (tcmc);
4938 }
4939
4940
4941 /**
4942  * Handle SEND-message.
4943  *
4944  * @param cls closure (always NULL)
4945  * @param client identification of the client
4946  * @param message the actual message
4947  */
4948 static void
4949 handle_send (void *cls,
4950              struct GNUNET_SERVER_Client *client,
4951              const struct GNUNET_MessageHeader *message)
4952 {
4953   const struct OutboundMessage *obm;
4954   const struct GNUNET_MessageHeader *obmm;
4955   struct TransmitClientMessageContext *tcmc;
4956   uint16_t size;
4957   uint16_t msize;
4958
4959   size = ntohs (message->size);
4960   if (size <
4961       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
4962     {
4963       GNUNET_break (0);
4964       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4965       return;
4966     }
4967   GNUNET_STATISTICS_update (stats,
4968                             gettext_noop ("# payload received for other peers"),
4969                             size,
4970                             GNUNET_NO);
4971   obm = (const struct OutboundMessage *) message;
4972   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
4973   msize = size - sizeof (struct OutboundMessage);
4974
4975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4976               "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
4977               "SEND", GNUNET_i2s (&obm->peer),
4978               ntohs (obmm->type),
4979               msize);
4980
4981   tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
4982   tcmc->client = client;
4983   tcmc->priority = ntohl (obm->priority);
4984   tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
4985   tcmc->msize = msize;
4986   /* FIXME: this memcpy can be up to 7% of our total runtime */
4987   memcpy (&tcmc[1], obmm, msize);
4988   GNUNET_SERVER_client_keep (client);
4989   setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
4990                               &transmit_client_message,
4991                               tcmc);
4992 }
4993
4994
4995 /**
4996  * Handle request connect message
4997  *
4998  * @param cls closure (always NULL)
4999  * @param client identification of the client
5000  * @param message the actual message
5001  */
5002 static void
5003 handle_request_connect (void *cls,
5004                         struct GNUNET_SERVER_Client *client,
5005                         const struct GNUNET_MessageHeader *message)
5006 {
5007   const struct TransportRequestConnectMessage *trcm =
5008     (const struct TransportRequestConnectMessage *) message;
5009
5010   GNUNET_STATISTICS_update (stats,
5011                             gettext_noop ("# REQUEST CONNECT messages received"),
5012                             1,
5013                             GNUNET_NO);
5014   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a request connect message for peer %s\n", GNUNET_i2s(&trcm->peer));
5015   setup_peer_check_blacklist (&trcm->peer, GNUNET_YES,
5016                               NULL, NULL);
5017   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5018 }
5019
5020 /**
5021  * Handle SET_QUOTA-message.
5022  *
5023  * @param cls closure (always NULL)
5024  * @param client identification of the client
5025  * @param message the actual message
5026  */
5027 static void
5028 handle_set_quota (void *cls,
5029                   struct GNUNET_SERVER_Client *client,
5030                   const struct GNUNET_MessageHeader *message)
5031 {
5032   const struct QuotaSetMessage *qsm =
5033     (const struct QuotaSetMessage *) message;
5034   struct NeighbourList *n;
5035
5036   GNUNET_STATISTICS_update (stats,
5037                             gettext_noop ("# SET QUOTA messages received"),
5038                             1,
5039                             GNUNET_NO);
5040   n = find_neighbour (&qsm->peer);
5041   if (n == NULL)
5042     {
5043       GNUNET_SERVER_receive_done (client, GNUNET_OK);
5044       GNUNET_STATISTICS_update (stats,
5045                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
5046                                 1,
5047                                 GNUNET_NO);
5048       return;
5049     }
5050 #if DEBUG_TRANSPORT
5051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5052               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
5053               "SET_QUOTA",
5054               (unsigned int) ntohl (qsm->quota.value__),
5055               (unsigned int) n->in_tracker.available_bytes_per_s__,
5056               GNUNET_i2s (&qsm->peer));
5057 #endif
5058   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
5059                                          qsm->quota);
5060   if (0 == ntohl (qsm->quota.value__))
5061     {
5062       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5063                 "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&n->id),
5064                 "SET_QUOTA");
5065       disconnect_neighbour (n, GNUNET_NO);
5066     }
5067   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5068 }
5069
5070
5071 /**
5072  * Take the given address and append it to the set of results sent back to
5073  * the client.
5074  *
5075  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
5076  * @param address the resolved name, NULL to indicate the last response
5077  */
5078 static void
5079 transmit_address_to_client (void *cls, const char *address)
5080 {
5081   struct GNUNET_SERVER_TransmitContext *tc = cls;
5082   size_t slen;
5083
5084   if (NULL == address)
5085     slen = 0;
5086   else
5087     slen = strlen (address) + 1;
5088
5089   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
5090                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5091   if (NULL == address)
5092     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
5093 }
5094
5095
5096 /**
5097  * Handle AddressLookup-message.
5098  *
5099  * @param cls closure (always NULL)
5100  * @param client identification of the client
5101  * @param message the actual message
5102  */
5103 static void
5104 handle_address_lookup (void *cls,
5105                        struct GNUNET_SERVER_Client *client,
5106                        const struct GNUNET_MessageHeader *message)
5107 {
5108   const struct AddressLookupMessage *alum;
5109   struct TransportPlugin *lsPlugin;
5110   const char *nameTransport;
5111   const char *address;
5112   uint16_t size;
5113   struct GNUNET_SERVER_TransmitContext *tc;
5114   struct GNUNET_TIME_Absolute timeout;
5115   struct GNUNET_TIME_Relative rtimeout;
5116   int32_t numeric;
5117
5118   size = ntohs (message->size);
5119   if (size < sizeof (struct AddressLookupMessage))
5120     {
5121       GNUNET_break_op (0);
5122       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5123       return;
5124     }
5125   alum = (const struct AddressLookupMessage *) message;
5126   uint32_t addressLen = ntohl (alum->addrlen);
5127   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
5128     {
5129       GNUNET_break_op (0);
5130       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5131       return;
5132     }
5133   address = (const char *) &alum[1];
5134   nameTransport = (const char *) &address[addressLen];
5135   if (nameTransport
5136       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
5137     {
5138       GNUNET_break_op (0);
5139       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5140       return;
5141     }
5142   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
5143   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
5144   numeric = ntohl (alum->numeric_only);
5145   lsPlugin = find_transport (nameTransport);
5146   if (NULL == lsPlugin)
5147     {
5148       tc = GNUNET_SERVER_transmit_context_create (client);
5149       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
5150                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
5151       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
5152       return;
5153     }
5154   tc = GNUNET_SERVER_transmit_context_create (client);
5155   lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
5156                                          nameTransport,
5157                                          address, addressLen,
5158                                          numeric,
5159                                          rtimeout,
5160                                          &transmit_address_to_client, tc);
5161 }
5162
5163
5164 /**
5165  * Setup the environment for this plugin.
5166  */
5167 static void
5168 create_environment (struct TransportPlugin *plug)
5169 {
5170   plug->env.cfg = cfg;
5171   plug->env.my_identity = &my_identity;
5172   plug->env.our_hello = &our_hello;
5173   plug->env.cls = plug;
5174   plug->env.receive = &plugin_env_receive;
5175   plug->env.notify_address = &plugin_env_notify_address;
5176   plug->env.session_end = &plugin_env_session_end;
5177   plug->env.max_connections = max_connect_per_transport;
5178   plug->env.stats = stats;
5179 }
5180
5181
5182 /**
5183  * Start the specified transport (load the plugin).
5184  */
5185 static void
5186 start_transport (struct GNUNET_SERVER_Handle *server,
5187                  const char *name)
5188 {
5189   struct TransportPlugin *plug;
5190   char *libname;
5191
5192   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5193               _("Loading `%s' transport plugin\n"), name);
5194   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
5195   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
5196   create_environment (plug);
5197   plug->short_name = GNUNET_strdup (name);
5198   plug->lib_name = libname;
5199   plug->next = plugins;
5200   plugins = plug;
5201   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
5202   if (plug->api == NULL)
5203     {
5204       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5205                   _("Failed to load transport plugin for `%s'\n"), name);
5206       GNUNET_free (plug->short_name);
5207       plugins = plug->next;
5208       GNUNET_free (libname);
5209       GNUNET_free (plug);
5210     }
5211 }
5212
5213
5214 /**
5215  * Called whenever a client is disconnected.  Frees our
5216  * resources associated with that client.
5217  *
5218  * @param cls closure
5219  * @param client identification of the client
5220  */
5221 static void
5222 client_disconnect_notification (void *cls,
5223                                 struct GNUNET_SERVER_Client *client)
5224 {
5225   struct TransportClient *pos;
5226   struct TransportClient *prev;
5227   struct ClientMessageQueueEntry *mqe;
5228   struct Blacklisters *bl;
5229   struct BlacklistCheck *bc;
5230
5231   if (client == NULL)
5232     return;
5233 #if DEBUG_TRANSPORT
5234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
5235               "Client disconnected, cleaning up.\n");
5236 #endif
5237   /* clean up blacklister */
5238   bl = bl_head;
5239   while (bl != NULL)
5240     {
5241       if (bl->client == client)
5242         {
5243           bc = bc_head;
5244           while (bc != NULL)
5245             {
5246               if (bc->bl_pos == bl)
5247                 {
5248                   bc->bl_pos = bl->next;
5249                   if (bc->th != NULL)
5250                     {
5251                       GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
5252                       bc->th = NULL;            
5253                     }
5254                   if (bc->task == GNUNET_SCHEDULER_NO_TASK)
5255                     bc->task = GNUNET_SCHEDULER_add_now (&do_blacklist_check,
5256                                                          bc);
5257                   break;
5258                 }
5259               bc = bc->next;
5260             }
5261           GNUNET_CONTAINER_DLL_remove (bl_head,
5262                                        bl_tail,
5263                                        bl);
5264           GNUNET_SERVER_client_drop (bl->client);
5265           GNUNET_free (bl);
5266           break;
5267         }
5268       bl = bl->next;
5269     }
5270   /* clean up 'normal' clients */
5271   prev = NULL;
5272   pos = clients;
5273   while ((pos != NULL) && (pos->client != client))
5274     {
5275       prev = pos;
5276       pos = pos->next;
5277     }
5278   if (pos == NULL)
5279     return;
5280   while (NULL != (mqe = pos->message_queue_head))
5281     {
5282       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
5283                                    pos->message_queue_tail,
5284                                    mqe);
5285       pos->message_count--;
5286       GNUNET_free (mqe);
5287     }
5288   if (prev == NULL)
5289     clients = pos->next;
5290   else
5291     prev->next = pos->next;
5292   if (GNUNET_YES == pos->tcs_pending)
5293     {
5294       pos->client = NULL;
5295       return;
5296     }
5297   if (pos->th != NULL)
5298     {
5299       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
5300       pos->th = NULL;
5301     }
5302   GNUNET_break (0 == pos->message_count);
5303   GNUNET_free (pos);
5304 }
5305
5306
5307 /**
5308  * Function called when the service shuts down.  Unloads our plugins
5309  * and cancels pending validations.
5310  *
5311  * @param cls closure, unused
5312  * @param tc task context (unused)
5313  */
5314 static void
5315 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5316 {
5317   struct TransportPlugin *plug;
5318   struct OwnAddressList *al;
5319   struct CheckHelloValidatedContext *chvc;
5320
5321   while (neighbours != NULL)
5322     {
5323       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5324               "Disconnecting peer `%4s', %s\n", GNUNET_i2s(&neighbours->id),
5325               "SHUTDOWN_TASK");
5326       disconnect_neighbour (neighbours, GNUNET_NO);
5327     }
5328 #if DEBUG_TRANSPORT
5329   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5330               "Transport service is unloading plugins...\n");
5331 #endif
5332   while (NULL != (plug = plugins))
5333     {
5334       plugins = plug->next;
5335       if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
5336         {
5337           GNUNET_SCHEDULER_cancel (plug->address_update_task);
5338           plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
5339         }
5340       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
5341       GNUNET_free (plug->lib_name);
5342       GNUNET_free (plug->short_name);
5343       while (NULL != (al = plug->addresses))
5344         {
5345           plug->addresses = al->next;
5346           GNUNET_free (al);
5347         }
5348       GNUNET_free (plug);
5349     }
5350   if (my_private_key != NULL)
5351     GNUNET_CRYPTO_rsa_key_free (my_private_key);
5352   GNUNET_free_non_null (our_hello);
5353
5354   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
5355                                          &abort_validation,
5356                                          NULL);
5357   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5358   validation_map = NULL;
5359
5360   /* free 'chvc' data structure */
5361   while (NULL != (chvc = chvc_head))
5362     {
5363       chvc_head = chvc->next;
5364       if (chvc->piter != NULL)
5365         {
5366           GNUNET_PEERINFO_iterate_cancel (chvc->piter);
5367           GNUNET_STATISTICS_update (stats,
5368                                     gettext_noop ("# outstanding peerinfo iterate requests"),
5369                                     -1,
5370                                     GNUNET_NO);
5371         }
5372       else
5373         GNUNET_break (0);
5374       GNUNET_assert (chvc->ve_count == 0);
5375       GNUNET_free (chvc);
5376     }
5377   chvc_tail = NULL;
5378
5379   if (stats != NULL)
5380     {
5381       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5382       stats = NULL;
5383     }
5384   if (peerinfo != NULL)
5385     {
5386       GNUNET_PEERINFO_disconnect (peerinfo);
5387       peerinfo = NULL;
5388     }
5389   /* Can we assume those are gone by now, or do we need to clean up
5390      explicitly!? */
5391   GNUNET_break (bl_head == NULL);
5392   GNUNET_break (bc_head == NULL);
5393 }
5394
5395
5396 /**
5397  * Initiate transport service.
5398  *
5399  * @param cls closure
5400  * @param server the initialized server
5401  * @param c configuration to use
5402  */
5403 static void
5404 run (void *cls,
5405      struct GNUNET_SERVER_Handle *server,
5406      const struct GNUNET_CONFIGURATION_Handle *c)
5407 {
5408   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
5409     {&handle_start, NULL,
5410      GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
5411     {&handle_hello, NULL,
5412      GNUNET_MESSAGE_TYPE_HELLO, 0},
5413     {&handle_send, NULL,
5414      GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
5415     {&handle_request_connect, NULL,
5416      GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT, sizeof(struct TransportRequestConnectMessage)},
5417     {&handle_set_quota, NULL,
5418      GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
5419     {&handle_address_lookup, NULL,
5420      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
5421      0},
5422     {&handle_blacklist_init, NULL,
5423      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
5424     {&handle_blacklist_reply, NULL,
5425      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
5426     {NULL, NULL, 0, 0}
5427   };
5428   char *plugs;
5429   char *pos;
5430   int no_transports;
5431   unsigned long long tneigh;
5432   char *keyfile;
5433
5434   cfg = c;
5435   stats = GNUNET_STATISTICS_create ("transport", cfg);
5436   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
5437   /* parse configuration */
5438   if ((GNUNET_OK !=
5439        GNUNET_CONFIGURATION_get_value_number (c,
5440                                               "TRANSPORT",
5441                                               "NEIGHBOUR_LIMIT",
5442                                               &tneigh)) ||
5443       (GNUNET_OK !=
5444        GNUNET_CONFIGURATION_get_value_filename (c,
5445                                                 "GNUNETD",
5446                                                 "HOSTKEY", &keyfile)))
5447     {
5448       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5449                   _
5450                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
5451       GNUNET_SCHEDULER_shutdown ();
5452       if (stats != NULL)
5453         {
5454           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5455           stats = NULL;
5456         }
5457       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5458       validation_map = NULL;
5459       return;
5460     }
5461   max_connect_per_transport = (uint32_t) tneigh;
5462   peerinfo = GNUNET_PEERINFO_connect (cfg);
5463   if (peerinfo == NULL)
5464     {
5465       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5466                   _("Could not access PEERINFO service.  Exiting.\n")); 
5467       GNUNET_SCHEDULER_shutdown ();
5468       if (stats != NULL)
5469         {
5470           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5471           stats = NULL;
5472         }
5473       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5474       validation_map = NULL;
5475       GNUNET_free (keyfile);
5476       return;
5477     }
5478   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
5479   GNUNET_free (keyfile);
5480   if (my_private_key == NULL)
5481     {
5482       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5483                   _
5484                   ("Transport service could not access hostkey.  Exiting.\n"));
5485       GNUNET_SCHEDULER_shutdown ();
5486       if (stats != NULL)
5487         {
5488           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
5489           stats = NULL;
5490         }
5491       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
5492       validation_map = NULL;
5493       return;
5494     }
5495   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
5496   GNUNET_CRYPTO_hash (&my_public_key,
5497                       sizeof (my_public_key), &my_identity.hashPubKey);
5498   /* setup notification */
5499   GNUNET_SERVER_disconnect_notify (server,
5500                                    &client_disconnect_notification, NULL);
5501   /* load plugins... */
5502   no_transports = 1;
5503   if (GNUNET_OK ==
5504       GNUNET_CONFIGURATION_get_value_string (c,
5505                                              "TRANSPORT", "PLUGINS", &plugs))
5506     {
5507       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5508                   _("Starting transport plugins `%s'\n"), plugs);
5509       pos = strtok (plugs, " ");
5510       while (pos != NULL)
5511         {
5512           start_transport (server, pos);
5513           no_transports = 0;
5514           pos = strtok (NULL, " ");
5515         }
5516       GNUNET_free (plugs);
5517     }
5518   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5519                                 &shutdown_task, NULL);
5520   if (no_transports)
5521     refresh_hello ();
5522
5523 #if DEBUG_TRANSPORT
5524   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
5525 #endif
5526   /* If we have a blacklist file, read from it */
5527   read_blacklist_file(cfg);
5528   /* process client requests */
5529   GNUNET_SERVER_add_handlers (server, handlers);
5530 }
5531
5532
5533 /**
5534  * The main function for the transport service.
5535  *
5536  * @param argc number of arguments from the command line
5537  * @param argv command line arguments
5538  * @return 0 ok, 1 on error
5539  */
5540 int
5541 main (int argc, char *const *argv)
5542 {
5543   a2s (NULL, NULL, 0); /* make compiler happy */
5544   return (GNUNET_OK ==
5545           GNUNET_SERVICE_run (argc,
5546                               argv,
5547                               "transport",
5548                               GNUNET_SERVICE_OPTION_NONE,
5549                               &run, NULL)) ? 0 : 1;
5550 }
5551
5552 /* end of gnunet-service-transport.c */