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