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