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