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