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