extra check for blacklist, spelling
[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 2, 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 "plugin_transport.h"
40 #include "transport.h"
41
42 #define DEBUG_BLACKLIST GNUNET_NO
43
44 #define DEBUG_PING_PONG GNUNET_NO
45
46 #define SIGN_USELESS GNUNET_NO
47
48 /**
49  * Should we do some additional checks (to validate behavior
50  * of clients)?
51  */
52 #define EXTRA_CHECKS GNUNET_YES
53
54 /**
55  * How many messages can we have pending for a given client process
56  * before we start to drop incoming messages?  We typically should
57  * have only one client and so this would be the primary buffer for
58  * messages, so the number should be chosen rather generously.
59  *
60  * The expectation here is that most of the time the queue is large
61  * enough so that a drop is virtually never required.  Note that
62  * this value must be about as large as 'TOTAL_MSGS' in the
63  * 'test_transport_api_reliability.c', otherwise that testcase may
64  * fail.
65  */
66 #define MAX_PENDING (128 * 1024)
67
68 /**
69  * Size of the per-transport blacklist hash maps.
70  */
71 #define TRANSPORT_BLACKLIST_HT_SIZE 16
72
73 /**
74  * How often should we try to reconnect to a peer using a particular
75  * transport plugin before giving up?  Note that the plugin may be
76  * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
77  */
78 #define MAX_CONNECT_RETRY 3
79
80 /**
81  * Limit on the number of ready-to-run tasks when validating 
82  * HELLOs.  If more tasks are ready to run, we will drop 
83  * HELLOs instead of validating them.
84  */
85 #define MAX_HELLO_LOAD 4
86
87 /**
88  * How often must a peer violate bandwidth quotas before we start
89  * to simply drop its messages?
90  */
91 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
92
93 /**
94  * How long until a HELLO verification attempt should time out?
95  * Must be rather small, otherwise a partially successful HELLO
96  * validation (some addresses working) might not be available
97  * before a client's request for a connection fails for good.
98  * Besides, if a single request to an address takes a long time,
99  * then the peer is unlikely worthwhile anyway.
100  */
101 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
102
103 /**
104  * Priority to use for PONG messages.
105  */
106 #define TRANSPORT_PONG_PRIORITY 4
107
108 /**
109  * How often do we re-add (cheaper) plugins to our list of plugins
110  * to try for a given connected peer?
111  */
112 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
113
114 /**
115  * After how long do we expire an address in a HELLO that we just
116  * validated?  This value is also used for our own addresses when we
117  * create a HELLO.
118  */
119 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
120
121
122 /**
123  * How long before an existing address expires should we again try to
124  * validate it?  Must be (significantly) smaller than
125  * HELLO_ADDRESS_EXPIRATION.
126  */
127 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
128
129 /**
130  * Maximum frequency for re-evaluating latencies for all transport addresses.
131  */
132 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
133
134 /**
135  * Maximum frequency for re-evaluating latencies for connected addresses.
136  */
137 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
138
139
140 /**
141  * List of addresses of other peers
142  */
143 struct ForeignAddressList
144 {
145   /**
146    * This is a linked list.
147    */
148   struct ForeignAddressList *next;
149
150   /**
151    * Which ready list does this entry belong to.
152    */
153   struct ReadyList *ready_list;
154
155   /**
156    * How long until we auto-expire this address (unless it is
157    * re-confirmed by the transport)?
158    */
159   struct GNUNET_TIME_Absolute expires;
160
161   /**
162    * Task used to re-validate addresses, updates latencies and
163    * verifies liveness.
164    */
165   GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
166
167   /**
168    * The address.
169    */
170   const void *addr;
171
172   /**
173    * Session (or NULL if no valid session currently exists or if the
174    * plugin does not use sessions).
175    */
176   struct Session *session;
177
178   /**
179    * What was the last latency observed for this address, plugin and peer?
180    */
181   struct GNUNET_TIME_Relative latency;
182
183   /**
184    * If we did not successfully transmit a message to the given peer
185    * via this connection during the specified time, we should consider
186    * the connection to be dead.  This is used in the case that a TCP
187    * transport simply stalls writing to the stream but does not
188    * formerly get a signal that the other peer died.
189    */
190   struct GNUNET_TIME_Absolute timeout;
191
192   /**
193    * How often have we tried to connect using this plugin?  Used to
194    * discriminate against addresses that do not work well.
195    * FIXME: not yet used, but should be!
196    */
197   unsigned int connect_attempts;
198
199   /**
200    * DV distance to this peer (1 if no DV is used). 
201    * FIXME: need to set this from transport plugins!
202    */
203   uint32_t distance;
204
205   /**
206    * Length of addr.
207    */
208   uint16_t addrlen;
209
210   /**
211    * Have we ever estimated the latency of this address?  Used to
212    * ensure that the first time we add an address, we immediately
213    * probe its latency.
214    */
215   int8_t estimated;
216
217   /**
218    * Are we currently connected via this address?  The first time we
219    * successfully transmit or receive data to a peer via a particular
220    * address, we set this to GNUNET_YES.  If we later get an error
221    * (disconnect notification, transmission failure, timeout), we set
222    * it back to GNUNET_NO.  
223    */
224   int8_t connected;
225
226   /**
227    * Is this plugin currently busy transmitting to the specific target?
228    * GNUNET_NO if not (initial, default state is GNUNET_NO).   Internal
229    * messages do not count as 'in transmit'.
230    */
231   int8_t in_transmit;
232
233   /**
234    * Has this address been validated yet?
235    */
236   int8_t validated;
237
238 };
239
240
241 /**
242  * Entry in linked list of network addresses for ourselves.
243  */
244 struct OwnAddressList
245 {
246   /**
247    * This is a linked list.
248    */
249   struct OwnAddressList *next;
250
251   /**
252    * The address, actually a pointer to the end
253    * of this struct.  Do not free!
254    */
255   const void *addr;
256   
257   /**
258    * How long until we auto-expire this address (unless it is
259    * re-confirmed by the transport)?
260    */
261   struct GNUNET_TIME_Absolute expires;
262
263   /**
264    * Length of addr.
265    */
266   uint16_t addrlen;
267
268 };
269
270
271 /**
272  * Entry in linked list of all of our plugins.
273  */
274 struct TransportPlugin
275 {
276
277   /**
278    * This is a linked list.
279    */
280   struct TransportPlugin *next;
281
282   /**
283    * API of the transport as returned by the plugin's
284    * initialization function.
285    */
286   struct GNUNET_TRANSPORT_PluginFunctions *api;
287
288   /**
289    * Short name for the plugin (i.e. "tcp").
290    */
291   char *short_name;
292
293   /**
294    * Name of the library (i.e. "gnunet_plugin_transport_tcp").
295    */
296   char *lib_name;
297
298   /**
299    * List of our known addresses for this transport.
300    */
301   struct OwnAddressList *addresses;
302
303   /**
304    * Environment this transport service is using
305    * for this plugin.
306    */
307   struct GNUNET_TRANSPORT_PluginEnvironment env;
308
309   /**
310    * ID of task that is used to clean up expired addresses.
311    */
312   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
313
314   /**
315    * Set to GNUNET_YES if we need to scrap the existing list of
316    * "addresses" and start fresh when we receive the next address
317    * update from a transport.  Set to GNUNET_NO if we should just add
318    * the new address to the list and wait for the commit call.
319    */
320   int rebuild;
321
322   /**
323    * Hashmap of blacklisted peers for this particular transport.
324    */
325   struct GNUNET_CONTAINER_MultiHashMap *blacklist;
326 };
327
328 struct NeighbourList;
329
330 /**
331  * For each neighbour we keep a list of messages
332  * that we still want to transmit to the neighbour.
333  */
334 struct MessageQueue
335 {
336
337   /**
338    * This is a doubly linked list.
339    */
340   struct MessageQueue *next;
341
342   /**
343    * This is a doubly linked list.
344    */
345   struct MessageQueue *prev;
346
347   /**
348    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
349    * stuck together in memory.  Allocated at the end of this struct.
350    */
351   const char *message_buf;
352
353   /**
354    * Size of the message buf
355    */
356   size_t message_buf_size;
357
358   /**
359    * Client responsible for queueing the message;
360    * used to check that a client has no two messages
361    * pending for the same target.  Can be NULL.
362    */
363   struct TransportClient *client;
364
365   /**
366    * Using which specific address should we send this message?
367    */
368   struct ForeignAddressList *specific_address;
369
370   /**
371    * Peer ID of the Neighbour this entry belongs to.
372    */
373   struct GNUNET_PeerIdentity neighbour_id;
374
375   /**
376    * Plugin that we used for the transmission.
377    * NULL until we scheduled a transmission.
378    */
379   struct TransportPlugin *plugin;
380
381   /**
382    * At what time should we fail?
383    */
384   struct GNUNET_TIME_Absolute timeout;
385
386   /**
387    * Internal message of the transport system that should not be
388    * included in the usual SEND-SEND_OK transmission confirmation
389    * traffic management scheme.  Typically, "internal_msg" will
390    * be set whenever "client" is NULL (but it is not strictly
391    * required).
392    */
393   int internal_msg;
394
395   /**
396    * How important is the message?
397    */
398   unsigned int priority;
399
400 };
401
402
403 /**
404  * For a given Neighbour, which plugins are available
405  * to talk to this peer and what are their costs?
406  */
407 struct ReadyList
408 {
409   /**
410    * This is a linked list.
411    */
412   struct ReadyList *next;
413
414   /**
415    * Which of our transport plugins does this entry
416    * represent?
417    */
418   struct TransportPlugin *plugin;
419
420   /**
421    * Transport addresses, latency, and readiness for
422    * this particular plugin.
423    */
424   struct ForeignAddressList *addresses;
425
426   /**
427    * To which neighbour does this ready list belong to?
428    */
429   struct NeighbourList *neighbour;
430
431 };
432
433
434 /**
435  * Entry in linked list of all of our current neighbours.
436  */
437 struct NeighbourList
438 {
439
440   /**
441    * This is a linked list.
442    */
443   struct NeighbourList *next;
444
445   /**
446    * Which of our transports is connected to this peer
447    * and what is their status?
448    */
449   struct ReadyList *plugins;
450
451   /**
452    * Head of list of messages we would like to send to this peer;
453    * must contain at most one message per client.
454    */
455   struct MessageQueue *messages_head;
456
457   /**
458    * Tail of list of messages we would like to send to this peer; must
459    * contain at most one message per client.
460    */
461   struct MessageQueue *messages_tail;
462
463   /**
464    * Buffer for at most one payload message used when we receive
465    * payload data before our PING-PONG has succeeded.  We then
466    * store such messages in this intermediary buffer until the
467    * connection is fully up.  
468    */
469   struct GNUNET_MessageHeader *pre_connect_message_buffer;
470
471   /**
472    * Context for peerinfo iteration.
473    * NULL after we are done processing peerinfo's information.
474    */
475   struct GNUNET_PEERINFO_IteratorContext *piter;
476
477   /**
478    * Public key for this peer.   Valid only if the respective flag is set below.
479    */
480   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
481
482   /**
483    * Identity of this neighbour.
484    */
485   struct GNUNET_PeerIdentity id;
486
487   /**
488    * ID of task scheduled to run when this peer is about to
489    * time out (will free resources associated with the peer).
490    */
491   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
492
493   /**
494    * ID of task scheduled to run when we should retry transmitting
495    * the head of the message queue.  Actually triggered when the
496    * transmission is timing out (we trigger instantly when we have
497    * a chance of success).
498    */
499   GNUNET_SCHEDULER_TaskIdentifier retry_task;
500
501   /**
502    * How long until we should consider this peer dead
503    * (if we don't receive another message in the
504    * meantime)?
505    */
506   struct GNUNET_TIME_Absolute peer_timeout;
507
508   /**
509    * Tracker for inbound bandwidth.
510    */
511   struct GNUNET_BANDWIDTH_Tracker in_tracker;
512
513   /**
514    * The latency we have seen for this particular address for
515    * this particular peer.  This latency may have been calculated
516    * over multiple transports.  This value reflects how long it took
517    * us to receive a response when SENDING via this particular
518    * transport/neighbour/address combination!
519    *
520    * FIXME: we need to periodically send PINGs to update this
521    * latency (at least more often than the current "huge" (11h?)
522    * update interval).
523    */
524   struct GNUNET_TIME_Relative latency;
525
526   /**
527    * How often has the other peer (recently) violated the
528    * inbound traffic limit?  Incremented by 10 per violation,
529    * decremented by 1 per non-violation (for each
530    * time interval).
531    */
532   unsigned int quota_violation_count;
533
534   /**
535    * DV distance to this peer (1 if no DV is used). 
536    */
537   uint32_t distance;
538
539   /**
540    * Have we seen an PONG from this neighbour in the past (and
541    * not had a disconnect since)?
542    */
543   int received_pong;
544
545   /**
546    * Do we have a valid public key for this neighbour?
547    */
548   int public_key_valid;
549
550 };
551
552 /**
553  * Message used to ask a peer to validate receipt (to check an address
554  * from a HELLO).  
555  */
556 struct TransportPingMessage
557 {
558
559   /**
560    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
561    */
562   struct GNUNET_MessageHeader header;
563
564   /**
565    * Random challenge number (in network byte order).
566    */
567   uint32_t challenge GNUNET_PACKED;
568
569   /**
570    * Who is the intended recipient?
571    */
572   struct GNUNET_PeerIdentity target;
573
574 };
575
576
577 /**
578  * Message used to validate a HELLO.  The challenge is included in the
579  * confirmation to make matching of replies to requests possible.  The
580  * signature signs the original challenge number, our public key, the
581  * sender's address (so that the sender can check that the address we
582  * saw is plausible for him and possibly detect a MiM attack) and a
583  * timestamp (to limit replay).<p>
584  *
585  * This message is followed by the address of the
586  * client that we are observing (which is part of what
587  * is being signed).
588  */
589 struct TransportPongMessage
590 {
591
592   /**
593    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
594    */
595   struct GNUNET_MessageHeader header;
596
597   /**
598    * For padding, always zero.
599    */
600   uint32_t reserved GNUNET_PACKED;
601
602   /**
603    * Signature.
604    */
605   struct GNUNET_CRYPTO_RsaSignature signature;
606
607   /**
608    * What are we signing and why?
609    */
610   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
611
612   /**
613    * Random challenge number (in network byte order).
614    */
615   uint32_t challenge GNUNET_PACKED;
616
617   /**
618    * Who signed this message?
619    */
620   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
621
622   /**
623    * Size of address appended to this message
624    */
625   uint16_t addrlen;
626
627 };
628
629
630 /**
631  * Linked list of messages to be transmitted to the client.  Each
632  * entry is followed by the actual message.
633  */
634 struct ClientMessageQueueEntry
635 {
636   /**
637    * This is a doubly-linked list.
638    */
639   struct ClientMessageQueueEntry *next;
640
641   /**
642    * This is a doubly-linked list.
643    */
644   struct ClientMessageQueueEntry *prev;
645 };
646
647
648 /**
649  * Client connected to the transport service.
650  */
651 struct TransportClient
652 {
653
654   /**
655    * This is a linked list.
656    */
657   struct TransportClient *next;
658
659   /**
660    * Handle to the client.
661    */
662   struct GNUNET_SERVER_Client *client;
663
664   /**
665    * Linked list of messages yet to be transmitted to
666    * the client.
667    */
668   struct ClientMessageQueueEntry *message_queue_head;
669
670   /**
671    * Tail of linked list of messages yet to be transmitted to the
672    * client.
673    */
674   struct ClientMessageQueueEntry *message_queue_tail;
675
676   /**
677    * Current transmit request handle.
678    */ 
679   struct GNUNET_CONNECTION_TransmitHandle *th;
680
681   /**
682    * Is a call to "transmit_send_continuation" pending?  If so, we
683    * must not free this struct (even if the corresponding client
684    * disconnects) and instead only remove it from the linked list and
685    * set the "client" field to NULL.
686    */
687   int tcs_pending;
688
689   /**
690    * Length of the list of messages pending for this client.
691    */
692   unsigned int message_count;
693
694 };
695
696
697 /**
698  * Context of currently active requests to peerinfo
699  * for validation of HELLOs.
700  */
701 struct CheckHelloValidatedContext;
702
703
704 /**
705  * Entry in map of all HELLOs awaiting validation.
706  */
707 struct ValidationEntry
708 {
709
710   /**
711    * NULL if this entry is not part of a larger HELLO validation.
712    */
713   struct CheckHelloValidatedContext *chvc;
714
715   /**
716    * The address, actually a pointer to the end
717    * of this struct.  Do not free!
718    */
719   const void *addr;
720
721   /**
722    * Name of the transport.
723    */
724   char *transport_name;
725
726   /**
727    * The public key of the peer.
728    */
729   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
730
731   /**
732    * ID of task that will clean up this entry if we don't succeed
733    * with the validation first.
734    */
735   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
736
737   /**
738    * At what time did we send this validation?
739    */
740   struct GNUNET_TIME_Absolute send_time;
741
742   /**
743    * Session being validated (or NULL for none).
744    */
745   struct Session *session;
746
747   /**
748    * Challenge number we used.
749    */
750   uint32_t challenge;
751
752   /**
753    * Length of addr.
754    */
755   uint16_t addrlen;
756
757 };
758
759
760 /**
761  * Context of currently active requests to peerinfo
762  * for validation of HELLOs.
763  */
764 struct CheckHelloValidatedContext
765 {
766
767   /**
768    * This is a doubly-linked list.
769    */
770   struct CheckHelloValidatedContext *next;
771
772   /**
773    * This is a doubly-linked list.
774    */
775   struct CheckHelloValidatedContext *prev;
776
777   /**
778    * Hello that we are validating.
779    */
780   const struct GNUNET_HELLO_Message *hello;
781
782   /**
783    * Context for peerinfo iteration.
784    * NULL after we are done processing peerinfo's information.
785    */
786   struct GNUNET_PEERINFO_IteratorContext *piter;
787   
788   /**
789    * Was a HELLO known for this peer to peerinfo?
790    */
791   int hello_known;
792
793   /**
794    * Number of validation entries currently referring to this
795    * CHVC.
796    */
797   unsigned int ve_count;
798 };
799
800
801
802 /**
803  * Our HELLO message.
804  */
805 static struct GNUNET_HELLO_Message *our_hello;
806
807 /**
808  * Our public key.
809  */
810 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
811
812 /**
813  * Our identity.
814  */
815 static struct GNUNET_PeerIdentity my_identity;
816
817 /**
818  * Our private key.
819  */
820 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
821
822 /**
823  * Our scheduler.
824  */
825 struct GNUNET_SCHEDULER_Handle *sched;
826
827 /**
828  * Our configuration.
829  */
830 const struct GNUNET_CONFIGURATION_Handle *cfg;
831
832 /**
833  * Linked list of all clients to this service.
834  */
835 static struct TransportClient *clients;
836
837 /**
838  * All loaded plugins.
839  */
840 static struct TransportPlugin *plugins;
841
842 /**
843  * Handle to peerinfo service.
844  */
845 static struct GNUNET_PEERINFO_Handle *peerinfo;
846
847 /**
848  * All known neighbours and their HELLOs.
849  */
850 static struct NeighbourList *neighbours;
851
852 /**
853  * Number of neighbours we'd like to have.
854  */
855 static uint32_t max_connect_per_transport;
856
857 /**
858  * Head of linked list.
859  */
860 static struct CheckHelloValidatedContext *chvc_head;
861
862 /**
863  * Tail of linked list.
864  */
865 static struct CheckHelloValidatedContext *chvc_tail;
866
867 /**
868  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
869  * of the given peer that we are currently validating).
870  */
871 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
872
873 /**
874  * Handle for reporting statistics.
875  */
876 static struct GNUNET_STATISTICS_Handle *stats;
877
878
879 /**
880  * The peer specified by the given neighbour has timed-out or a plugin
881  * has disconnected.  We may either need to do nothing (other plugins
882  * still up), or trigger a full disconnect and clean up.  This
883  * function updates our state and do the necessary notifications.
884  * Also notifies our clients that the neighbour is now officially
885  * gone.
886  *
887  * @param n the neighbour list entry for the peer
888  * @param check should we just check if all plugins
889  *        disconnected or must we ask all plugins to
890  *        disconnect?
891  */
892 static void disconnect_neighbour (struct NeighbourList *n, int check);
893
894 /**
895  * Check the ready list for the given neighbour and if a plugin is
896  * ready for transmission (and if we have a message), do so!
897  *
898  * @param neighbour target peer for which to transmit
899  */
900 static void try_transmission_to_peer (struct NeighbourList *neighbour);
901
902
903 /**
904  * Find an entry in the neighbour list for a particular peer.
905  *  
906  * @return NULL if not found.
907  */
908 static struct NeighbourList *
909 find_neighbour (const struct GNUNET_PeerIdentity *key)
910 {
911   struct NeighbourList *head = neighbours;
912
913   while ((head != NULL) &&
914         (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
915     head = head->next;
916   return head;
917 }
918
919
920 /**
921  * Find an entry in the transport list for a particular transport.
922  *
923  * @return NULL if not found.
924  */
925 static struct TransportPlugin *
926 find_transport (const char *short_name)
927 {
928   struct TransportPlugin *head = plugins;
929   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
930     head = head->next;
931   return head;
932 }
933
934 /**
935  * Is a particular peer blacklisted for a particular transport?
936  *
937  * @param peer the peer to check for
938  * @param plugin the plugin used to connect to the peer
939  *
940  * @return GNUNET_YES if the peer is blacklisted, GNUNET_NO if not
941  */
942 static int
943 is_blacklisted (const struct GNUNET_PeerIdentity *peer, struct TransportPlugin *plugin)
944 {
945
946   if (plugin->blacklist != NULL)
947     {
948       if (GNUNET_CONTAINER_multihashmap_contains(plugin->blacklist, &peer->hashPubKey) == GNUNET_YES)
949         {
950 #if DEBUG_BLACKLIST
951           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
952                       _("Peer `%s:%s' is blacklisted!\n"),
953                       plugin->short_name, GNUNET_i2s (peer));
954 #endif
955           return GNUNET_YES;
956         }
957     }
958
959   return GNUNET_NO;
960 }
961
962
963 static void
964 add_peer_to_blacklist (struct GNUNET_PeerIdentity *peer, char *transport_name)
965 {
966   struct TransportPlugin *plugin;
967
968   plugin = find_transport(transport_name);
969   if (plugin == NULL) /* Nothing to do */
970     return;
971   if (plugin->blacklist == NULL)    
972     plugin->blacklist = GNUNET_CONTAINER_multihashmap_create(TRANSPORT_BLACKLIST_HT_SIZE);    
973   GNUNET_assert(plugin->blacklist != NULL);
974   GNUNET_CONTAINER_multihashmap_put(plugin->blacklist, &peer->hashPubKey,
975                                     NULL, 
976                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
977 }
978
979
980 /**
981  * Read the blacklist file, containing transport:peer entries.
982  * Provided the transport is loaded, set up hashmap with these
983  * entries to blacklist peers by transport.
984  *
985  */
986 static void
987 read_blacklist_file (const struct GNUNET_CONFIGURATION_Handle *cfg)
988 {
989   char *fn;
990   char *data;
991   size_t pos;
992   size_t colon_pos;
993   int tsize;
994   struct GNUNET_PeerIdentity pid;
995   struct stat frstat;
996   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
997   unsigned int entries_found;
998   char *transport_name;
999
1000   if (GNUNET_OK !=
1001       GNUNET_CONFIGURATION_get_value_filename (cfg,
1002                                                "TRANSPORT",
1003                                                "BLACKLIST_FILE",
1004                                                &fn))
1005     {
1006 #if DEBUG_TRANSPORT
1007       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1008                   _("Option `%s' in section `%s' not specified!\n"),
1009                   "BLACKLIST_FILE",
1010                   "TRANSPORT");
1011 #endif
1012       return;
1013     }
1014   if (GNUNET_OK != GNUNET_DISK_file_test (fn))
1015     GNUNET_DISK_fn_write (fn, NULL, 0, GNUNET_DISK_PERM_USER_READ
1016         | GNUNET_DISK_PERM_USER_WRITE);
1017   if (0 != STAT (fn, &frstat))
1018     {
1019       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1020                   _("Could not read blacklist file `%s'\n"), fn);
1021       GNUNET_free (fn);
1022       return;
1023     }
1024   if (frstat.st_size == 0)
1025     {
1026       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1027                   _("Blacklist file `%s' is empty.\n"),
1028                   fn);
1029       GNUNET_free (fn);
1030       return;
1031     }
1032   /* FIXME: use mmap */
1033   data = GNUNET_malloc_large (frstat.st_size);
1034   GNUNET_assert(data != NULL);
1035   if (frstat.st_size !=
1036       GNUNET_DISK_fn_read (fn, data, frstat.st_size))
1037     {
1038       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1039                   _("Failed to read blacklist from `%s'\n"), fn);
1040       GNUNET_free (fn);
1041       GNUNET_free (data);
1042       return;
1043     }
1044   entries_found = 0;
1045   pos = 0;
1046   while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1047     pos++;
1048   while ((frstat.st_size >= sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)) &&
1049          (pos <= frstat.st_size - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)))
1050     {
1051       colon_pos = pos;
1052       while ((colon_pos < frstat.st_size) && (data[colon_pos] != ':') && !isspace ( (unsigned char) data[colon_pos]))
1053         colon_pos++;
1054
1055       if (colon_pos >= frstat.st_size)
1056         {
1057           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1058                       _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1059                       (unsigned long long) colon_pos);
1060           GNUNET_free (fn);
1061           GNUNET_free (data);
1062           return;
1063         }
1064
1065       if (isspace( (unsigned char) data[colon_pos]))
1066       {
1067         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1068                     _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1069                     (unsigned long long) colon_pos);
1070         pos = colon_pos;
1071         while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1072           pos++;
1073         continue;
1074       }
1075       tsize = colon_pos - pos;
1076       if ((pos >= frstat.st_size) || (pos + tsize >= frstat.st_size) || (tsize == 0))
1077         {
1078           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1079                       _("Syntax error in blacklist file at offset %llu, giving up!\n"),
1080                       (unsigned long long) colon_pos);
1081           GNUNET_free (fn);
1082           GNUNET_free (data);
1083           return;
1084         }
1085
1086       transport_name = GNUNET_malloc(tsize);
1087       memcpy(transport_name, &data[pos], tsize);
1088       pos = colon_pos + 1;
1089
1090
1091       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1092                   _("Read transport name %s in blacklist file.\n"),
1093                   transport_name);
1094
1095       memcpy (&enc, &data[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
1096       if (!isspace ( (unsigned char) enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1]))
1097         {
1098           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099                       _("Syntax error in blacklist file at offset %llu, skipping bytes.\n"),
1100                       (unsigned long long) pos);
1101           pos++;
1102           while ((pos < frstat.st_size) && (!isspace ( (unsigned char) data[pos])))
1103             pos++;
1104           GNUNET_free_non_null(transport_name);
1105           continue;
1106         }
1107       enc.encoding[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
1108       if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &pid.hashPubKey))
1109         {
1110           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1111                       _("Syntax error in blacklist file at offset %llu, skipping bytes `%s'.\n"),
1112                       (unsigned long long) pos,
1113                       &enc);
1114         }
1115       else
1116         {
1117           if (0 != memcmp (&pid,
1118                            &my_identity,
1119                            sizeof (struct GNUNET_PeerIdentity)))
1120             {
1121               entries_found++;
1122               add_peer_to_blacklist (&pid,
1123                               transport_name);
1124               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1125                           _("Found blacklisted peer `%s:%s' in configuration\n"),
1126                           transport_name, GNUNET_i2s (&pid));
1127             }
1128           else
1129             {
1130               GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1131                           _("Found myself `%s' in blacklist (useless, ignored)\n"),
1132                           GNUNET_i2s (&pid));
1133             }
1134         }
1135       pos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded);
1136       GNUNET_free_non_null(transport_name);
1137       while ((pos < frstat.st_size) && isspace ( (unsigned char) data[pos]))
1138         pos++;
1139     }
1140   GNUNET_free (data);
1141   GNUNET_free (fn);
1142 }
1143
1144
1145 /**
1146  * Function called to notify a client about the socket being ready to
1147  * queue more data.  "buf" will be NULL and "size" zero if the socket
1148  * was closed for writing in the meantime.
1149  *
1150  * @param cls closure
1151  * @param size number of bytes available in buf
1152  * @param buf where the callee should write the message
1153  * @return number of bytes written to buf
1154  */
1155 static size_t
1156 transmit_to_client_callback (void *cls, size_t size, void *buf)
1157 {
1158   struct TransportClient *client = cls;
1159   struct ClientMessageQueueEntry *q;
1160   uint16_t msize;
1161   size_t tsize;
1162   const struct GNUNET_MessageHeader *msg;
1163   char *cbuf;
1164
1165   client->th = NULL;
1166   if (buf == NULL)
1167     {
1168       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1169                   "Transmission to client failed, closing connection.\n");
1170       /* fatal error with client, free message queue! */
1171       while (NULL != (q = client->message_queue_head))
1172         {
1173           GNUNET_STATISTICS_update (stats,
1174                                     gettext_noop ("# bytes discarded (could not transmit to client)"),
1175                                     ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
1176                                     GNUNET_NO);      
1177           GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1178                                        client->message_queue_tail,
1179                                        q);
1180           GNUNET_free (q);
1181         }
1182       client->message_count = 0;
1183       return 0;
1184     }
1185   cbuf = buf;
1186   tsize = 0;
1187   while (NULL != (q = client->message_queue_head))
1188     {
1189       msg = (const struct GNUNET_MessageHeader *) &q[1];
1190       msize = ntohs (msg->size);
1191       if (msize + tsize > size)
1192         break;
1193 #if DEBUG_TRANSPORT
1194       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                   "Transmitting message of type %u to client.\n",
1196                   ntohs (msg->type));
1197 #endif
1198       GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
1199                                    client->message_queue_tail,
1200                                    q);
1201       memcpy (&cbuf[tsize], msg, msize);
1202       tsize += msize;
1203       GNUNET_free (q);
1204       client->message_count--;
1205     }
1206   if (NULL != q)
1207     {
1208       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1209       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1210                                                         msize,
1211                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1212                                                         &transmit_to_client_callback,
1213                                                         client);
1214       GNUNET_assert (client->th != NULL);
1215     }
1216   return tsize;
1217 }
1218
1219
1220 /**
1221  * Convert an address to a string.
1222  *
1223  * @param plugin name of the plugin responsible for the address
1224  * @param addr binary address
1225  * @param addr_len number of bytes in addr
1226  * @return NULL on error, otherwise address string
1227  */
1228 static const char*
1229 a2s (const char *plugin,
1230      const void *addr,
1231      uint16_t addr_len)
1232 {
1233   struct TransportPlugin *p;
1234
1235   if (plugin == NULL)
1236     return NULL;
1237   p = find_transport (plugin);
1238   if (p == NULL)
1239     return NULL;
1240   return p->api->address_to_string (p->api->cls,
1241                                     addr,
1242                                     addr_len);
1243 }   
1244
1245
1246 /**
1247  * Mark the given FAL entry as 'connected' (and hence preferred for
1248  * sending); also mark all others for the same peer as 'not connected'
1249  * (since only one can be preferred).
1250  *
1251  * @param fal address to set to 'connected'
1252  */
1253 static void
1254 mark_address_connected (struct ForeignAddressList *fal)
1255 {
1256   struct ForeignAddressList *pos;
1257   int cnt;
1258
1259   GNUNET_assert (GNUNET_YES == fal->validated);
1260   if (fal->connected == GNUNET_YES)
1261     return; /* nothing to do */
1262   cnt = GNUNET_YES;
1263   pos = fal->ready_list->addresses;
1264   while (pos != NULL)
1265     {
1266       if (GNUNET_YES == pos->connected)
1267         {
1268 #if DEBUG_TRANSPORT
1269           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1270                       "Marking address `%s' as no longer connected (due to connect on other address)\n",
1271                       a2s (pos->ready_list->plugin->short_name,
1272                            pos->addr,
1273                            pos->addrlen));
1274 #endif
1275           GNUNET_break (cnt == GNUNET_YES);
1276           cnt = GNUNET_NO;
1277           pos->connected = GNUNET_NO;
1278           GNUNET_STATISTICS_update (stats,
1279                                     gettext_noop ("# connected addresses"),
1280                                     -1,
1281                                     GNUNET_NO);
1282         }
1283       pos = pos->next;
1284     }
1285   fal->connected = GNUNET_YES;
1286   if (GNUNET_YES == cnt)
1287     {
1288       GNUNET_STATISTICS_update (stats,
1289                                 gettext_noop ("# connected addresses"),
1290                                 1,
1291                                 GNUNET_NO);
1292     }
1293 }
1294
1295
1296 /**
1297  * Send the specified message to the specified client.  Since multiple
1298  * messages may be pending for the same client at a time, this code
1299  * makes sure that no message is lost.
1300  *
1301  * @param client client to transmit the message to
1302  * @param msg the message to send
1303  * @param may_drop can this message be dropped if the
1304  *        message queue for this client is getting far too large?
1305  */
1306 static void
1307 transmit_to_client (struct TransportClient *client,
1308                     const struct GNUNET_MessageHeader *msg, int may_drop)
1309 {
1310   struct ClientMessageQueueEntry *q;
1311   uint16_t msize;
1312
1313   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
1314     {
1315       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1316                   _
1317                   ("Dropping message of type %u and size %u, have %u messages pending (%u is the soft limit)\n"),
1318                   ntohs (msg->type),
1319                   ntohs (msg->size),
1320                   client->message_count, 
1321                   MAX_PENDING);
1322       GNUNET_STATISTICS_update (stats,
1323                                 gettext_noop ("# messages dropped due to slow client"),
1324                                 1,
1325                                 GNUNET_NO);
1326       return;
1327     }
1328   msize = ntohs (msg->size);
1329   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
1330   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1331   memcpy (&q[1], msg, msize);
1332   GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1333                                      client->message_queue_tail,
1334                                      client->message_queue_tail,
1335                                      q);                                     
1336   client->message_count++;
1337   if (client->th == NULL)
1338     {
1339       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1340                                                         msize,
1341                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1342                                                         &transmit_to_client_callback,
1343                                                         client);
1344       GNUNET_assert (client->th != NULL);
1345     }
1346 }
1347
1348
1349 /**
1350  * Transmit a 'SEND_OK' notification to the given client for the
1351  * given neighbour.
1352  *
1353  * @param client who to notify
1354  * @param n neighbour to notify about
1355  * @param result status code for the transmission request
1356  */
1357 static void
1358 transmit_send_ok (struct TransportClient *client,
1359                   struct NeighbourList *n,
1360                   int result)
1361 {
1362   struct SendOkMessage send_ok_msg;
1363
1364   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1365   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1366   send_ok_msg.success = htonl (result);
1367   send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1368   send_ok_msg.peer = n->id;
1369   transmit_to_client (client, &send_ok_msg.header, GNUNET_NO); 
1370 }
1371
1372
1373 /**
1374  * Function called by the GNUNET_TRANSPORT_TransmitFunction
1375  * upon "completion" of a send request.  This tells the API
1376  * that it is now legal to send another message to the given
1377  * peer.
1378  *
1379  * @param cls closure, identifies the entry on the
1380  *            message queue that was transmitted and the
1381  *            client responsible for queueing the message
1382  * @param target the peer receiving the message
1383  * @param result GNUNET_OK on success, if the transmission
1384  *           failed, we should not tell the client to transmit
1385  *           more messages
1386  */
1387 static void
1388 transmit_send_continuation (void *cls,
1389                             const struct GNUNET_PeerIdentity *target,
1390                             int result)
1391 {
1392   struct MessageQueue *mq = cls;
1393   struct NeighbourList *n;
1394   
1395   GNUNET_STATISTICS_update (stats,
1396                             gettext_noop ("# bytes pending with plugins"),
1397                             - (int64_t) mq->message_buf_size,
1398                             GNUNET_NO);
1399   if (result == GNUNET_OK)
1400     {
1401       GNUNET_STATISTICS_update (stats,
1402                                 gettext_noop ("# bytes successfully transmitted by plugins"),
1403                                 mq->message_buf_size,
1404                                 GNUNET_NO);      
1405     }
1406   else
1407     {
1408       GNUNET_STATISTICS_update (stats,
1409                                 gettext_noop ("# bytes with transmission failure by plugins"),
1410                                 mq->message_buf_size,
1411                                 GNUNET_NO);      
1412     }  
1413   n = find_neighbour(&mq->neighbour_id);
1414   GNUNET_assert (n != NULL);
1415   if (mq->specific_address != NULL)
1416     {
1417       if (result == GNUNET_OK)    
1418         {
1419           mq->specific_address->timeout =
1420             GNUNET_TIME_relative_to_absolute
1421             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1422           if (mq->specific_address->validated == GNUNET_YES)
1423             mark_address_connected (mq->specific_address);
1424         }    
1425       else
1426         {
1427           if (mq->specific_address->connected != GNUNET_NO)
1428             {
1429 #if DEBUG_TRANSPORT
1430               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431                           "Marking address `%s' as no longer connected (due to transmission problem)\n",
1432                           a2s (mq->specific_address->ready_list->plugin->short_name,
1433                                mq->specific_address->addr,
1434                                mq->specific_address->addrlen));
1435 #endif
1436               GNUNET_STATISTICS_update (stats,
1437                                         gettext_noop ("# connected addresses"),
1438                                         -1,
1439                                         GNUNET_NO);
1440               mq->specific_address->connected = GNUNET_NO;
1441             }
1442         }    
1443       if (! mq->internal_msg) 
1444         mq->specific_address->in_transmit = GNUNET_NO;
1445     }
1446   if (mq->client != NULL)
1447     transmit_send_ok (mq->client, n, result);
1448   GNUNET_free (mq);
1449   try_transmission_to_peer (n);
1450 }
1451
1452
1453 /**
1454  * Find an address in any of the available transports for
1455  * the given neighbour that would be good for message
1456  * transmission.  This is essentially the transport selection
1457  * routine.
1458  *
1459  * @param neighbour for whom to select an address
1460  * @return selected address, NULL if we have none
1461  */
1462 struct ForeignAddressList *
1463 find_ready_address(struct NeighbourList *neighbour)
1464 {
1465   struct ReadyList *head = neighbour->plugins;
1466   struct ForeignAddressList *addresses;
1467   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1468   struct ForeignAddressList *best_address;
1469
1470   best_address = NULL;
1471   while (head != NULL)
1472     {
1473       addresses = head->addresses;
1474       while (addresses != NULL)
1475         {
1476           if ( (addresses->timeout.value < now.value) && 
1477                (addresses->connected == GNUNET_YES) )
1478             {
1479 #if DEBUG_TRANSPORT
1480               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1481                           "Marking long-time inactive connection to `%4s' as down.\n",
1482                           GNUNET_i2s (&neighbour->id));
1483 #endif
1484               GNUNET_STATISTICS_update (stats,
1485                                         gettext_noop ("# connected addresses"),
1486                                         -1,
1487                                         GNUNET_NO);
1488               addresses->connected = GNUNET_NO;
1489             }
1490           addresses = addresses->next;
1491         }
1492
1493       addresses = head->addresses;
1494       while (addresses != NULL)
1495         {
1496 #if DEBUG_TRANSPORT > 1
1497           if (addresses->addr != NULL)
1498             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499                         "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1500                         a2s (head->plugin->short_name,
1501                              addresses->addr,
1502                              addresses->addrlen),
1503                         GNUNET_i2s (&neighbour->id),
1504                         addresses->connected,
1505                         addresses->in_transmit,
1506                         addresses->validated,
1507                         addresses->connect_attempts,
1508                         (unsigned long long) addresses->timeout.value,
1509                         (unsigned int) addresses->distance);
1510 #endif
1511           if ( ( (best_address == NULL) || 
1512                  (addresses->connected == GNUNET_YES) ||
1513                  (best_address->connected == GNUNET_NO) ) &&
1514                (addresses->in_transmit == GNUNET_NO) &&
1515                ( (best_address == NULL) || 
1516                  (addresses->latency.value < best_address->latency.value)) )
1517             best_address = addresses;            
1518           /* FIXME: also give lower-latency addresses that are not
1519              connected a chance some times... */
1520           addresses = addresses->next;
1521         }
1522       head = head->next;
1523     }
1524   if (best_address != NULL)
1525     {
1526 #if DEBUG_TRANSPORT
1527       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1528                   "Best address found (`%s') has latency of %llu ms.\n",
1529                   a2s (best_address->ready_list->plugin->short_name,
1530                        best_address->addr,
1531                        best_address->addrlen),
1532                   best_address->latency.value);
1533 #endif
1534     }
1535   else
1536     {
1537       GNUNET_STATISTICS_update (stats,
1538                                 gettext_noop ("# transmission attempts failed (no address)"),
1539                                 1,
1540                                 GNUNET_NO);
1541     }
1542   return best_address;
1543
1544 }
1545
1546
1547 /**
1548  * We should re-try transmitting to the given peer,
1549  * hopefully we've learned something in the meantime.
1550  */
1551 static void
1552 retry_transmission_task (void *cls,
1553                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1554 {
1555   struct NeighbourList *n = cls;
1556
1557   n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1558   try_transmission_to_peer (n);
1559 }
1560
1561
1562 /**
1563  * Check the ready list for the given neighbour and if a plugin is
1564  * ready for transmission (and if we have a message), do so!
1565  *
1566  * @param neighbour target peer for which to transmit
1567  */
1568 static void
1569 try_transmission_to_peer (struct NeighbourList *neighbour)
1570 {
1571   struct ReadyList *rl;
1572   struct MessageQueue *mq;
1573   struct GNUNET_TIME_Relative timeout;
1574   ssize_t ret;
1575   int force_address;
1576
1577   if (neighbour->messages_head == NULL)
1578     {
1579 #if DEBUG_TRANSPORT
1580       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581                   "Transmission queue for `%4s' is empty\n",
1582                   GNUNET_i2s (&neighbour->id));
1583 #endif
1584       return;                     /* nothing to do */
1585     }
1586   rl = NULL;
1587   mq = neighbour->messages_head;
1588   force_address = GNUNET_YES;
1589   if (mq->specific_address == NULL)
1590     {
1591       mq->specific_address = find_ready_address(neighbour); 
1592       GNUNET_STATISTICS_update (stats,
1593                                 gettext_noop ("# transport selected peer address freely"),
1594                                 1,
1595                                 GNUNET_NO); 
1596       force_address = GNUNET_NO;
1597     }
1598   if (mq->specific_address == NULL)
1599     {
1600       GNUNET_STATISTICS_update (stats,
1601                                 gettext_noop ("# transport failed to selected peer address"),
1602                                 1,
1603                                 GNUNET_NO); 
1604       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1605       if (timeout.value == 0)
1606         {
1607 #if DEBUG_TRANSPORT
1608           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1609                       "No destination address available to transmit message of size %u to peer `%4s'\n",
1610                       mq->message_buf_size,
1611                       GNUNET_i2s (&mq->neighbour_id));
1612 #endif
1613           GNUNET_STATISTICS_update (stats,
1614                                     gettext_noop ("# bytes in message queue for other peers"),
1615                                     - (int64_t) mq->message_buf_size,
1616                                     GNUNET_NO);
1617           GNUNET_STATISTICS_update (stats,
1618                                     gettext_noop ("# bytes discarded (no destination address available)"),
1619                                     mq->message_buf_size,
1620                                     GNUNET_NO);      
1621           if (mq->client != NULL)
1622             transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1623           GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1624                                        neighbour->messages_tail,
1625                                        mq);
1626           GNUNET_free (mq);
1627           return;               /* nobody ready */ 
1628         }
1629       GNUNET_STATISTICS_update (stats,
1630                                 gettext_noop ("# message delivery deferred (no address)"),
1631                                 1,
1632                                 GNUNET_NO);
1633       if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1634         GNUNET_SCHEDULER_cancel (sched,
1635                                  neighbour->retry_task);
1636       neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1637                                                             timeout,
1638                                                             &retry_transmission_task,
1639                                                             neighbour);
1640 #if DEBUG_TRANSPORT
1641       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1642                   "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1643                   mq->message_buf_size,
1644                   GNUNET_i2s (&mq->neighbour_id),
1645                   timeout.value);
1646 #endif
1647       /* FIXME: might want to trigger peerinfo lookup here
1648          (unless that's already pending...) */
1649       return;    
1650     }
1651   GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1652                                neighbour->messages_tail,
1653                                mq);
1654   if (mq->specific_address->connected == GNUNET_NO)
1655     mq->specific_address->connect_attempts++;
1656   rl = mq->specific_address->ready_list;
1657   mq->plugin = rl->plugin;
1658   if (!mq->internal_msg)
1659     mq->specific_address->in_transmit = GNUNET_YES;
1660 #if DEBUG_TRANSPORT
1661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1663               mq->message_buf_size,
1664               GNUNET_i2s (&neighbour->id), 
1665               (mq->specific_address->addr != NULL)
1666               ? a2s (mq->plugin->short_name,
1667                      mq->specific_address->addr,
1668                      mq->specific_address->addrlen)
1669               : "<inbound>",
1670               rl->plugin->short_name);
1671 #endif
1672   GNUNET_STATISTICS_update (stats,
1673                             gettext_noop ("# bytes in message queue for other peers"),
1674                             - (int64_t) mq->message_buf_size,
1675                             GNUNET_NO);
1676   GNUNET_STATISTICS_update (stats,
1677                             gettext_noop ("# bytes pending with plugins"),
1678                             mq->message_buf_size,
1679                             GNUNET_NO);
1680   ret = rl->plugin->api->send (rl->plugin->api->cls,
1681                                &mq->neighbour_id,
1682                                mq->message_buf,
1683                                mq->message_buf_size,
1684                                mq->priority,
1685                                GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1686                                mq->specific_address->session,
1687                                mq->specific_address->addr,
1688                                mq->specific_address->addrlen,
1689                                force_address,
1690                                &transmit_send_continuation, mq);
1691   if (ret == -1)
1692     {
1693       /* failure, but 'send' would not call continuation in this case,
1694          so we need to do it here! */
1695       transmit_send_continuation (mq, 
1696                                   &mq->neighbour_id,
1697                                   GNUNET_SYSERR);
1698     }
1699 }
1700
1701
1702 /**
1703  * Send the specified message to the specified peer.
1704  *
1705  * @param client source of the transmission request (can be NULL)
1706  * @param peer_address ForeignAddressList where we should send this message
1707  * @param priority how important is the message
1708  * @param timeout how long do we have to transmit?
1709  * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1710  * @param message_buf_size total size of all messages in message_buf
1711  * @param is_internal is this an internal message; these are pre-pended and
1712  *                    also do not count for plugins being "ready" to transmit
1713  * @param neighbour handle to the neighbour for transmission
1714  */
1715 static void
1716 transmit_to_peer (struct TransportClient *client,
1717                   struct ForeignAddressList *peer_address,
1718                   unsigned int priority,
1719                   struct GNUNET_TIME_Relative timeout,
1720                   const char *message_buf,
1721                   size_t message_buf_size,
1722                   int is_internal, struct NeighbourList *neighbour)
1723 {
1724   struct MessageQueue *mq;
1725
1726 #if EXTRA_CHECKS
1727   if (client != NULL)
1728     {
1729       /* check for duplicate submission */
1730       mq = neighbour->messages_head;
1731       while (NULL != mq)
1732         {
1733           if (mq->client == client)
1734             {
1735               /* client transmitted to same peer twice
1736                  before getting SEND_OK! */
1737               GNUNET_break (0);
1738               return;
1739             }
1740           mq = mq->next;
1741         }
1742     }
1743 #endif
1744   GNUNET_STATISTICS_update (stats,
1745                             gettext_noop ("# bytes in message queue for other peers"),
1746                             message_buf_size,
1747                             GNUNET_NO);
1748   mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1749   mq->specific_address = peer_address;
1750   mq->client = client;
1751   memcpy (&mq[1], message_buf, message_buf_size);
1752   mq->message_buf = (const char*) &mq[1];
1753   mq->message_buf_size = message_buf_size;
1754   memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1755   mq->internal_msg = is_internal;
1756   mq->priority = priority;
1757   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1758   if (is_internal)    
1759     GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1760                                  neighbour->messages_tail,
1761                                  mq);
1762   else
1763     GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1764                                        neighbour->messages_tail,
1765                                        neighbour->messages_tail,
1766                                        mq);
1767   try_transmission_to_peer (neighbour);
1768 }
1769
1770
1771 /**
1772  * FIXME: document.
1773  */
1774 struct GeneratorContext
1775 {
1776   struct TransportPlugin *plug_pos;
1777   struct OwnAddressList *addr_pos;
1778   struct GNUNET_TIME_Absolute expiration;
1779 };
1780
1781
1782 /**
1783  * FIXME: document.
1784  */
1785 static size_t
1786 address_generator (void *cls, size_t max, void *buf)
1787 {
1788   struct GeneratorContext *gc = cls;
1789   size_t ret;
1790
1791   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1792     {
1793       gc->plug_pos = gc->plug_pos->next;
1794       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1795     }
1796   if (NULL == gc->plug_pos)
1797     {
1798
1799       return 0;
1800     }
1801   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1802                                   gc->expiration,
1803                                   gc->addr_pos->addr,
1804                                   gc->addr_pos->addrlen, buf, max);
1805   gc->addr_pos = gc->addr_pos->next;
1806   return ret;
1807 }
1808
1809
1810 /**
1811  * Construct our HELLO message from all of the addresses of
1812  * all of the transports.
1813  */
1814 static void
1815 refresh_hello ()
1816 {
1817   struct GNUNET_HELLO_Message *hello;
1818   struct TransportClient *cpos;
1819   struct NeighbourList *npos;
1820   struct GeneratorContext gc;
1821
1822   gc.plug_pos = plugins;
1823   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1824   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1825   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1826 #if DEBUG_TRANSPORT
1827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1828               "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1829 #endif
1830   GNUNET_STATISTICS_update (stats,
1831                             gettext_noop ("# refreshed my HELLO"),
1832                             1,
1833                             GNUNET_NO);
1834   cpos = clients;
1835   while (cpos != NULL)
1836     {
1837       transmit_to_client (cpos,
1838                           (const struct GNUNET_MessageHeader *) hello,
1839                           GNUNET_NO);
1840       cpos = cpos->next;
1841     }
1842
1843   GNUNET_free_non_null (our_hello);
1844   our_hello = hello;
1845   GNUNET_PEERINFO_add_peer (peerinfo, our_hello);
1846   npos = neighbours;
1847   while (npos != NULL)
1848     {
1849 #if DEBUG_TRANSPORT
1850       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1851                   "Transmitting updated `%s' to neighbour `%4s'\n",
1852                   "HELLO", GNUNET_i2s (&npos->id));
1853 #endif
1854       GNUNET_STATISTICS_update (stats,
1855                                 gettext_noop ("# transmitted my HELLO to other peers"),
1856                                 1,
1857                                 GNUNET_NO);
1858       transmit_to_peer (NULL, NULL, 0,
1859                         HELLO_ADDRESS_EXPIRATION,
1860                         (const char *) our_hello, 
1861                         GNUNET_HELLO_size(our_hello),
1862                         GNUNET_NO, npos);
1863       npos = npos->next;
1864     }
1865 }
1866
1867
1868 /**
1869  * Task used to clean up expired addresses for a plugin.
1870  *
1871  * @param cls closure
1872  * @param tc context
1873  */
1874 static void
1875 expire_address_task (void *cls,
1876                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1877
1878
1879 /**
1880  * Update the list of addresses for this plugin,
1881  * expiring those that are past their expiration date.
1882  *
1883  * @param plugin addresses of which plugin should be recomputed?
1884  * @param fresh set to GNUNET_YES if a new address was added
1885  *        and we need to regenerate the HELLO even if nobody
1886  *        expired
1887  */
1888 static void
1889 update_addresses (struct TransportPlugin *plugin, int fresh)
1890 {
1891   static struct GNUNET_TIME_Absolute last_update;
1892   struct GNUNET_TIME_Relative min_remaining;
1893   struct GNUNET_TIME_Relative remaining;
1894   struct GNUNET_TIME_Absolute now;
1895   struct OwnAddressList *pos;
1896   struct OwnAddressList *prev;
1897   struct OwnAddressList *next;
1898   int expired;
1899
1900   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1901     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1902   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1903   now = GNUNET_TIME_absolute_get ();
1904   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1905   expired = (GNUNET_TIME_absolute_get_duration (last_update).value > (HELLO_ADDRESS_EXPIRATION.value / 4));
1906   prev = NULL;
1907   pos = plugin->addresses;
1908   while (pos != NULL)
1909     {
1910       next = pos->next;
1911       if (pos->expires.value < now.value)
1912         {
1913           expired = GNUNET_YES;
1914           if (prev == NULL)
1915             plugin->addresses = pos->next;
1916           else
1917             prev->next = pos->next;  
1918           GNUNET_free (pos);
1919         }
1920       else
1921         {
1922           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1923           if (remaining.value < min_remaining.value)
1924             min_remaining = remaining;
1925           prev = pos;
1926         }
1927       pos = next;
1928     }
1929
1930   if (expired || fresh)
1931     {
1932       last_update = now;
1933       refresh_hello ();
1934     }
1935   min_remaining = GNUNET_TIME_relative_min (min_remaining,
1936                                             GNUNET_TIME_relative_divide (HELLO_ADDRESS_EXPIRATION,
1937                                                                          2));
1938   plugin->address_update_task
1939     = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1940                                     min_remaining,
1941                                     &expire_address_task, plugin);
1942 }
1943
1944
1945 /**
1946  * Task used to clean up expired addresses for a plugin.
1947  *
1948  * @param cls closure
1949  * @param tc context
1950  */
1951 static void
1952 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1953 {
1954   struct TransportPlugin *plugin = cls;
1955
1956   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1957   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1958     update_addresses (plugin, GNUNET_NO);
1959 }
1960
1961
1962 /**
1963  * Iterator over hash map entries that NULLs the session of validation
1964  * entries that match the given session.
1965  *
1966  * @param cls closure (the 'struct Session*' to match against)
1967  * @param key current key code (peer ID, not used)
1968  * @param value value in the hash map ('struct ValidationEntry*')
1969  * @return GNUNET_YES (we should continue to iterate)
1970  */
1971 static int 
1972 remove_session_validations (void *cls,
1973                             const GNUNET_HashCode * key,
1974                             void *value)
1975 {
1976   struct Session *session = cls;
1977   struct ValidationEntry *ve = value;
1978
1979   if (session == ve->session)
1980     ve->session = NULL;
1981   return GNUNET_YES;
1982 }
1983
1984
1985 /**
1986  * Function that will be called whenever the plugin internally
1987  * cleans up a session pointer and hence the service needs to
1988  * discard all of those sessions as well.  Plugins that do not
1989  * use sessions can simply omit calling this function and always
1990  * use NULL wherever a session pointer is needed.
1991  * 
1992  * @param cls closure
1993  * @param peer which peer was the session for 
1994  * @param session which session is being destoyed
1995  */
1996 static void
1997 plugin_env_session_end  (void *cls,
1998                          const struct GNUNET_PeerIdentity *peer,
1999                          struct Session *session)
2000 {
2001   struct TransportPlugin *p = cls;
2002   struct NeighbourList *nl;
2003   struct ReadyList *rl;
2004   struct ForeignAddressList *pos;
2005   struct ForeignAddressList *prev;
2006
2007   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2008                                          &remove_session_validations,
2009                                          session);
2010   nl = find_neighbour (peer);
2011   if (nl == NULL)
2012     return;
2013   rl = nl->plugins;
2014   while (rl != NULL)
2015     {
2016       if (rl->plugin == p)
2017         break;
2018       rl = rl->next;
2019     }
2020   if (rl == NULL)
2021     return;
2022   prev = NULL;
2023   pos = rl->addresses;
2024   while ( (pos != NULL) &&
2025           (pos->session != session) )
2026     {
2027       prev = pos;
2028       pos = pos->next;
2029     }
2030   if (pos == NULL)
2031     return;
2032   pos->session = NULL;
2033   if (pos->addrlen != 0)
2034     return;
2035   if (prev == NULL)
2036     rl->addresses = pos->next;
2037   else
2038     prev->next = pos->next;
2039   if (GNUNET_SCHEDULER_NO_TASK != pos->revalidate_task)
2040     {
2041       GNUNET_SCHEDULER_cancel (sched,
2042                                pos->revalidate_task);
2043       pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2044     }
2045   GNUNET_free (pos);
2046   if (nl->received_pong == GNUNET_NO)
2047     return; /* nothing to do */
2048   /* check if we have any validated addresses left */
2049   pos = rl->addresses;
2050   while (pos != NULL)
2051     {
2052       if (pos->validated)
2053         return;
2054       pos = pos->next;
2055     }
2056   /* no valid addresses left, signal disconnect! */
2057   disconnect_neighbour (nl, GNUNET_NO);  
2058 }
2059
2060
2061 /**
2062  * Function that must be called by each plugin to notify the
2063  * transport service about the addresses under which the transport
2064  * provided by the plugin can be reached.
2065  *
2066  * @param cls closure
2067  * @param name name of the transport that generated the address
2068  * @param addr one of the addresses of the host, NULL for the last address
2069  *        the specific address format depends on the transport
2070  * @param addrlen length of the address
2071  * @param expires when should this address automatically expire?
2072  */
2073 static void
2074 plugin_env_notify_address (void *cls,
2075                            const char *name,
2076                            const void *addr,
2077                            uint16_t addrlen,
2078                            struct GNUNET_TIME_Relative expires)
2079 {
2080   struct TransportPlugin *p = cls;
2081   struct OwnAddressList *al;
2082   struct GNUNET_TIME_Absolute abex;
2083
2084   GNUNET_assert (addr != NULL);
2085   abex = GNUNET_TIME_relative_to_absolute (expires);
2086   GNUNET_assert (p == find_transport (name));
2087   al = p->addresses;
2088   while (al != NULL)
2089     {
2090       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
2091         {
2092           if (al->expires.value < abex.value)
2093             al->expires = abex;
2094           return;
2095         }
2096       al = al->next;
2097     }
2098
2099   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
2100   al->addr = &al[1];
2101   al->next = p->addresses;
2102   p->addresses = al;
2103   al->expires = abex;
2104   al->addrlen = addrlen;
2105   memcpy (&al[1], addr, addrlen);
2106   update_addresses (p, GNUNET_YES);
2107 }
2108
2109
2110 /**
2111  * Notify all of our clients about a peer connecting.
2112  */
2113 static void
2114 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
2115                         struct GNUNET_TIME_Relative latency,
2116                         uint32_t distance)
2117 {
2118   struct ConnectInfoMessage cim;
2119   struct TransportClient *cpos;
2120
2121 #if DEBUG_TRANSPORT
2122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2123               "Notifying clients about connection from `%s'\n",
2124               GNUNET_i2s (peer));
2125 #endif
2126   GNUNET_STATISTICS_update (stats,
2127                             gettext_noop ("# peers connected"),
2128                             1,
2129                             GNUNET_NO);
2130   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2131   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2132   cim.distance = htonl (distance);
2133   cim.latency = GNUNET_TIME_relative_hton (latency);
2134   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
2135   cpos = clients;
2136   while (cpos != NULL)
2137     {
2138       transmit_to_client (cpos, &cim.header, GNUNET_NO);
2139       cpos = cpos->next;
2140     }
2141 }
2142
2143
2144 /**
2145  * Notify all of our clients about a peer disconnecting.
2146  */
2147 static void
2148 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
2149 {
2150   struct DisconnectInfoMessage dim;
2151   struct TransportClient *cpos;
2152
2153 #if DEBUG_TRANSPORT
2154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2155               "Notifying clients about lost connection to `%s'\n",
2156               GNUNET_i2s (peer));
2157 #endif
2158   GNUNET_STATISTICS_update (stats,
2159                             gettext_noop ("# peers connected"),
2160                             -1,
2161                             GNUNET_NO);
2162   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
2163   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
2164   dim.reserved = htonl (0);
2165   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
2166   cpos = clients;
2167   while (cpos != NULL)
2168     {
2169       transmit_to_client (cpos, &dim.header, GNUNET_NO);
2170       cpos = cpos->next;
2171     }
2172 }
2173
2174
2175 /**
2176  * Find a ForeignAddressList entry for the given neighbour
2177  * that matches the given address and transport.
2178  *
2179  * @param neighbour which peer we care about
2180  * @param tname name of the transport plugin
2181  * @param session session to look for, NULL for 'any'; otherwise
2182  *        can be used for the service to "learn" this session ID
2183  *        if 'addr' matches
2184  * @param addr binary address
2185  * @param addrlen length of addr
2186  * @return NULL if no such entry exists
2187  */
2188 static struct ForeignAddressList *
2189 find_peer_address(struct NeighbourList *neighbour,
2190                   const char *tname,
2191                   struct Session *session,
2192                   const char *addr,
2193                   uint16_t addrlen)
2194 {
2195   struct ReadyList *head;
2196   struct ForeignAddressList *pos;
2197
2198   head = neighbour->plugins;
2199   while (head != NULL)
2200     {
2201       if (0 == strcmp (tname, head->plugin->short_name))
2202         break;
2203       head = head->next;
2204     }
2205   if (head == NULL)
2206     return NULL;
2207   pos = head->addresses;
2208   while ( (pos != NULL) &&
2209           ( (pos->addrlen != addrlen) ||
2210             (memcmp(pos->addr, addr, addrlen) != 0) ) )
2211     {
2212       if ( (session != NULL) &&
2213            (pos->session == session) )
2214         return pos;
2215       pos = pos->next;
2216     }
2217   if ( (session != NULL) && (pos != NULL) )
2218     pos->session = session; /* learn it! */
2219   return pos;
2220 }
2221
2222
2223 /**
2224  * Get the peer address struct for the given neighbour and
2225  * address.  If it doesn't yet exist, create it.
2226  *
2227  * @param neighbour which peer we care about
2228  * @param tname name of the transport plugin
2229  * @param session session of the plugin, or NULL for none
2230  * @param addr binary address
2231  * @param addrlen length of addr
2232  * @return NULL if we do not have a transport plugin for 'tname'
2233  */
2234 static struct ForeignAddressList *
2235 add_peer_address (struct NeighbourList *neighbour,
2236                   const char *tname,
2237                   struct Session *session,
2238                   const char *addr, 
2239                   uint16_t addrlen)
2240 {
2241   struct ReadyList *head;
2242   struct ForeignAddressList *ret;
2243
2244   ret = find_peer_address (neighbour, tname, session, addr, addrlen);
2245   if (ret != NULL)
2246     return ret;
2247   head = neighbour->plugins;
2248
2249   while (head != NULL)
2250     {
2251       if (0 == strcmp (tname, head->plugin->short_name))
2252         break;
2253       head = head->next;
2254     }
2255   if (head == NULL)
2256     return NULL;
2257   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
2258   ret->session = session;
2259   if (addrlen > 0)
2260     {
2261       ret->addr = (const char*) &ret[1];
2262       memcpy (&ret[1], addr, addrlen);
2263     }
2264   else
2265     {
2266       ret->addr = NULL;
2267     }
2268   ret->addrlen = addrlen;
2269   ret->expires = GNUNET_TIME_relative_to_absolute
2270     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2271   ret->latency = GNUNET_TIME_relative_get_forever();
2272   ret->distance = -1;
2273   ret->timeout = GNUNET_TIME_relative_to_absolute
2274     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); 
2275   ret->ready_list = head;
2276   ret->next = head->addresses;
2277   head->addresses = ret;
2278   return ret;
2279 }
2280
2281
2282 /**
2283  * Closure for 'add_validated_address'.
2284  */
2285 struct AddValidatedAddressContext
2286 {
2287   /**
2288    * Entry that has been validated.
2289    */
2290   const struct ValidationEntry *ve;
2291
2292   /**
2293    * Flag set after we have added the address so
2294    * that we terminate the iteration next time.
2295    */
2296   int done;
2297 };
2298
2299
2300 /**
2301  * Callback function used to fill a buffer of max bytes with a list of
2302  * addresses in the format used by HELLOs.  Should use
2303  * "GNUNET_HELLO_add_address" as a helper function.
2304  *
2305  * @param cls the 'struct AddValidatedAddressContext' with the validated address
2306  * @param max maximum number of bytes that can be written to buf
2307  * @param buf where to write the address information
2308  * @return number of bytes written, 0 to signal the
2309  *         end of the iteration.
2310  */
2311 static size_t
2312 add_validated_address (void *cls,
2313                        size_t max, void *buf)
2314 {
2315   struct AddValidatedAddressContext *avac = cls;
2316   const struct ValidationEntry *ve = avac->ve;
2317
2318   if (GNUNET_YES == avac->done)
2319     return 0;
2320   avac->done = GNUNET_YES;
2321   return GNUNET_HELLO_add_address (ve->transport_name,
2322                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
2323                                    ve->addr,
2324                                    ve->addrlen,
2325                                    buf,
2326                                    max);
2327 }
2328
2329
2330
2331 /**
2332  * Closure for 'check_address_exists'.
2333  */
2334 struct CheckAddressExistsClosure
2335 {
2336   /**
2337    * Address to check for.
2338    */
2339   const void *addr;
2340
2341   /**
2342    * Name of the transport.
2343    */
2344   const char *tname;
2345
2346   /**
2347    * Session, or NULL.
2348    */
2349   struct Session *session;
2350
2351   /**
2352    * Set to GNUNET_YES if the address exists.
2353    */
2354   int exists;
2355
2356   /**
2357    * Length of addr.
2358    */
2359   uint16_t addrlen;
2360
2361 };
2362
2363
2364 /**
2365  * Iterator over hash map entries.  Checks if the given
2366  * validation entry is for the same address as what is given
2367  * in the closure.
2368  *
2369  * @param cls the 'struct CheckAddressExistsClosure*'
2370  * @param key current key code (ignored)
2371  * @param value value in the hash map ('struct ValidationEntry')
2372  * @return GNUNET_YES if we should continue to
2373  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2374  */
2375 static int
2376 check_address_exists (void *cls,
2377                       const GNUNET_HashCode * key,
2378                       void *value)
2379 {
2380   struct CheckAddressExistsClosure *caec = cls;
2381   struct ValidationEntry *ve = value;
2382
2383   if ( (0 == strcmp (caec->tname,
2384                      ve->transport_name)) &&
2385        (caec->addrlen == ve->addrlen) &&
2386        (0 == memcmp (caec->addr,
2387                      ve->addr,
2388                      caec->addrlen)) )
2389     {
2390       caec->exists = GNUNET_YES;
2391       return GNUNET_NO;
2392     }
2393   if ( (ve->session != NULL) &&
2394        (caec->session == ve->session) )
2395     {
2396       caec->exists = GNUNET_YES;
2397       return GNUNET_NO;
2398     }
2399   return GNUNET_YES;
2400 }
2401
2402
2403
2404 /**
2405  * Iterator to free entries in the validation_map.
2406  *
2407  * @param cls closure (unused)
2408  * @param key current key code
2409  * @param value value in the hash map (validation to abort)
2410  * @return GNUNET_YES (always)
2411  */
2412 static int 
2413 abort_validation (void *cls,
2414                   const GNUNET_HashCode * key,
2415                   void *value)
2416 {
2417   struct ValidationEntry *va = value;
2418
2419   if (GNUNET_SCHEDULER_NO_TASK != va->timeout_task)
2420     GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
2421   GNUNET_free (va->transport_name);
2422   if (va->chvc != NULL)
2423     {
2424       va->chvc->ve_count--;
2425       if (va->chvc->ve_count == 0)
2426         {
2427           GNUNET_CONTAINER_DLL_remove (chvc_head,
2428                                        chvc_tail,
2429                                        va->chvc);
2430           GNUNET_free (va->chvc);
2431         }
2432       va->chvc = NULL;
2433     }
2434   GNUNET_free (va);
2435   return GNUNET_YES;
2436 }
2437
2438
2439 /**
2440  * HELLO validation cleanup task (validation failed).
2441  *
2442  * @param cls the 'struct ValidationEntry' that failed
2443  * @param tc scheduler context (unused)
2444  */
2445 static void
2446 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2447 {
2448   struct ValidationEntry *va = cls;
2449   struct GNUNET_PeerIdentity pid;
2450
2451   va->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2452   GNUNET_STATISTICS_update (stats,
2453                             gettext_noop ("# address validation timeouts"),
2454                             1,
2455                             GNUNET_NO);
2456   GNUNET_CRYPTO_hash (&va->publicKey,
2457                       sizeof (struct
2458                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2459                       &pid.hashPubKey);
2460   GNUNET_break (GNUNET_OK ==
2461                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
2462                                                       &pid.hashPubKey,
2463                                                       va));
2464   abort_validation (NULL, NULL, va);
2465 }
2466
2467
2468 static void
2469 neighbour_timeout_task (void *cls,
2470                        const struct GNUNET_SCHEDULER_TaskContext *tc)
2471 {
2472   struct NeighbourList *n = cls;
2473
2474 #if DEBUG_TRANSPORT
2475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2476               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
2477 #endif
2478   GNUNET_STATISTICS_update (stats,
2479                             gettext_noop ("# disconnects due to timeout"),
2480                             1,
2481                             GNUNET_NO);
2482   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2483   disconnect_neighbour (n, GNUNET_NO);
2484 }
2485
2486
2487 /**
2488  * Schedule the job that will cause us to send a PING to the
2489  * foreign address to evaluate its validity and latency.
2490  *
2491  * @param fal address to PING
2492  */
2493 static void
2494 schedule_next_ping (struct ForeignAddressList *fal);
2495
2496
2497 /**
2498  * Add the given address to the list of foreign addresses
2499  * available for the given peer (check for duplicates).
2500  *
2501  * @param cls the respective 'struct NeighbourList' to update
2502  * @param tname name of the transport
2503  * @param expiration expiration time
2504  * @param addr the address
2505  * @param addrlen length of the address
2506  * @return GNUNET_OK (always)
2507  */
2508 static int
2509 add_to_foreign_address_list (void *cls,
2510                              const char *tname,
2511                              struct GNUNET_TIME_Absolute expiration,
2512                              const void *addr,
2513                              uint16_t addrlen)
2514 {
2515   struct NeighbourList *n = cls;
2516   struct ForeignAddressList *fal;
2517   int try;
2518
2519   GNUNET_STATISTICS_update (stats,
2520                             gettext_noop ("# valid peer addresses returned by PEERINFO"),
2521                             1,
2522                             GNUNET_NO);      
2523   try = GNUNET_NO;
2524   fal = find_peer_address (n, tname, NULL, addr, addrlen);
2525   if (fal == NULL)
2526     {
2527 #if DEBUG_TRANSPORT
2528       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2529                   "Adding address `%s' (%s) for peer `%4s' due to PEERINFO data for %llums.\n",
2530                   a2s (tname, addr, addrlen),
2531                   tname,
2532                   GNUNET_i2s (&n->id),
2533                   expiration.value);
2534 #endif
2535       fal = add_peer_address (n, tname, NULL, addr, addrlen);
2536       if (fal == NULL)
2537         {
2538           GNUNET_STATISTICS_update (stats,
2539                                     gettext_noop ("# previously validated addresses lacking transport"),
2540                                     1,
2541                                     GNUNET_NO); 
2542         }
2543       else
2544         {
2545           fal->expires = GNUNET_TIME_absolute_max (expiration,
2546                                                    fal->expires);
2547           schedule_next_ping (fal);
2548         }
2549       try = GNUNET_YES;
2550     }
2551   else
2552     {
2553       fal->expires = GNUNET_TIME_absolute_max (expiration,
2554                                                fal->expires);
2555     }
2556   if (fal == NULL)
2557     {
2558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2559                   "Failed to add new address for `%4s'\n",
2560                   GNUNET_i2s (&n->id));
2561       return GNUNET_OK;
2562     }
2563   if (fal->validated == GNUNET_NO)
2564     {
2565       fal->validated = GNUNET_YES;  
2566       GNUNET_STATISTICS_update (stats,
2567                                 gettext_noop ("# peer addresses considered valid"),
2568                                 1,
2569                                 GNUNET_NO);      
2570     }
2571   if (try == GNUNET_YES)
2572     {
2573       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2574                   "Have new addresses, will try to trigger transmissions.\n");
2575       try_transmission_to_peer (n);
2576     }
2577   return GNUNET_OK;
2578 }
2579
2580
2581 /**
2582  * Add addresses in validated HELLO "h" to the set of addresses
2583  * we have for this peer.
2584  *
2585  * @param cls closure ('struct NeighbourList*')
2586  * @param peer id of the peer, NULL for last call
2587  * @param h hello message for the peer (can be NULL)
2588  * @param trust amount of trust we have in the peer (not used)
2589  */
2590 static void
2591 add_hello_for_peer (void *cls,
2592                     const struct GNUNET_PeerIdentity *peer,
2593                     const struct GNUNET_HELLO_Message *h, 
2594                     uint32_t trust)
2595 {
2596   struct NeighbourList *n = cls;
2597
2598   if (peer == NULL)
2599     {
2600       n->piter = NULL;
2601       return;
2602     } 
2603   if (h == NULL)
2604     return; /* no HELLO available */
2605 #if DEBUG_TRANSPORT
2606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2607               "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2608               "HELLO",
2609               GNUNET_i2s (peer));
2610 #endif
2611   if (GNUNET_YES != n->public_key_valid)
2612     {
2613       GNUNET_HELLO_get_key (h, &n->publicKey);
2614       n->public_key_valid = GNUNET_YES;
2615     }
2616   GNUNET_HELLO_iterate_addresses (h,
2617                                   GNUNET_NO,
2618                                   &add_to_foreign_address_list,
2619                                   n);
2620 }
2621
2622
2623 /**
2624  * Create a fresh entry in our neighbour list for the given peer.
2625  * Will try to transmit our current HELLO to the new neighbour. 
2626  * Do not call this function directly, use 'setup_peer_check_blacklist.
2627  *
2628  * @param peer the peer for which we create the entry
2629  * @param do_hello should we schedule transmitting a HELLO
2630  * @return the new neighbour list entry
2631  */
2632 static struct NeighbourList *
2633 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer,
2634                      int do_hello)
2635 {
2636   struct NeighbourList *n;
2637   struct TransportPlugin *tp;
2638   struct ReadyList *rl;
2639
2640 #if DEBUG_TRANSPORT
2641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642               "Setting up state for neighbour `%4s'\n",
2643               GNUNET_i2s (peer));
2644 #endif
2645   GNUNET_assert (our_hello != NULL);
2646   GNUNET_STATISTICS_update (stats,
2647                             gettext_noop ("# active neighbours"),
2648                             1,
2649                             GNUNET_NO);
2650   n = GNUNET_malloc (sizeof (struct NeighbourList));
2651   n->next = neighbours;
2652   neighbours = n;
2653   n->id = *peer;
2654   n->peer_timeout =
2655     GNUNET_TIME_relative_to_absolute
2656     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2657   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2658                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2659                                  MAX_BANDWIDTH_CARRY_S);
2660   tp = plugins;
2661   while (tp != NULL)
2662     {
2663       if ((tp->api->send != NULL) && (!is_blacklisted(peer, tp)))
2664         {
2665           rl = GNUNET_malloc (sizeof (struct ReadyList));
2666           rl->neighbour = n;
2667           rl->next = n->plugins;
2668           n->plugins = rl;
2669           rl->plugin = tp;
2670           rl->addresses = NULL;
2671         }
2672       tp = tp->next;
2673     }
2674   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2675   n->distance = -1;
2676   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2677                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2678                                                   &neighbour_timeout_task, n);
2679   if (do_hello)
2680     {
2681       n->piter = GNUNET_PEERINFO_iterate (peerinfo, peer,
2682                                           0, GNUNET_TIME_UNIT_FOREVER_REL,
2683                                           &add_hello_for_peer, n);
2684       transmit_to_peer (NULL, NULL, 0,
2685                         HELLO_ADDRESS_EXPIRATION,
2686                         (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2687                         GNUNET_NO, n);
2688     }
2689   return n;
2690 }
2691
2692
2693 /**
2694  * Function called after we have checked if communicating
2695  * with a given peer is acceptable.  
2696  *
2697  * @param cls closure
2698  * @param n NULL if communication is not acceptable
2699  */
2700 typedef void (*SetupContinuation)(void *cls,
2701                                   struct NeighbourList *n);
2702
2703
2704 /**
2705  * Information kept for each client registered to perform
2706  * blacklisting.
2707  */
2708 struct Blacklisters
2709 {
2710   /**
2711    * This is a linked list.
2712    */
2713   struct Blacklisters *next;
2714
2715   /**
2716    * This is a linked list.
2717    */
2718   struct Blacklisters *prev;
2719
2720   /**
2721    * Client responsible for this entry.
2722    */
2723   struct GNUNET_SERVER_Client *client;
2724
2725   /**
2726    * Blacklist check that we're currently performing.
2727    */
2728   struct BlacklistCheck *bc;
2729
2730 };
2731
2732
2733 /**
2734  * Head of DLL of blacklisting clients.
2735  */
2736 static struct Blacklisters *bl_head;
2737
2738 /**
2739  * Tail of DLL of blacklisting clients.
2740  */
2741 static struct Blacklisters *bl_tail;
2742
2743
2744 /**
2745  * Context we use when performing a blacklist check.
2746  */
2747 struct BlacklistCheck
2748 {
2749   
2750   /**
2751    * This is a linked list.
2752    */
2753   struct BlacklistCheck *next;
2754   
2755   /**
2756    * This is a linked list.
2757    */
2758   struct BlacklistCheck *prev;
2759
2760   /**
2761    * Peer being checked.
2762    */
2763   struct GNUNET_PeerIdentity peer;
2764
2765   /**
2766    * Option for setup neighbour afterwards.
2767    */
2768   int do_hello;
2769
2770   /**
2771    * Continuation to call with the result.
2772    */
2773   SetupContinuation cont;
2774
2775   /**
2776    * Closure for cont.
2777    */
2778   void *cont_cls;
2779
2780   /**
2781    * Current transmission request handle for this client, or NULL if no
2782    * request is pending.
2783    */
2784   struct GNUNET_CONNECTION_TransmitHandle *th;
2785
2786   /**
2787    * Our current position in the blacklisters list.
2788    */
2789   struct Blacklisters *bl_pos;
2790
2791   /**
2792    * Current task performing the check.
2793    */
2794   GNUNET_SCHEDULER_TaskIdentifier task;
2795
2796 };
2797
2798 /**
2799  * Head of DLL of active blacklisting queries.
2800  */
2801 static struct BlacklistCheck *bc_head;
2802
2803 /**
2804  * Tail of DLL of active blacklisting queries.
2805  */
2806 static struct BlacklistCheck *bc_tail;
2807
2808
2809 /**
2810  * Perform next action in the blacklist check.
2811  *
2812  * @param cls the 'struct BlacklistCheck*'
2813  * @param tc unused 
2814  */
2815 static void
2816 do_blacklist_check (void *cls,
2817                     const struct GNUNET_SCHEDULER_TaskContext *tc);
2818
2819
2820 /**
2821  * Transmit blacklist query to the client.
2822  *
2823  * @param cls the 'struct BlacklistCheck'
2824  * @param size number of bytes allowed
2825  * @param buf where to copy the message
2826  * @return number of bytes copied to buf
2827  */
2828 static size_t
2829 transmit_blacklist_message (void *cls,
2830                             size_t size,
2831                             void *buf)
2832 {
2833   struct BlacklistCheck *bc = cls;
2834   struct Blacklisters *bl;
2835   struct BlacklistMessage bm;
2836
2837   bc->th = NULL;
2838   if (size == 0)
2839     {
2840       GNUNET_assert (bc->task == GNUNET_SCHEDULER_NO_TASK);
2841       bc->task = GNUNET_SCHEDULER_add_now (sched,
2842                                            &do_blacklist_check,
2843                                            bc);
2844       return 0;
2845     }
2846   bl = bc->bl_pos;
2847   bm.header.size = htons (sizeof (struct BlacklistMessage));
2848   bm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_QUERY);
2849   bm.is_allowed = htonl (0);
2850   bm.peer = bc->peer;
2851   memcpy (buf, &bm, sizeof (bm)); 
2852   GNUNET_SERVER_receive_done (bl->client, GNUNET_OK);
2853   return sizeof (bm);
2854 }
2855
2856
2857 /**
2858  * Perform next action in the blacklist check.
2859  *
2860  * @param cls the 'struct BlacklistCheck*'
2861  * @param tc unused 
2862  */
2863 static void
2864 do_blacklist_check (void *cls,
2865                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2866 {
2867   struct BlacklistCheck *bc = cls;
2868   struct Blacklisters *bl;
2869
2870   bc->task = GNUNET_SCHEDULER_NO_TASK;
2871   bl = bc->bl_pos;
2872   if (bl == NULL)
2873     {
2874       bc->cont (bc->cont_cls,
2875                 setup_new_neighbour (&bc->peer, bc->do_hello));         
2876       GNUNET_free (bc);
2877       return;
2878     }
2879   if (bl->bc == NULL) 
2880     {
2881       bl->bc = bc;
2882       bc->th = GNUNET_SERVER_notify_transmit_ready (bl->client,
2883                                                     sizeof (struct BlacklistMessage),
2884                                                     GNUNET_TIME_UNIT_FOREVER_REL,
2885                                                     &transmit_blacklist_message,
2886                                                     bc); 
2887     }
2888 }
2889
2890
2891 /**
2892  * Obtain a 'struct NeighbourList' for the given peer.  If such an entry
2893  * does not yet exist, check the blacklist.  If the blacklist says creating
2894  * one is acceptable, create one and call the continuation; otherwise
2895  * call the continuation with NULL.
2896  *
2897  * @param peer peer to setup or look up a struct NeighbourList for
2898  * @param do_hello should we also schedule sending our HELLO to the peer
2899  *        if this is a new record
2900  * @param cont function to call with the 'struct NeigbhbourList*'
2901  * @param cont_cls closure for cont
2902  */
2903 static void
2904 setup_peer_check_blacklist (const struct GNUNET_PeerIdentity *peer,
2905                             int do_hello,
2906                             SetupContinuation cont,
2907                             void *cont_cls)
2908 {
2909   struct NeighbourList *n;
2910   struct BlacklistCheck *bc;
2911
2912   n = find_neighbour(peer);
2913   if (n != NULL)
2914     {
2915       cont (cont_cls, n);
2916       return;
2917     }
2918   if (bl_head == NULL)
2919     {
2920       cont (cont_cls,
2921             setup_new_neighbour (peer, do_hello));
2922       return;
2923     }
2924   bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2925   GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2926   bc->peer = *peer;
2927   bc->do_hello = do_hello;
2928   bc->cont = cont;
2929   bc->cont_cls = cont_cls;
2930   bc->bl_pos = bl_head;
2931   bc->task = GNUNET_SCHEDULER_add_now (sched,
2932                                        &do_blacklist_check,
2933                                        bc);
2934 }
2935
2936
2937 /**
2938  * Function called with the result of querying a new blacklister about 
2939  * it being allowed (or not) to continue to talk to an existing neighbour.
2940  *
2941  * @param cls the original 'struct NeighbourList'
2942  * @param n NULL if we need to disconnect
2943  */
2944 static void
2945 confirm_or_drop_neighbour (void *cls,
2946                            struct NeighbourList *n)
2947 {
2948   struct NeighbourList * orig = cls;
2949
2950   if (n == NULL)
2951     disconnect_neighbour (orig, GNUNET_NO);
2952 }
2953
2954
2955 /**
2956  * Handle a request to start a blacklist.
2957  *
2958  * @param cls closure (always NULL)
2959  * @param client identification of the client
2960  * @param message the actual message
2961  */
2962 static void
2963 handle_blacklist_init (void *cls,
2964                        struct GNUNET_SERVER_Client *client,
2965                        const struct GNUNET_MessageHeader *message)
2966 {
2967   struct Blacklisters *bl;
2968   struct BlacklistCheck *bc;
2969   struct NeighbourList *n;
2970
2971   bl = bl_head;
2972   while (bl != NULL)
2973     {
2974       if (bl->client == client)
2975         {
2976           GNUNET_break (0);
2977           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2978           return;
2979         }
2980       bl = bl->next;
2981     }
2982   bl = GNUNET_malloc (sizeof (struct Blacklisters));
2983   bl->client = client;
2984   GNUNET_SERVER_client_keep (client);
2985   GNUNET_CONTAINER_DLL_insert_after (bl_head, bl_tail, bl_tail, bl);
2986   /* confirm that all existing connections are OK! */
2987   n = neighbours;
2988   while (NULL != n)
2989     {
2990       bc = GNUNET_malloc (sizeof (struct BlacklistCheck));
2991       GNUNET_CONTAINER_DLL_insert (bc_head, bc_tail, bc);
2992       bc->peer = n->id;
2993       bc->do_hello = GNUNET_NO;
2994       bc->cont = &confirm_or_drop_neighbour;
2995       bc->cont_cls = n;
2996       bc->bl_pos = bl;
2997       if (n == neighbours) /* all would wait for the same client, no need to
2998                               create more than just the first task right now */
2999         bc->task = GNUNET_SCHEDULER_add_now (sched,
3000                                              &do_blacklist_check,
3001                                              bc);
3002       n = n->next;
3003     }
3004 }
3005
3006
3007 /**
3008  * Handle a request to blacklist a peer.
3009  *
3010  * @param cls closure (always NULL)
3011  * @param client identification of the client
3012  * @param message the actual message
3013  */
3014 static void
3015 handle_blacklist_reply (void *cls,
3016                         struct GNUNET_SERVER_Client *client,
3017                         const struct GNUNET_MessageHeader *message)
3018 {
3019   const struct BlacklistMessage *msg = (const struct BlacklistMessage*) message;
3020   struct Blacklisters *bl;
3021   struct BlacklistCheck *bc;
3022
3023   bl = bl_head;
3024   while ( (bl != NULL) &&
3025           (bl->client != client) )
3026     bl = bl->next;  
3027   if (bl == NULL)
3028     {
3029       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3030       return;
3031     }
3032   bc = bl->bc;
3033   bl->bc = NULL;  
3034   if (ntohl (msg->is_allowed) == GNUNET_SYSERR)
3035     {    
3036       bc->cont (bc->cont_cls, NULL);
3037       GNUNET_CONTAINER_DLL_remove (bc_head, bc_tail, bc);
3038       GNUNET_free (bc);
3039     }
3040   else
3041     {
3042       bc->bl_pos = bc->bl_pos->next;
3043       bc->task = GNUNET_SCHEDULER_add_now (sched,
3044                                            &do_blacklist_check,
3045                                            bc);      
3046     }
3047   /* check if any other bc's are waiting for this blacklister */
3048   bc = bc_head;
3049   while (bc != NULL)
3050     {
3051       if ( (bc->bl_pos == bl) &&
3052            (GNUNET_SCHEDULER_NO_TASK == bc->task) )
3053         bc->task = GNUNET_SCHEDULER_add_now (sched,
3054                                              &do_blacklist_check,
3055                                              bc);      
3056       bc = bc->next;
3057     }
3058 }
3059
3060
3061 /**
3062  * Send periodic PING messages to a given foreign address.
3063  *
3064  * @param cls our 'struct PeriodicValidationContext*'
3065  * @param tc task context
3066  */
3067 static void 
3068 send_periodic_ping (void *cls, 
3069                     const struct GNUNET_SCHEDULER_TaskContext *tc)
3070 {
3071   struct ForeignAddressList *peer_address = cls;
3072   struct TransportPlugin *tp;
3073   struct ValidationEntry *va;
3074   struct NeighbourList *neighbour;
3075   struct TransportPingMessage ping;
3076   struct CheckAddressExistsClosure caec;
3077   char * message_buf;
3078   uint16_t hello_size;
3079   size_t tsize;
3080
3081   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3082   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3083     return; 
3084   tp = peer_address->ready_list->plugin;
3085   neighbour = peer_address->ready_list->neighbour;
3086   if (GNUNET_YES != neighbour->public_key_valid)
3087     {
3088       /* no public key yet, try again later */
3089       schedule_next_ping (peer_address);     
3090       return;
3091     }
3092   caec.addr = peer_address->addr;
3093   caec.addrlen = peer_address->addrlen;
3094   caec.tname = tp->short_name;
3095   caec.session = peer_address->session;
3096   caec.exists = GNUNET_NO;
3097   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3098                                          &check_address_exists,
3099                                          &caec);
3100   if (caec.exists == GNUNET_YES)
3101     {
3102       /* During validation attempts we will likely trigger the other
3103          peer trying to validate our address which in turn will cause
3104          it to send us its HELLO, so we expect to hit this case rather
3105          frequently.  Only print something if we are very verbose. */
3106 #if DEBUG_TRANSPORT > 1
3107       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3108                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3109                   (peer_address->addr != NULL)
3110                   ? a2s (tp->short_name,
3111                          peer_address->addr,
3112                          peer_address->addrlen)
3113                   : "<inbound>",
3114                   tp->short_name,
3115                   GNUNET_i2s (&neighbour->id));
3116 #endif
3117       schedule_next_ping (peer_address);     
3118       return;
3119     }
3120   va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
3121   va->transport_name = GNUNET_strdup (tp->short_name);
3122   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3123                                             UINT_MAX);
3124   va->send_time = GNUNET_TIME_absolute_get();
3125   va->session = peer_address->session;
3126   if (peer_address->addr != NULL)
3127     {
3128       va->addr = (const void*) &va[1];
3129       memcpy (&va[1], peer_address->addr, peer_address->addrlen);
3130       va->addrlen = peer_address->addrlen;
3131     }
3132   memcpy(&va->publicKey,
3133          &neighbour->publicKey, 
3134          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3135
3136   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3137                                                    HELLO_VERIFICATION_TIMEOUT,
3138                                                    &timeout_hello_validation,
3139                                                    va);
3140   GNUNET_CONTAINER_multihashmap_put (validation_map,
3141                                      &neighbour->id.hashPubKey,
3142                                      va,
3143                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3144   hello_size = GNUNET_HELLO_size(our_hello);
3145   tsize = sizeof(struct TransportPingMessage) + hello_size;
3146   message_buf = GNUNET_malloc(tsize);
3147   ping.challenge = htonl(va->challenge);
3148   ping.header.size = htons(sizeof(struct TransportPingMessage));
3149   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3150   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3151   memcpy(message_buf, our_hello, hello_size);
3152   memcpy(&message_buf[hello_size],
3153          &ping,
3154          sizeof(struct TransportPingMessage));
3155 #if DEBUG_TRANSPORT_REVALIDATION
3156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3157               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3158               (peer_address->addr != NULL) 
3159               ? a2s (peer_address->plugin->short_name,
3160                      peer_address->addr,
3161                      peer_address->addrlen)
3162               : "<inbound>",
3163               tp->short_name,
3164               GNUNET_i2s (&neighbour->id),
3165               "HELLO", hello_size,
3166               "PING", sizeof (struct TransportPingMessage));
3167 #endif
3168   GNUNET_STATISTICS_update (stats,
3169                             gettext_noop ("# PING messages sent for re-validation"),
3170                             1,
3171                             GNUNET_NO);
3172   transmit_to_peer (NULL, peer_address,
3173                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3174                     HELLO_VERIFICATION_TIMEOUT,
3175                     message_buf, tsize,
3176                     GNUNET_YES, neighbour);
3177   GNUNET_free(message_buf);
3178   schedule_next_ping (peer_address);
3179 }
3180
3181
3182 /**
3183  * Schedule the job that will cause us to send a PING to the
3184  * foreign address to evaluate its validity and latency.
3185  *
3186  * @param fal address to PING
3187  */
3188 static void
3189 schedule_next_ping (struct ForeignAddressList *fal)
3190 {
3191   struct GNUNET_TIME_Relative delay;
3192
3193   if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
3194     return;
3195   delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
3196   delay.value /= 2; /* do before expiration */
3197   delay = GNUNET_TIME_relative_min (delay,
3198                                     LATENCY_EVALUATION_MAX_DELAY);
3199   if (GNUNET_YES != fal->estimated)
3200     {
3201       delay = GNUNET_TIME_UNIT_ZERO;
3202       fal->estimated = GNUNET_YES;
3203     }                               
3204   if (GNUNET_YES == fal->connected)
3205     {
3206       delay = GNUNET_TIME_relative_min (delay,
3207                                         CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
3208     }  
3209   /* FIXME: also adjust delay based on how close the last
3210      observed latency is to the latency of the best alternative */
3211   /* bound how fast we can go */
3212   delay = GNUNET_TIME_relative_max (delay,
3213                                     GNUNET_TIME_UNIT_SECONDS);
3214   /* randomize a bit (to avoid doing all at the same time) */
3215   delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
3216   fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched, 
3217                                                       delay,
3218                                                       &send_periodic_ping, 
3219                                                       fal);
3220 }
3221
3222
3223
3224
3225 /**
3226  * Function that will be called if we receive some payload
3227  * from another peer.
3228  *
3229  * @param message the payload
3230  * @param n peer who claimed to be the sender
3231  */
3232 static void
3233 handle_payload_message (const struct GNUNET_MessageHeader *message,
3234                         struct NeighbourList *n)
3235 {
3236   struct InboundMessage *im;
3237   struct TransportClient *cpos;
3238   uint16_t msize;
3239
3240   msize = ntohs (message->size);
3241   if (n->received_pong == GNUNET_NO)
3242     {
3243       GNUNET_free_non_null (n->pre_connect_message_buffer);
3244       n->pre_connect_message_buffer = GNUNET_malloc (msize);
3245       memcpy (n->pre_connect_message_buffer, message, msize);
3246       return;
3247     }
3248 #if DEBUG_TRANSPORT
3249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3250               "Received message of type %u and size %u from `%4s', sending to all clients.\n",
3251               ntohs (message->type), 
3252               ntohs (message->size), 
3253               GNUNET_i2s (&n->id));
3254 #endif
3255   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3256                                                       (ssize_t) msize))
3257     {
3258       n->quota_violation_count++;
3259 #if DEBUG_TRANSPORT
3260       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,                        
3261                   "Bandwidth quota (%u b/s) violation detected (total of %u).\n", 
3262                   n->in_tracker.available_bytes_per_s__,
3263                   n->quota_violation_count);
3264 #endif
3265       /* Discount 32k per violation */
3266       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3267                                         - 32 * 1024);           
3268     }
3269   else 
3270     {
3271       if (n->quota_violation_count > 0)
3272         {
3273           /* try to add 32k back */
3274           GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3275                                             32 * 1024);
3276           n->quota_violation_count--;
3277         }
3278     }
3279   GNUNET_STATISTICS_update (stats,
3280                             gettext_noop ("# payload received from other peers"),
3281                             msize,
3282                             GNUNET_NO);
3283   /* transmit message to all clients */
3284   im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3285   im->header.size = htons (sizeof (struct InboundMessage) + msize);
3286   im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3287   im->latency = GNUNET_TIME_relative_hton (n->latency);
3288   im->peer = n->id;
3289   im->distance = ntohl(n->distance);
3290   memcpy (&im[1], message, msize);
3291   cpos = clients;
3292   while (cpos != NULL)
3293     {
3294       transmit_to_client (cpos, &im->header, GNUNET_YES);
3295       cpos = cpos->next;
3296     }
3297   GNUNET_free (im);
3298 }
3299
3300
3301 /**
3302  * Iterator over hash map entries.  Checks if the given validation
3303  * entry is for the same challenge as what is given in the PONG.
3304  *
3305  * @param cls the 'struct TransportPongMessage*'
3306  * @param key peer identity
3307  * @param value value in the hash map ('struct ValidationEntry')
3308  * @return GNUNET_YES if we should continue to
3309  *         iterate (mismatch), GNUNET_NO if not (entry matched)
3310  */
3311 static int
3312 check_pending_validation (void *cls,
3313                           const GNUNET_HashCode * key,
3314                           void *value)
3315 {
3316   const struct TransportPongMessage *pong = cls;
3317   struct ValidationEntry *ve = value;
3318   struct AddValidatedAddressContext avac;
3319   unsigned int challenge = ntohl(pong->challenge);
3320   struct GNUNET_HELLO_Message *hello;
3321   struct GNUNET_PeerIdentity target;
3322   struct NeighbourList *n;
3323   struct ForeignAddressList *fal;
3324   struct GNUNET_MessageHeader *prem;
3325
3326   if (ve->challenge != challenge)
3327     return GNUNET_YES;
3328
3329 #if SIGN_USELESS
3330   if (GNUNET_OK !=
3331       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING,
3332                                 &pong->purpose, 
3333                                 &pong->signature,
3334                                 &ve->publicKey))
3335     {
3336       GNUNET_break_op (0);
3337       return GNUNET_YES;
3338     }
3339 #endif
3340
3341 #if DEBUG_TRANSPORT
3342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3343               "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
3344               GNUNET_h2s (key),
3345               (ve->addr != NULL) 
3346               ? a2s (ve->transport_name,
3347                      (const struct sockaddr *) ve->addr,
3348                      ve->addrlen)
3349               : "<inbound>",
3350               ve->transport_name);
3351 #endif
3352   GNUNET_STATISTICS_update (stats,
3353                             gettext_noop ("# address validation successes"),
3354                             1,
3355                             GNUNET_NO);
3356   /* create the updated HELLO */
3357   GNUNET_CRYPTO_hash (&ve->publicKey,
3358                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3359                       &target.hashPubKey);
3360   if (ve->addr != NULL)
3361     {
3362       avac.done = GNUNET_NO;
3363       avac.ve = ve;
3364       hello = GNUNET_HELLO_create (&ve->publicKey,
3365                                    &add_validated_address,
3366                                    &avac);
3367       GNUNET_PEERINFO_add_peer (peerinfo,
3368                                 hello);
3369       GNUNET_free (hello);
3370     }
3371   n = find_neighbour (&target);
3372   if (n != NULL)
3373     {
3374       n->publicKey = ve->publicKey;
3375       n->public_key_valid = GNUNET_YES;
3376       fal = add_peer_address (n,
3377                               ve->transport_name,
3378                               ve->session,
3379                               ve->addr,
3380                               ve->addrlen);
3381       GNUNET_assert (fal != NULL);
3382       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
3383       fal->validated = GNUNET_YES;
3384       mark_address_connected (fal);
3385       GNUNET_STATISTICS_update (stats,
3386                                 gettext_noop ("# peer addresses considered valid"),
3387                                 1,
3388                                 GNUNET_NO);      
3389       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
3390       schedule_next_ping (fal);
3391       if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
3392         n->latency = fal->latency;
3393       else
3394         n->latency.value = (fal->latency.value + n->latency.value) / 2;
3395
3396       n->distance = fal->distance;
3397       if (GNUNET_NO == n->received_pong)
3398         {
3399           n->received_pong = GNUNET_YES;
3400           notify_clients_connect (&target, n->latency, n->distance);
3401           if (NULL != (prem = n->pre_connect_message_buffer))
3402             {
3403               n->pre_connect_message_buffer = NULL;
3404               handle_payload_message (prem, n);
3405               GNUNET_free (prem);
3406             }
3407         }
3408       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3409         {
3410           GNUNET_SCHEDULER_cancel (sched,
3411                                    n->retry_task);
3412           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3413           try_transmission_to_peer (n);
3414         }
3415     }
3416
3417   /* clean up validation entry */
3418   GNUNET_assert (GNUNET_YES ==
3419                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
3420                                                        key,
3421                                                        ve));
3422   abort_validation (NULL, NULL, ve);
3423   return GNUNET_NO;
3424 }
3425
3426
3427 /**
3428  * Function that will be called if we receive a validation
3429  * of an address challenge that we transmitted to another
3430  * peer.  Note that the validation should only be considered
3431  * acceptable if the challenge matches AND if the sender
3432  * address is at least a plausible address for this peer
3433  * (otherwise we may be seeing a MiM attack).
3434  *
3435  * @param cls closure
3436  * @param message the pong message
3437  * @param peer who responded to our challenge
3438  * @param sender_address string describing our sender address (as observed
3439  *         by the other peer in binary format)
3440  * @param sender_address_len number of bytes in 'sender_address'
3441  */
3442 static void
3443 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
3444              const struct GNUNET_PeerIdentity *peer,
3445              const char *sender_address,
3446              size_t sender_address_len)
3447 {
3448 #if DEBUG_TRANSPORT > 1
3449   /* we get tons of these that just get discarded, only log
3450      if we are quite verbose */
3451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3452               "Receiving `%s' message from `%4s'.\n", "PONG",
3453               GNUNET_i2s (peer));
3454 #endif
3455   GNUNET_STATISTICS_update (stats,
3456                             gettext_noop ("# PONG messages received"),
3457                             1,
3458                             GNUNET_NO);
3459   if (GNUNET_SYSERR !=
3460       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
3461                                                   &peer->hashPubKey,
3462                                                   &check_pending_validation,
3463                                                   (void*) message))
3464     {
3465       /* This is *expected* to happen a lot since we send
3466          PONGs to *all* known addresses of the sender of
3467          the PING, so most likely we get multiple PONGs
3468          per PING, and all but the first PONG will end up
3469          here. So really we should not print anything here
3470          unless we want to be very, very verbose... */
3471 #if DEBUG_TRANSPORT > 2
3472       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3473                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
3474                   "PONG",
3475                   GNUNET_i2s (peer),
3476                   "PING");
3477 #endif
3478       return;
3479     }
3480
3481 }
3482
3483
3484 /**
3485  * Try to validate a neighbour's address by sending him our HELLO and a PING.
3486  *
3487  * @param cls the 'struct ValidationEntry*'
3488  * @param neighbour neighbour to validate, NULL if validation failed
3489  */
3490 static void
3491 transmit_hello_and_ping (void *cls,
3492                          struct NeighbourList *neighbour)
3493 {
3494   struct ValidationEntry *va = cls;
3495   struct ForeignAddressList *peer_address;
3496   struct TransportPingMessage ping;
3497   uint16_t hello_size;
3498   size_t tsize;
3499   char * message_buf;
3500   struct GNUNET_PeerIdentity id;
3501
3502   GNUNET_CRYPTO_hash (&va->publicKey,
3503                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3504                       &id.hashPubKey);
3505   if (neighbour == NULL)
3506     {
3507       /* FIXME: stats... */
3508       GNUNET_break (GNUNET_OK ==
3509                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3510                                                           &id.hashPubKey,
3511                                                           va));
3512       abort_validation (NULL, NULL, va);
3513       return;
3514     }
3515   neighbour->publicKey = va->publicKey;
3516   neighbour->public_key_valid = GNUNET_YES;
3517   peer_address = add_peer_address (neighbour,
3518                                    va->transport_name, NULL,
3519                                    (const void*) &va[1],
3520                                    va->addrlen);
3521   if (peer_address == NULL)
3522     {
3523       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3524                   "Failed to add peer `%4s' for plugin `%s'\n",
3525                   GNUNET_i2s (&neighbour->id), 
3526                   va->transport_name);
3527       GNUNET_break (GNUNET_OK ==
3528                     GNUNET_CONTAINER_multihashmap_remove (validation_map,
3529                                                           &id.hashPubKey,
3530                                                           va));
3531       abort_validation (NULL, NULL, va);
3532       return;
3533     }
3534   hello_size = GNUNET_HELLO_size(our_hello);
3535   tsize = sizeof(struct TransportPingMessage) + hello_size;
3536   message_buf = GNUNET_malloc(tsize);
3537   ping.challenge = htonl(va->challenge);
3538   ping.header.size = htons(sizeof(struct TransportPingMessage));
3539   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
3540   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
3541   memcpy(message_buf, our_hello, hello_size);
3542   memcpy(&message_buf[hello_size],
3543          &ping,
3544          sizeof(struct TransportPingMessage));
3545 #if DEBUG_TRANSPORT
3546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3547               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
3548               a2s (va->transport_name,
3549                    (const void*) &va[1], va->addrlen),
3550               va->transport_name,
3551               GNUNET_i2s (&neighbour->id),
3552               "HELLO", hello_size,
3553               "PING", sizeof (struct TransportPingMessage));
3554 #endif
3555
3556   GNUNET_STATISTICS_update (stats,
3557                             gettext_noop ("# PING messages sent for initial validation"),
3558                             1,
3559                             GNUNET_NO);      
3560   transmit_to_peer (NULL, peer_address,
3561                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
3562                     HELLO_VERIFICATION_TIMEOUT,
3563                     message_buf, tsize,
3564                     GNUNET_YES, neighbour);
3565   GNUNET_free(message_buf);
3566 }
3567
3568
3569 /**
3570  * Check if the given address is already being validated; if not,
3571  * append the given address to the list of entries that are being be
3572  * validated and initiate validation.
3573  *
3574  * @param cls closure ('struct CheckHelloValidatedContext *')
3575  * @param tname name of the transport
3576  * @param expiration expiration time
3577  * @param addr the address
3578  * @param addrlen length of the address
3579  * @return GNUNET_OK (always)
3580  */
3581 static int
3582 run_validation (void *cls,
3583                 const char *tname,
3584                 struct GNUNET_TIME_Absolute expiration,
3585                 const void *addr, 
3586                 uint16_t addrlen)
3587 {
3588   struct CheckHelloValidatedContext *chvc = cls;
3589   struct GNUNET_PeerIdentity id;
3590   struct TransportPlugin *tp;
3591   struct ValidationEntry *va;
3592   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3593   struct CheckAddressExistsClosure caec;
3594   struct OwnAddressList *oal;
3595
3596   GNUNET_assert (addr != NULL);
3597
3598   GNUNET_STATISTICS_update (stats,
3599                             gettext_noop ("# peer addresses scheduled for validation"),
3600                             1,
3601                             GNUNET_NO);      
3602   tp = find_transport (tname);
3603   if (tp == NULL)
3604     {
3605       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
3606                   GNUNET_ERROR_TYPE_BULK,
3607                   _
3608                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
3609                   tname);
3610       GNUNET_STATISTICS_update (stats,
3611                                 gettext_noop ("# peer addresses not validated (plugin not available)"),
3612                                 1,
3613                                 GNUNET_NO);      
3614       return GNUNET_OK;
3615     }
3616   /* check if this is one of our own addresses */
3617   oal = tp->addresses;
3618   while (NULL != oal)
3619     {
3620       if ( (oal->addrlen == addrlen) &&
3621            (0 == memcmp (oal->addr,
3622                          addr,
3623                          addrlen)) )
3624         {
3625           /* not plausible, this address is equivalent to our own address! */
3626           GNUNET_STATISTICS_update (stats,
3627                                     gettext_noop ("# peer addresses not validated (loopback)"),
3628                                     1,
3629                                     GNUNET_NO);      
3630           return GNUNET_OK;
3631         }
3632       oal = oal->next;
3633     }
3634   GNUNET_HELLO_get_key (chvc->hello, &pk);
3635   GNUNET_CRYPTO_hash (&pk,
3636                       sizeof (struct
3637                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3638                       &id.hashPubKey);
3639
3640   if (is_blacklisted(&id, tp))
3641     {
3642 #if DEBUG_TRANSPORT
3643       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3644                   "Attempted to validate blacklisted peer `%s' using `%s'!\n", 
3645                   GNUNET_i2s(&id), 
3646                   tname);
3647 #endif
3648       return GNUNET_OK;
3649     }
3650
3651   caec.addr = addr;
3652   caec.addrlen = addrlen;
3653   caec.session = NULL;
3654   caec.tname = tname;
3655   caec.exists = GNUNET_NO;
3656   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3657                                          &check_address_exists,
3658                                          &caec);
3659   if (caec.exists == GNUNET_YES)
3660     {
3661       /* During validation attempts we will likely trigger the other
3662          peer trying to validate our address which in turn will cause
3663          it to send us its HELLO, so we expect to hit this case rather
3664          frequently.  Only print something if we are very verbose. */
3665 #if DEBUG_TRANSPORT > 1
3666       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3667                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
3668                   a2s (tname, addr, addrlen),
3669                   tname,
3670                   GNUNET_i2s (&id));
3671 #endif
3672       GNUNET_STATISTICS_update (stats,
3673                                 gettext_noop ("# peer addresses not validated (in progress)"),
3674                                 1,
3675                                 GNUNET_NO);      
3676       return GNUNET_OK;
3677     }
3678   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
3679   va->chvc = chvc;
3680   chvc->ve_count++;
3681   va->transport_name = GNUNET_strdup (tname);
3682   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3683                                             UINT_MAX);
3684   va->send_time = GNUNET_TIME_absolute_get();
3685   va->addr = (const void*) &va[1];
3686   memcpy (&va[1], addr, addrlen);
3687   va->addrlen = addrlen;
3688   GNUNET_HELLO_get_key (chvc->hello,
3689                         &va->publicKey);
3690   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
3691                                                    HELLO_VERIFICATION_TIMEOUT,
3692                                                    &timeout_hello_validation,
3693                                                    va);
3694   GNUNET_CONTAINER_multihashmap_put (validation_map,
3695                                      &id.hashPubKey,
3696                                      va,
3697                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3698   setup_peer_check_blacklist (&id, GNUNET_NO,
3699                               &transmit_hello_and_ping,
3700                               va);
3701   return GNUNET_OK;
3702 }
3703
3704
3705 /**
3706  * Check if addresses in validated hello "h" overlap with
3707  * those in "chvc->hello" and validate the rest.
3708  *
3709  * @param cls closure
3710  * @param peer id of the peer, NULL for last call
3711  * @param h hello message for the peer (can be NULL)
3712  * @param trust amount of trust we have in the peer (not used)
3713  */
3714 static void
3715 check_hello_validated (void *cls,
3716                        const struct GNUNET_PeerIdentity *peer,
3717                        const struct GNUNET_HELLO_Message *h, 
3718                        uint32_t trust)
3719 {
3720   struct CheckHelloValidatedContext *chvc = cls;
3721   struct GNUNET_HELLO_Message *plain_hello;
3722   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
3723   struct GNUNET_PeerIdentity target;
3724   struct NeighbourList *n;
3725
3726   if (peer == NULL)
3727     {
3728       chvc->piter = NULL;
3729       if (GNUNET_NO == chvc->hello_known)
3730         {
3731           /* notify PEERINFO about the peer now, so that we at least
3732              have the public key if some other component needs it */
3733           GNUNET_HELLO_get_key (chvc->hello, &pk);
3734           GNUNET_CRYPTO_hash (&pk,
3735                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3736                               &target.hashPubKey);
3737           plain_hello = GNUNET_HELLO_create (&pk,
3738                                              NULL, 
3739                                              NULL);
3740           GNUNET_PEERINFO_add_peer (peerinfo, plain_hello);
3741           GNUNET_free (plain_hello);
3742 #if DEBUG_TRANSPORT
3743           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3744                       "PEERINFO had no `%s' message for peer `%4s', full validation needed.\n",
3745                       "HELLO",
3746                       GNUNET_i2s (&target));
3747 #endif
3748           GNUNET_STATISTICS_update (stats,
3749                                     gettext_noop ("# new HELLOs requiring full validation"),
3750                                     1,
3751                                     GNUNET_NO);      
3752           GNUNET_HELLO_iterate_addresses (chvc->hello,
3753                                           GNUNET_NO, 
3754                                           &run_validation, 
3755                                           chvc);
3756         }
3757       else
3758         {
3759           GNUNET_STATISTICS_update (stats,
3760                                     gettext_noop ("# duplicate HELLO (peer known)"),
3761                                     1,
3762                                     GNUNET_NO);      
3763         }
3764       chvc->ve_count--;
3765       if (chvc->ve_count == 0)
3766         {
3767           GNUNET_CONTAINER_DLL_remove (chvc_head,
3768                                        chvc_tail,
3769                                        chvc);
3770           GNUNET_free (chvc);     
3771         }
3772       return;
3773     } 
3774   if (h == NULL)
3775     return;
3776 #if DEBUG_TRANSPORT
3777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3778               "PEERINFO had `%s' message for peer `%4s', validating only new addresses.\n",
3779               "HELLO",
3780               GNUNET_i2s (peer));
3781 #endif
3782   chvc->hello_known = GNUNET_YES;
3783   n = find_neighbour (peer);
3784   if (n != NULL)
3785     {
3786       GNUNET_HELLO_iterate_addresses (h,
3787                                       GNUNET_NO,
3788                                       &add_to_foreign_address_list,
3789                                       n);
3790       try_transmission_to_peer (n);
3791     }
3792   else
3793     {
3794       GNUNET_STATISTICS_update (stats,
3795                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3796                                 1,
3797                                 GNUNET_NO);      
3798     }
3799   GNUNET_STATISTICS_update (stats,
3800                             gettext_noop ("# HELLO validations (update case)"),
3801                             1,
3802                             GNUNET_NO);      
3803   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3804                                       h,
3805                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3806                                       &run_validation, 
3807                                       chvc);
3808 }
3809
3810
3811 /**
3812  * Process HELLO-message.
3813  *
3814  * @param plugin transport involved, may be NULL
3815  * @param message the actual message
3816  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3817  */
3818 static int
3819 process_hello (struct TransportPlugin *plugin,
3820                const struct GNUNET_MessageHeader *message)
3821 {
3822   uint16_t hsize;
3823   struct GNUNET_PeerIdentity target;
3824   const struct GNUNET_HELLO_Message *hello;
3825   struct CheckHelloValidatedContext *chvc;
3826   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3827
3828   hsize = ntohs (message->size);
3829   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3830       (hsize < sizeof (struct GNUNET_MessageHeader)))
3831     {
3832       GNUNET_break (0);
3833       return GNUNET_SYSERR;
3834     }
3835   GNUNET_STATISTICS_update (stats,
3836                             gettext_noop ("# HELLOs received for validation"),
3837                             1,
3838                             GNUNET_NO);      
3839   /* first, check if load is too high */
3840   if (GNUNET_SCHEDULER_get_load (sched,
3841                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3842     {
3843       GNUNET_STATISTICS_update (stats,
3844                                 gettext_noop ("# HELLOs ignored due to high load"),
3845                                 1,
3846                                 GNUNET_NO);      
3847       return GNUNET_OK;
3848     }
3849   hello = (const struct GNUNET_HELLO_Message *) message;
3850   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3851     {
3852       GNUNET_break_op (0);
3853       return GNUNET_SYSERR;
3854     }
3855   GNUNET_CRYPTO_hash (&publicKey,
3856                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3857                       &target.hashPubKey);
3858   if (0 == memcmp (&my_identity,
3859                    &target,
3860                    sizeof (struct GNUNET_PeerIdentity)))
3861     {
3862       GNUNET_STATISTICS_update (stats,
3863                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3864                                 1,
3865                                 GNUNET_NO);      
3866       return GNUNET_OK;      
3867     }
3868   chvc = chvc_head;
3869   while (NULL != chvc)
3870     {
3871       if (GNUNET_HELLO_equals (hello,
3872                                chvc->hello,
3873                                GNUNET_TIME_absolute_get ()).value > 0)
3874         {
3875 #if DEBUG_TRANSPORT
3876           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877                       "Received duplicate `%s' message for `%4s'; ignored\n",
3878                       "HELLO", 
3879                       GNUNET_i2s (&target));
3880 #endif
3881           return GNUNET_OK; /* validation already pending */
3882         }
3883       if (GNUNET_HELLO_size(hello) == GNUNET_HELLO_size (chvc->hello))
3884         GNUNET_break (0 != memcmp (hello, chvc->hello,
3885                                    GNUNET_HELLO_size(hello)));
3886       chvc = chvc->next;
3887     }
3888 #if DEBUG_TRANSPORT 
3889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3890               "Starting validation of `%s' message for `%4s' of size %u\n",
3891               "HELLO", 
3892               GNUNET_i2s (&target), 
3893               GNUNET_HELLO_size(hello));
3894 #endif
3895   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3896   chvc->ve_count = 1;
3897   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3898   memcpy (&chvc[1], hello, hsize);
3899   GNUNET_CONTAINER_DLL_insert (chvc_head,
3900                                chvc_tail,
3901                                chvc);
3902   /* finally, check if HELLO was previously validated
3903      (continuation will then schedule actual validation) */
3904   chvc->piter = GNUNET_PEERINFO_iterate (peerinfo,
3905                                          &target,
3906                                          0,
3907                                          HELLO_VERIFICATION_TIMEOUT,
3908                                          &check_hello_validated, chvc);
3909   return GNUNET_OK;
3910 }
3911
3912
3913 /**
3914  * The peer specified by the given neighbour has timed-out or a plugin
3915  * has disconnected.  We may either need to do nothing (other plugins
3916  * still up), or trigger a full disconnect and clean up.  This
3917  * function updates our state and does the necessary notifications.
3918  * Also notifies our clients that the neighbour is now officially
3919  * gone.
3920  *
3921  * @param n the neighbour list entry for the peer
3922  * @param check should we just check if all plugins
3923  *        disconnected or must we ask all plugins to
3924  *        disconnect?
3925  */
3926 static void
3927 disconnect_neighbour (struct NeighbourList *n, int check)
3928 {
3929   struct ReadyList *rpos;
3930   struct NeighbourList *npos;
3931   struct NeighbourList *nprev;
3932   struct MessageQueue *mq;
3933   struct ForeignAddressList *peer_addresses;
3934   struct ForeignAddressList *peer_pos;
3935
3936   if (GNUNET_YES == check)
3937     {
3938       rpos = n->plugins;
3939       while (NULL != rpos)
3940         {
3941           peer_addresses = rpos->addresses;
3942           while (peer_addresses != NULL)
3943             {
3944               if (GNUNET_YES == peer_addresses->connected)
3945                 return;             /* still connected */
3946               peer_addresses = peer_addresses->next;
3947             }
3948           rpos = rpos->next;
3949         }
3950     }
3951 #if DEBUG_TRANSPORT
3952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3953               "Disconnecting from `%4s'\n",
3954               GNUNET_i2s (&n->id));
3955 #endif
3956   /* remove n from neighbours list */
3957   nprev = NULL;
3958   npos = neighbours;
3959   while ((npos != NULL) && (npos != n))
3960     {
3961       nprev = npos;
3962       npos = npos->next;
3963     }
3964   GNUNET_assert (npos != NULL);
3965   if (nprev == NULL)
3966     neighbours = n->next;
3967   else
3968     nprev->next = n->next;
3969
3970   /* notify all clients about disconnect */
3971   if (GNUNET_YES == n->received_pong)
3972     notify_clients_disconnect (&n->id);
3973
3974   /* clean up all plugins, cancel connections and pending transmissions */
3975   while (NULL != (rpos = n->plugins))
3976     {
3977       n->plugins = rpos->next;
3978       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3979       while (rpos->addresses != NULL)
3980         {
3981           peer_pos = rpos->addresses;
3982           rpos->addresses = peer_pos->next;
3983           if (peer_pos->connected == GNUNET_YES)
3984             GNUNET_STATISTICS_update (stats,
3985                                       gettext_noop ("# connected addresses"),
3986                                       -1,
3987                                       GNUNET_NO); 
3988           if (GNUNET_YES == peer_pos->validated)
3989             GNUNET_STATISTICS_update (stats,
3990                                       gettext_noop ("# peer addresses considered valid"),
3991                                       -1,
3992                                       GNUNET_NO);      
3993           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3994             {
3995               GNUNET_SCHEDULER_cancel (sched,
3996                                        peer_pos->revalidate_task);
3997               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3998             }
3999           GNUNET_free(peer_pos);
4000         }
4001       GNUNET_free (rpos);
4002     }
4003
4004   /* free all messages on the queue */
4005   while (NULL != (mq = n->messages_head))
4006     {
4007       GNUNET_STATISTICS_update (stats,
4008                                 gettext_noop ("# bytes in message queue for other peers"),
4009                                 - (int64_t) mq->message_buf_size,
4010                                 GNUNET_NO);
4011       GNUNET_STATISTICS_update (stats,
4012                                 gettext_noop ("# bytes discarded due to disconnect"),
4013                                 mq->message_buf_size,
4014                                 GNUNET_NO);
4015       GNUNET_CONTAINER_DLL_remove (n->messages_head,
4016                                    n->messages_tail,
4017                                    mq);
4018       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
4019                                  &n->id,
4020                                  sizeof(struct GNUNET_PeerIdentity)));
4021       GNUNET_free (mq);
4022     }
4023   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
4024     {
4025       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
4026       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4027     }
4028   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
4029     {
4030       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
4031       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
4032     }
4033   if (n->piter != NULL)
4034     {
4035       GNUNET_PEERINFO_iterate_cancel (n->piter);
4036       n->piter = NULL;
4037     }
4038   /* finally, free n itself */
4039   GNUNET_STATISTICS_update (stats,
4040                             gettext_noop ("# active neighbours"),
4041                             -1,
4042                             GNUNET_NO);
4043   GNUNET_free_non_null (n->pre_connect_message_buffer);
4044   GNUNET_free (n);
4045 }
4046
4047
4048 /**
4049  * We have received a PING message from someone.  Need to send a PONG message
4050  * in response to the peer by any means necessary. 
4051  */
4052 static int 
4053 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
4054             const struct GNUNET_PeerIdentity *peer,
4055             const char *sender_address,
4056             uint16_t sender_address_len)
4057 {
4058   struct TransportPlugin *plugin = cls;
4059   struct TransportPingMessage *ping;
4060   struct TransportPongMessage *pong;
4061   struct NeighbourList *n;
4062   struct ReadyList *rl;
4063   struct ForeignAddressList *fal;
4064
4065   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
4066     {
4067       GNUNET_break_op (0);
4068       return GNUNET_SYSERR;
4069     }
4070
4071   ping = (struct TransportPingMessage *) message;
4072   if (0 != memcmp (&ping->target,
4073                    plugin->env.my_identity,
4074                    sizeof (struct GNUNET_PeerIdentity)))
4075     {
4076       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4077                   _("Received `%s' message not destined for me!\n"), 
4078                   "PING");
4079       return GNUNET_SYSERR;
4080     }
4081 #if DEBUG_PING_PONG
4082   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4083               "Processing `%s' from `%s'\n",
4084               "PING", 
4085               (sender_address != NULL) 
4086               ? a2s (plugin->short_name,
4087                      (const struct sockaddr *)sender_address, 
4088                      sender_address_len)
4089               : "<inbound>");
4090 #endif
4091   GNUNET_STATISTICS_update (stats,
4092                             gettext_noop ("# PING messages received"),
4093                             1,
4094                             GNUNET_NO);
4095   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
4096   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
4097   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
4098   pong->purpose.size =
4099     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
4100            sizeof (uint32_t) +
4101            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
4102   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
4103   pong->challenge = ping->challenge;
4104   pong->addrlen = htons(sender_address_len);
4105   memcpy(&pong->signer, 
4106          &my_public_key, 
4107          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
4108   if (sender_address != NULL)
4109     memcpy (&pong[1], sender_address, sender_address_len);
4110 #if SIGN_USELESS
4111   GNUNET_assert (GNUNET_OK ==
4112                  GNUNET_CRYPTO_rsa_sign (my_private_key,
4113                                          &pong->purpose, &pong->signature));
4114 #endif
4115   n = find_neighbour(peer);
4116   GNUNET_assert (n != NULL);
4117   /* first try reliable response transmission */
4118   rl = n->plugins;
4119   while (rl != NULL)
4120     {
4121       fal = rl->addresses;
4122       while (fal != NULL)
4123         {
4124           if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
4125                                            peer,
4126                                            (const char*) pong,
4127                                            ntohs (pong->header.size),
4128                                            TRANSPORT_PONG_PRIORITY, 
4129                                            HELLO_VERIFICATION_TIMEOUT,
4130                                            fal->session,
4131                                            fal->addr,
4132                                            fal->addrlen,
4133                                            GNUNET_SYSERR,
4134                                            NULL, NULL))
4135             {
4136               /* done! */
4137               GNUNET_STATISTICS_update (stats,
4138                                         gettext_noop ("# PONGs unicast via reliable transport"),
4139                                         1,
4140                                         GNUNET_NO);      
4141               GNUNET_free (pong);
4142               return GNUNET_OK;
4143             }
4144           fal = fal->next;
4145         }
4146       rl = rl->next;
4147     }
4148   /* no reliable method found, do multicast */
4149   GNUNET_STATISTICS_update (stats,
4150                             gettext_noop ("# PONGs multicast to all available addresses"),
4151                             1,
4152                             GNUNET_NO);      
4153   rl = n->plugins;
4154   while (rl != NULL)
4155     {
4156       fal = rl->addresses;
4157       while (fal != NULL)
4158         {
4159           transmit_to_peer(NULL, fal,
4160                            TRANSPORT_PONG_PRIORITY, 
4161                            HELLO_VERIFICATION_TIMEOUT,
4162                            (const char *)pong, 
4163                            ntohs(pong->header.size), 
4164                            GNUNET_YES, 
4165                            n);
4166           fal = fal->next;
4167         }
4168       rl = rl->next;
4169     }
4170   GNUNET_free(pong);
4171   return GNUNET_OK;
4172 }
4173
4174
4175 /**
4176  * Function called by the plugin for each received message.
4177  * Update data volumes, possibly notify plugins about
4178  * reducing the rate at which they read from the socket
4179  * and generally forward to our receive callback.
4180  *
4181  * @param cls the "struct TransportPlugin *" we gave to the plugin
4182  * @param peer (claimed) identity of the other peer
4183  * @param message the message, NULL if we only care about
4184  *                learning about the delay until we should receive again
4185  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
4186  * @param session identifier used for this session (can be NULL)
4187  * @param sender_address binary address of the sender (if observed)
4188  * @param sender_address_len number of bytes in sender_address
4189  * @return how long the plugin should wait until receiving more data
4190  *         (plugins that do not support this, can ignore the return value)
4191  */
4192 static struct GNUNET_TIME_Relative
4193 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
4194                     const struct GNUNET_MessageHeader *message,
4195                     uint32_t distance,
4196                     struct Session *session,
4197                     const char *sender_address,
4198                     uint16_t sender_address_len)
4199 {
4200   struct TransportPlugin *plugin = cls;
4201   struct ReadyList *service_context;
4202   struct ForeignAddressList *peer_address;
4203   uint16_t msize;
4204   struct NeighbourList *n;
4205   struct GNUNET_TIME_Relative ret;
4206
4207   if (is_blacklisted (peer, plugin))
4208     return GNUNET_TIME_UNIT_FOREVER_REL;
4209
4210   n = find_neighbour (peer);
4211   if (n == NULL)
4212     n = setup_new_neighbour (peer, GNUNET_YES);
4213   service_context = n->plugins;
4214   while ((service_context != NULL) && (plugin != service_context->plugin))
4215     service_context = service_context->next;
4216   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
4217   peer_address = NULL;
4218   if (message != NULL)
4219     {
4220       if ( (session != NULL) ||
4221            (sender_address != NULL) )
4222         peer_address = add_peer_address (n, 
4223                                          plugin->short_name,
4224                                          session,
4225                                          sender_address, 
4226                                          sender_address_len);  
4227       if (peer_address != NULL)
4228         {
4229           peer_address->distance = distance;
4230           if (GNUNET_YES == peer_address->validated)
4231             mark_address_connected (peer_address);
4232           peer_address->timeout
4233             =
4234             GNUNET_TIME_relative_to_absolute
4235             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4236           schedule_next_ping (peer_address);
4237         }
4238       /* update traffic received amount ... */
4239       msize = ntohs (message->size);      
4240       GNUNET_STATISTICS_update (stats,
4241                                 gettext_noop ("# bytes received from other peers"),
4242                                 msize,
4243                                 GNUNET_NO);
4244       n->distance = distance;
4245       n->peer_timeout =
4246         GNUNET_TIME_relative_to_absolute
4247         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
4248       GNUNET_SCHEDULER_cancel (sched,
4249                                n->timeout_task);
4250       n->timeout_task =
4251         GNUNET_SCHEDULER_add_delayed (sched,
4252                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
4253                                       &neighbour_timeout_task, n);
4254       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
4255         {
4256           /* dropping message due to frequent inbound volume violations! */
4257           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
4258                       GNUNET_ERROR_TYPE_BULK,
4259                       _
4260                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
4261                       n->in_tracker.available_bytes_per_s__,
4262                       n->quota_violation_count);
4263           GNUNET_STATISTICS_update (stats,
4264                                     gettext_noop ("# bandwidth quota violations by other peers"),
4265                                     1,
4266                                     GNUNET_NO);
4267           return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
4268         }
4269 #if DEBUG_PING_PONG
4270           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4271                       "Received message of type %u and size %u from `%4s', sending to all clients.\n",
4272                       ntohs (message->type), 
4273                       ntohs (message->size), 
4274                       GNUNET_i2s (peer));
4275 #endif
4276       switch (ntohs (message->type))
4277         {
4278         case GNUNET_MESSAGE_TYPE_HELLO:
4279           GNUNET_STATISTICS_update (stats,
4280                                     gettext_noop ("# HELLO messages received from other peers"),
4281                                     1,
4282                                     GNUNET_NO);
4283           process_hello (plugin, message);
4284           break;
4285         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
4286           handle_ping (plugin, message, peer, sender_address, sender_address_len);
4287           break;
4288         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
4289           handle_pong (plugin, message, peer, sender_address, sender_address_len);
4290           break;
4291         default:
4292           handle_payload_message (message, n);
4293           break;
4294         }
4295     }  
4296   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
4297   if (ret.value > 0)
4298     {
4299       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4300                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
4301                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
4302                   (unsigned int) n->in_tracker.available_bytes_per_s__,
4303                   (unsigned long long) ret.value);
4304       GNUNET_STATISTICS_update (stats,
4305                                 gettext_noop ("# ms throttling suggested"),
4306                                 (int64_t) ret.value,
4307                                 GNUNET_NO);      
4308     }
4309   return ret;
4310 }
4311
4312 /**
4313  * Handle START-message.  This is the first message sent to us
4314  * by any client which causes us to add it to our list.
4315  *
4316  * @param cls closure (always NULL)
4317  * @param client identification of the client
4318  * @param message the actual message
4319  */
4320 static void
4321 handle_start (void *cls,
4322               struct GNUNET_SERVER_Client *client,
4323               const struct GNUNET_MessageHeader *message)
4324 {
4325   struct TransportClient *c;
4326   struct ConnectInfoMessage cim;
4327   struct NeighbourList *n;
4328
4329 #if DEBUG_TRANSPORT
4330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4331               "Received `%s' request from client\n", "START");
4332 #endif
4333   c = clients;
4334   while (c != NULL)
4335     {
4336       if (c->client == client)
4337         {
4338           /* client already on our list! */
4339           GNUNET_break (0);
4340           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4341           return;
4342         }
4343       c = c->next;
4344     }
4345   c = GNUNET_malloc (sizeof (struct TransportClient));
4346   c->next = clients;
4347   clients = c;
4348   c->client = client;
4349   if (our_hello != NULL)
4350     {
4351 #if DEBUG_TRANSPORT
4352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4353                   "Sending our own `%s' to new client\n", "HELLO");
4354 #endif
4355       transmit_to_client (c,
4356                           (const struct GNUNET_MessageHeader *) our_hello,
4357                           GNUNET_NO);
4358       /* tell new client about all existing connections */
4359       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
4360       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
4361       n = neighbours; 
4362       while (n != NULL)
4363         {
4364           if (GNUNET_YES == n->received_pong)
4365             {
4366               cim.id = n->id;
4367               cim.latency = GNUNET_TIME_relative_hton (n->latency);
4368               cim.distance = htonl (n->distance);
4369               transmit_to_client (c, &cim.header, GNUNET_NO);
4370             }
4371             n = n->next;
4372         }
4373     }
4374   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4375 }
4376
4377
4378 /**
4379  * Handle HELLO-message.
4380  *
4381  * @param cls closure (always NULL)
4382  * @param client identification of the client
4383  * @param message the actual message
4384  */
4385 static void
4386 handle_hello (void *cls,
4387               struct GNUNET_SERVER_Client *client,
4388               const struct GNUNET_MessageHeader *message)
4389 {
4390   int ret;
4391
4392   GNUNET_STATISTICS_update (stats,
4393                             gettext_noop ("# HELLOs received from clients"),
4394                             1,
4395                             GNUNET_NO);      
4396   ret = process_hello (NULL, message);
4397   GNUNET_SERVER_receive_done (client, ret);
4398 }
4399
4400
4401 /**
4402  * Closure for 'transmit_client_message'; followed by
4403  * 'msize' bytes of the actual message.
4404  */
4405 struct TransmitClientMessageContext 
4406 {
4407   /**
4408    * Client on whom's behalf we are sending.
4409    */
4410   struct GNUNET_SERVER_Client *client;
4411
4412   /**
4413    * Timeout for the transmission.
4414    */
4415   struct GNUNET_TIME_Absolute timeout;
4416   
4417   /**
4418    * Message priority.
4419    */
4420   uint32_t priority;
4421
4422   /**
4423    * Size of the message in bytes.
4424    */ 
4425   uint16_t msize;
4426 };
4427
4428
4429 /**
4430  * Schedule transmission of a message we got from a client to a peer.
4431  *
4432  * @param cls the 'struct TransmitClientMessageContext*'
4433  * @param n destination, or NULL on error (in that case, drop the message)
4434  */
4435 static void
4436 transmit_client_message (void *cls,
4437                          struct NeighbourList *n)
4438 {
4439   struct TransmitClientMessageContext *tcmc = cls;
4440   struct TransportClient *tc;
4441
4442   tc = clients;
4443   while ((tc != NULL) && (tc->client != tcmc->client))
4444     tc = tc->next;
4445
4446   if (n != NULL)
4447     {
4448       transmit_to_peer (tc, NULL, tcmc->priority, 
4449                         GNUNET_TIME_absolute_get_remaining (tcmc->timeout),
4450                         (char *)&tcmc[1],
4451                         tcmc->msize, GNUNET_NO, n);
4452     }
4453   GNUNET_SERVER_receive_done (tcmc->client, GNUNET_OK);
4454   GNUNET_SERVER_client_drop (tcmc->client);
4455   GNUNET_free (tcmc);
4456 }
4457
4458
4459 /**
4460  * Handle SEND-message.
4461  *
4462  * @param cls closure (always NULL)
4463  * @param client identification of the client
4464  * @param message the actual message
4465  */
4466 static void
4467 handle_send (void *cls,
4468              struct GNUNET_SERVER_Client *client,
4469              const struct GNUNET_MessageHeader *message)
4470 {
4471   const struct OutboundMessage *obm;
4472   const struct GNUNET_MessageHeader *obmm;
4473   struct TransmitClientMessageContext *tcmc;
4474   uint16_t size;
4475   uint16_t msize;
4476
4477   size = ntohs (message->size);
4478   if (size <
4479       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
4480     {
4481       GNUNET_break (0);
4482       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4483       return;
4484     }
4485   GNUNET_STATISTICS_update (stats,
4486                             gettext_noop ("# payload received for other peers"),
4487                             size,
4488                             GNUNET_NO);      
4489   obm = (const struct OutboundMessage *) message;
4490   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
4491   msize = size - sizeof (struct OutboundMessage);
4492 #if DEBUG_TRANSPORT
4493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4494               "Received `%s' request from client with target `%4s' and message of type %u and size %u\n",
4495               "SEND", GNUNET_i2s (&obm->peer),
4496               ntohs (obmm->type),
4497               msize);
4498 #endif
4499   tcmc = GNUNET_malloc (sizeof (struct TransmitClientMessageContext) + msize);
4500   tcmc->client = client;
4501   tcmc->priority = ntohl (obm->priority);
4502   tcmc->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (obm->timeout));
4503   tcmc->msize = msize;
4504   memcpy (&tcmc[1], obmm, msize);
4505   GNUNET_SERVER_client_keep (client);
4506   setup_peer_check_blacklist (&obm->peer, GNUNET_YES,
4507                               &transmit_client_message,
4508                               tcmc);
4509 }
4510
4511
4512 /**
4513  * Handle SET_QUOTA-message.
4514  *
4515  * @param cls closure (always NULL)
4516  * @param client identification of the client
4517  * @param message the actual message
4518  */
4519 static void
4520 handle_set_quota (void *cls,
4521                   struct GNUNET_SERVER_Client *client,
4522                   const struct GNUNET_MessageHeader *message)
4523 {
4524   const struct QuotaSetMessage *qsm =
4525     (const struct QuotaSetMessage *) message;
4526   struct NeighbourList *n;
4527   
4528   GNUNET_STATISTICS_update (stats,
4529                             gettext_noop ("# SET QUOTA messages received"),
4530                             1,
4531                             GNUNET_NO);      
4532   n = find_neighbour (&qsm->peer);
4533   if (n == NULL)
4534     {
4535       GNUNET_SERVER_receive_done (client, GNUNET_OK);
4536       GNUNET_STATISTICS_update (stats,
4537                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
4538                                 1,
4539                                 GNUNET_NO);      
4540       return;
4541     }
4542 #if DEBUG_TRANSPORT
4543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4544               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
4545               "SET_QUOTA", 
4546               (unsigned int) ntohl (qsm->quota.value__),
4547               (unsigned int) n->in_tracker.available_bytes_per_s__,
4548               GNUNET_i2s (&qsm->peer));
4549 #endif
4550   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
4551                                          qsm->quota);
4552   if (0 == ntohl (qsm->quota.value__)) 
4553     disconnect_neighbour (n, GNUNET_NO);    
4554   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4555 }
4556
4557
4558 /**
4559  * Take the given address and append it to the set of results sent back to
4560  * the client.
4561  * 
4562  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
4563  * @param address the resolved name, NULL to indicate the last response
4564  */
4565 static void
4566 transmit_address_to_client (void *cls, const char *address)
4567 {
4568   struct GNUNET_SERVER_TransmitContext *tc = cls;
4569   size_t slen;
4570
4571   if (NULL == address)
4572     slen = 0;
4573   else
4574     slen = strlen (address) + 1;
4575
4576   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
4577                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4578   if (NULL == address)
4579     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
4580 }
4581
4582
4583 /**
4584  * Handle AddressLookup-message.
4585  *
4586  * @param cls closure (always NULL)
4587  * @param client identification of the client
4588  * @param message the actual message
4589  */
4590 static void
4591 handle_address_lookup (void *cls,
4592                        struct GNUNET_SERVER_Client *client,
4593                        const struct GNUNET_MessageHeader *message)
4594 {
4595   const struct AddressLookupMessage *alum;
4596   struct TransportPlugin *lsPlugin;
4597   const char *nameTransport;
4598   const char *address;
4599   uint16_t size;
4600   struct GNUNET_SERVER_TransmitContext *tc;
4601   struct GNUNET_TIME_Absolute timeout;
4602   struct GNUNET_TIME_Relative rtimeout;
4603   int32_t numeric;
4604
4605   size = ntohs (message->size);
4606   if (size < sizeof (struct AddressLookupMessage))
4607     {
4608       GNUNET_break_op (0);
4609       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4610       return;
4611     }
4612   alum = (const struct AddressLookupMessage *) message;
4613   uint32_t addressLen = ntohl (alum->addrlen);
4614   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
4615     {
4616       GNUNET_break_op (0);
4617       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4618       return;
4619     }
4620   address = (const char *) &alum[1];
4621   nameTransport = (const char *) &address[addressLen];
4622   if (nameTransport
4623       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
4624     {
4625       GNUNET_break_op (0);
4626       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4627       return;
4628     }
4629   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
4630   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
4631   numeric = ntohl (alum->numeric_only);
4632   lsPlugin = find_transport (nameTransport);
4633   if (NULL == lsPlugin)
4634     {
4635       tc = GNUNET_SERVER_transmit_context_create (client);
4636       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
4637                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
4638       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
4639       return;
4640     }
4641   tc = GNUNET_SERVER_transmit_context_create (client);
4642   lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
4643                                          nameTransport,
4644                                          address, addressLen, 
4645                                          numeric,
4646                                          rtimeout,
4647                                          &transmit_address_to_client, tc);
4648 }
4649
4650
4651 /**
4652  * Setup the environment for this plugin.
4653  */
4654 static void
4655 create_environment (struct TransportPlugin *plug)
4656 {
4657   plug->env.cfg = cfg;
4658   plug->env.sched = sched;
4659   plug->env.my_identity = &my_identity;
4660   plug->env.cls = plug;
4661   plug->env.receive = &plugin_env_receive;
4662   plug->env.notify_address = &plugin_env_notify_address;
4663   plug->env.session_end = &plugin_env_session_end;
4664   plug->env.max_connections = max_connect_per_transport;
4665   plug->env.stats = stats;
4666 }
4667
4668
4669 /**
4670  * Start the specified transport (load the plugin).
4671  */
4672 static void
4673 start_transport (struct GNUNET_SERVER_Handle *server, 
4674                  const char *name)
4675 {
4676   struct TransportPlugin *plug;
4677   char *libname;
4678
4679   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4680               _("Loading `%s' transport plugin\n"), name);
4681   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
4682   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
4683   create_environment (plug);
4684   plug->short_name = GNUNET_strdup (name);
4685   plug->lib_name = libname;
4686   plug->next = plugins;
4687   plugins = plug;
4688   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
4689   if (plug->api == NULL)
4690     {
4691       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4692                   _("Failed to load transport plugin for `%s'\n"), name);
4693       GNUNET_free (plug->short_name);
4694       plugins = plug->next;
4695       GNUNET_free (libname);
4696       GNUNET_free (plug);
4697     }
4698 }
4699
4700
4701 /**
4702  * Called whenever a client is disconnected.  Frees our
4703  * resources associated with that client.
4704  *
4705  * @param cls closure
4706  * @param client identification of the client
4707  */
4708 static void
4709 client_disconnect_notification (void *cls,
4710                                 struct GNUNET_SERVER_Client *client)
4711 {
4712   struct TransportClient *pos;
4713   struct TransportClient *prev;
4714   struct ClientMessageQueueEntry *mqe;
4715   struct Blacklisters *bl;
4716   struct BlacklistCheck *bc;
4717
4718   if (client == NULL)
4719     return;
4720 #if DEBUG_TRANSPORT
4721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
4722               "Client disconnected, cleaning up.\n");
4723 #endif
4724   /* clean up blacklister */
4725   bl = bl_head;
4726   while (bl != NULL)
4727     {
4728       if (bl->client == client)
4729         {
4730           bc = bc_head;
4731           while (bc != NULL)
4732             {
4733               if (bc->bl_pos == bl)
4734                 {
4735                   bc->bl_pos = bl->next;
4736                   if (bc->th != NULL)
4737                     {
4738                       GNUNET_CONNECTION_notify_transmit_ready_cancel (bc->th);
4739                       bc->th = NULL;                  
4740                     }
4741                   if (bc->task == GNUNET_SCHEDULER_NO_TASK)
4742                     bc->task = GNUNET_SCHEDULER_add_now (sched,
4743                                                          &do_blacklist_check,
4744                                                          bc);
4745                   break;
4746                 }
4747               bc = bc->next;
4748             }
4749           GNUNET_CONTAINER_DLL_remove (bl_head,
4750                                        bl_tail,
4751                                        bl);
4752           GNUNET_SERVER_client_drop (bl->client);
4753           GNUNET_free (bl);
4754           break;
4755         }
4756       bl = bl->next;
4757     }
4758   /* clean up 'normal' clients */
4759   prev = NULL;
4760   pos = clients;
4761   while ((pos != NULL) && (pos->client != client))
4762     {
4763       prev = pos;
4764       pos = pos->next;
4765     }
4766   if (pos == NULL)
4767     return;
4768   while (NULL != (mqe = pos->message_queue_head))
4769     {
4770       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
4771                                    pos->message_queue_tail,
4772                                    mqe);
4773       pos->message_count--;
4774       GNUNET_free (mqe);
4775     }
4776   if (prev == NULL)
4777     clients = pos->next;
4778   else
4779     prev->next = pos->next;
4780   if (GNUNET_YES == pos->tcs_pending)
4781     {
4782       pos->client = NULL;
4783       return;
4784     }
4785   if (pos->th != NULL)
4786     {
4787       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
4788       pos->th = NULL;
4789     }
4790   GNUNET_break (0 == pos->message_count);
4791   GNUNET_free (pos);
4792 }
4793
4794
4795 /**
4796  * Function called when the service shuts down.  Unloads our plugins
4797  * and cancels pending validations.
4798  *
4799  * @param cls closure, unused
4800  * @param tc task context (unused)
4801  */
4802 static void
4803 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4804 {
4805   struct TransportPlugin *plug;
4806   struct OwnAddressList *al;
4807   struct CheckHelloValidatedContext *chvc;
4808
4809   while (neighbours != NULL)
4810     disconnect_neighbour (neighbours, GNUNET_NO);
4811 #if DEBUG_TRANSPORT
4812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4813               "Transport service is unloading plugins...\n");
4814 #endif
4815   while (NULL != (plug = plugins))
4816     {
4817       plugins = plug->next;
4818       if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
4819         {
4820           GNUNET_SCHEDULER_cancel (plug->env.sched, 
4821                                    plug->address_update_task);
4822           plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
4823         }
4824       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
4825       GNUNET_free (plug->lib_name);
4826       GNUNET_free (plug->short_name);
4827       while (NULL != (al = plug->addresses))
4828         {
4829           plug->addresses = al->next;
4830           GNUNET_free (al);
4831         }
4832       GNUNET_free (plug);
4833     }
4834   if (my_private_key != NULL)
4835     GNUNET_CRYPTO_rsa_key_free (my_private_key);
4836   GNUNET_free_non_null (our_hello);
4837
4838   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
4839                                          &abort_validation,
4840                                          NULL);
4841   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4842   validation_map = NULL;
4843
4844   /* free 'chvc' data structure */
4845   while (NULL != (chvc = chvc_head))
4846     {
4847       chvc_head = chvc->next;
4848       if (chvc->piter != NULL)
4849         GNUNET_PEERINFO_iterate_cancel (chvc->piter);      
4850       else
4851         GNUNET_break (0);
4852       GNUNET_assert (chvc->ve_count == 0);
4853       GNUNET_free (chvc);
4854     }
4855   chvc_tail = NULL;
4856
4857   if (stats != NULL)
4858     {
4859       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4860       stats = NULL;
4861     }
4862   if (peerinfo != NULL)
4863     {
4864       GNUNET_PEERINFO_disconnect (peerinfo);
4865       peerinfo = NULL;
4866     }
4867   /* Can we assume those are gone by now, or do we need to clean up
4868      explicitly!? */
4869   GNUNET_break (bl_head == NULL);
4870   GNUNET_break (bc_head == NULL);
4871 }
4872
4873
4874 /**
4875  * Initiate transport service.
4876  *
4877  * @param cls closure
4878  * @param s scheduler to use
4879  * @param server the initialized server
4880  * @param c configuration to use
4881  */
4882 static void
4883 run (void *cls,
4884      struct GNUNET_SCHEDULER_Handle *s,
4885      struct GNUNET_SERVER_Handle *server,
4886      const struct GNUNET_CONFIGURATION_Handle *c)
4887 {
4888   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4889     {&handle_start, NULL,
4890      GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
4891     {&handle_hello, NULL,
4892      GNUNET_MESSAGE_TYPE_HELLO, 0},
4893     {&handle_send, NULL,
4894      GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
4895     {&handle_set_quota, NULL,
4896      GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
4897     {&handle_address_lookup, NULL,
4898      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
4899      0},
4900     {&handle_blacklist_init, NULL,
4901      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT, sizeof (struct GNUNET_MessageHeader)},
4902     {&handle_blacklist_reply, NULL,
4903      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY, sizeof (struct BlacklistMessage)},
4904     {NULL, NULL, 0, 0}
4905   };
4906   char *plugs;
4907   char *pos;
4908   int no_transports;
4909   unsigned long long tneigh;
4910   char *keyfile;
4911
4912   sched = s;
4913   cfg = c;
4914   stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4915   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4916   /* parse configuration */
4917   if ((GNUNET_OK !=
4918        GNUNET_CONFIGURATION_get_value_number (c,
4919                                               "TRANSPORT",
4920                                               "NEIGHBOUR_LIMIT",
4921                                               &tneigh)) ||
4922       (GNUNET_OK !=
4923        GNUNET_CONFIGURATION_get_value_filename (c,
4924                                                 "GNUNETD",
4925                                                 "HOSTKEY", &keyfile)))
4926     {
4927       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4928                   _
4929                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
4930       GNUNET_SCHEDULER_shutdown (s);
4931       if (stats != NULL)
4932         {
4933           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4934           stats = NULL;
4935         }
4936       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4937       validation_map = NULL;
4938       return;
4939     }
4940   max_connect_per_transport = (uint32_t) tneigh;
4941   peerinfo = GNUNET_PEERINFO_connect (sched, cfg);
4942   if (peerinfo == NULL)
4943     {
4944       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4945                   _("Could not access PEERINFO service.  Exiting.\n"));     
4946       GNUNET_SCHEDULER_shutdown (s);
4947       if (stats != NULL)
4948         {
4949           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4950           stats = NULL;
4951         }
4952       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4953       validation_map = NULL;
4954       GNUNET_free (keyfile);
4955       return;
4956     }
4957   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4958   GNUNET_free (keyfile);
4959   if (my_private_key == NULL)
4960     {
4961       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4962                   _
4963                   ("Transport service could not access hostkey.  Exiting.\n"));
4964       GNUNET_SCHEDULER_shutdown (s);
4965       if (stats != NULL)
4966         {
4967           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4968           stats = NULL;
4969         }
4970       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4971       validation_map = NULL;
4972       return;
4973     }
4974   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4975   GNUNET_CRYPTO_hash (&my_public_key,
4976                       sizeof (my_public_key), &my_identity.hashPubKey);
4977   /* setup notification */
4978   GNUNET_SERVER_disconnect_notify (server,
4979                                    &client_disconnect_notification, NULL);
4980   /* load plugins... */
4981   no_transports = 1;
4982   if (GNUNET_OK ==
4983       GNUNET_CONFIGURATION_get_value_string (c,
4984                                              "TRANSPORT", "PLUGINS", &plugs))
4985     {
4986       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4987                   _("Starting transport plugins `%s'\n"), plugs);
4988       pos = strtok (plugs, " ");
4989       while (pos != NULL)
4990         {
4991           start_transport (server, pos);
4992           no_transports = 0;
4993           pos = strtok (NULL, " ");
4994         }
4995       GNUNET_free (plugs);
4996     }
4997   GNUNET_SCHEDULER_add_delayed (sched,
4998                                 GNUNET_TIME_UNIT_FOREVER_REL,
4999                                 &shutdown_task, NULL);
5000   if (no_transports)
5001     refresh_hello ();
5002
5003 #if DEBUG_TRANSPORT
5004   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
5005 #endif
5006   /* If we have a blacklist file, read from it */
5007   read_blacklist_file(cfg);
5008   /* process client requests */
5009   GNUNET_SERVER_add_handlers (server, handlers);
5010 }
5011
5012
5013 /**
5014  * The main function for the transport service.
5015  *
5016  * @param argc number of arguments from the command line
5017  * @param argv command line arguments
5018  * @return 0 ok, 1 on error
5019  */
5020 int
5021 main (int argc, char *const *argv)
5022 {
5023   a2s (NULL, NULL, 0); /* make compiler happy */
5024   return (GNUNET_OK ==
5025           GNUNET_SERVICE_run (argc,
5026                               argv,
5027                               "transport",
5028                               GNUNET_SERVICE_OPTION_NONE,
5029                               &run, NULL)) ? 0 : 1;
5030 }
5031
5032 /* end of gnunet-service-transport.c */