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