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