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