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