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