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