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