fix
[oweals/gnunet.git] / src / transport / gnunet-service-transport.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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  */
32 #include "platform.h"
33 #include "gnunet_client_lib.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet_constants.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_os_lib.h"
39 #include "gnunet_peerinfo_service.h"
40 #include "gnunet_plugin_lib.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_service_lib.h"
43 #include "gnunet_signatures.h"
44 #include "plugin_transport.h"
45 #include "transport.h"
46
47 /**
48  * Should we do some additional checks (to validate behavior
49  * of clients)?
50  */
51 #define EXTRA_CHECKS GNUNET_YES
52
53 /**
54  * How many messages can we have pending for a given client process
55  * before we start to drop incoming messages?  We typically should
56  * have only one client and so this would be the primary buffer for
57  * messages, so the number should be chosen rather generously.
58  *
59  * The expectation here is that most of the time the queue is large
60  * enough so that a drop is virtually never required.
61  */
62 #define MAX_PENDING 128
63
64 /**
65  * How often should we try to reconnect to a peer using a particular
66  * transport plugin before giving up?  Note that the plugin may be
67  * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
68  */
69 #define MAX_CONNECT_RETRY 3
70
71 /**
72  * Limit on the number of ready-to-run tasks when validating 
73  * HELLOs.  If more tasks are ready to run, we will drop 
74  * HELLOs instead of validating them.
75  */
76 #define MAX_HELLO_LOAD 4
77
78 /**
79  * How often must a peer violate bandwidth quotas before we start
80  * to simply drop its messages?
81  */
82 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
83
84 /**
85  * How long until a HELLO verification attempt should time out?
86  * Must be rather small, otherwise a partially successful HELLO
87  * validation (some addresses working) might not be available
88  * before a client's request for a connection fails for good.
89  * Besides, if a single request to an address takes a long time,
90  * then the peer is unlikely worthwhile anyway.
91  */
92 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
93
94 /**
95  * How long will we allow sending of a ping to be delayed?
96  */
97 #define TRANSPORT_DEFAULT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
98
99 /**
100  * Priority to use for PONG messages.
101  */
102 #define TRANSPORT_PONG_PRIORITY 4
103
104 /**
105  * How often do we re-add (cheaper) plugins to our list of plugins
106  * to try for a given connected peer?
107  */
108 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
109
110 /**
111  * After how long do we expire an address in a HELLO that we just
112  * validated?  This value is also used for our own addresses when we
113  * create a HELLO.
114  */
115 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
116
117
118 /**
119  * How long before an existing address expires should we again try to
120  * validate it?  Must be (significantly) smaller than
121  * HELLO_ADDRESS_EXPIRATION.
122  */
123 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
124
125 /**
126  * Maximum frequency for re-evaluating latencies for all transport addresses.
127  */
128 #define LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
129
130 /**
131  * Maximum frequency for re-evaluating latencies for connected addresses.
132  */
133 #define CONNECTED_LATENCY_EVALUATION_MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1)
134
135
136 /**
137  * List of addresses of other peers
138  */
139 struct ForeignAddressList
140 {
141   /**
142    * This is a linked list.
143    */
144   struct ForeignAddressList *next;
145
146   /**
147    * Which ready list does this entry belong to.
148    */
149   struct ReadyList *ready_list;
150
151   /**
152    * How long until we auto-expire this address (unless it is
153    * re-confirmed by the transport)?
154    */
155   struct GNUNET_TIME_Absolute expires;
156
157   /**
158    * Task used to re-validate addresses, updates latencies and
159    * verifies liveness.
160    */
161   GNUNET_SCHEDULER_TaskIdentifier revalidate_task;
162
163   /**
164    * Length of addr.
165    */
166   size_t addrlen;
167
168   /**
169    * The address.
170    */
171   const void *addr;
172
173   /**
174    * What was the last latency observed for this address, plugin and peer?
175    */
176   struct GNUNET_TIME_Relative latency;
177
178   /**
179    * If we did not successfully transmit a message to the given peer
180    * via this connection during the specified time, we should consider
181    * the connection to be dead.  This is used in the case that a TCP
182    * transport simply stalls writing to the stream but does not
183    * formerly get a signal that the other peer died.
184    */
185   struct GNUNET_TIME_Absolute timeout;
186
187   /**
188    * How often have we tried to connect using this plugin?  Used to
189    * discriminate against addresses that do not work well.
190    * FIXME: not yet used, but should be!
191    */
192   unsigned int connect_attempts;
193
194   /**
195    * DV distance to this peer (1 if no DV is used). 
196    * FIXME: need to set this from transport plugins!
197    */
198   uint32_t distance;
199
200   /**
201    * Have we ever estimated the latency of this address?  Used to
202    * ensure that the first time we add an address, we immediately
203    * probe its latency.
204    */
205   int8_t estimated;
206
207   /**
208    * Are we currently connected via this address?  The first time we
209    * successfully transmit or receive data to a peer via a particular
210    * address, we set this to GNUNET_YES.  If we later get an error
211    * (disconnect notification, transmission failure, timeout), we set
212    * it back to GNUNET_NO.  
213    */
214   int8_t connected;
215
216   /**
217    * Is this plugin currently busy transmitting to the specific target?
218    * GNUNET_NO if not (initial, default state is GNUNET_NO).   Internal
219    * messages do not count as 'in transmit'.
220    */
221   int8_t in_transmit;
222
223   /**
224    * Has this address been validated yet?
225    */
226   int8_t validated;
227
228 };
229
230
231 /**
232  * Entry in linked list of network addresses for ourselves.
233  */
234 struct OwnAddressList
235 {
236   /**
237    * This is a linked list.
238    */
239   struct OwnAddressList *next;
240
241   /**
242    * The address, actually a pointer to the end
243    * of this struct.  Do not free!
244    */
245   const void *addr;
246   
247   /**
248    * How long until we auto-expire this address (unless it is
249    * re-confirmed by the transport)?
250    */
251   struct GNUNET_TIME_Absolute expires;
252
253   /**
254    * Length of addr.
255    */
256   size_t addrlen;
257
258 };
259
260
261 /**
262  * Entry in linked list of all of our plugins.
263  */
264 struct TransportPlugin
265 {
266
267   /**
268    * This is a linked list.
269    */
270   struct TransportPlugin *next;
271
272   /**
273    * API of the transport as returned by the plugin's
274    * initialization function.
275    */
276   struct GNUNET_TRANSPORT_PluginFunctions *api;
277
278   /**
279    * Short name for the plugin (i.e. "tcp").
280    */
281   char *short_name;
282
283   /**
284    * Name of the library (i.e. "gnunet_plugin_transport_tcp").
285    */
286   char *lib_name;
287
288   /**
289    * List of our known addresses for this transport.
290    */
291   struct OwnAddressList *addresses;
292
293   /**
294    * Environment this transport service is using
295    * for this plugin.
296    */
297   struct GNUNET_TRANSPORT_PluginEnvironment env;
298
299   /**
300    * ID of task that is used to clean up expired addresses.
301    */
302   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
303
304   /**
305    * Set to GNUNET_YES if we need to scrap the existing list of
306    * "addresses" and start fresh when we receive the next address
307    * update from a transport.  Set to GNUNET_NO if we should just add
308    * the new address to the list and wait for the commit call.
309    */
310   int rebuild;
311
312 };
313
314 struct NeighbourList;
315
316 /**
317  * For each neighbour we keep a list of messages
318  * that we still want to transmit to the neighbour.
319  */
320 struct MessageQueue
321 {
322
323   /**
324    * This is a doubly linked list.
325    */
326   struct MessageQueue *next;
327
328   /**
329    * This is a doubly linked list.
330    */
331   struct MessageQueue *prev;
332
333   /**
334    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
335    * stuck together in memory.  Allocated at the end of this struct.
336    */
337   const char *message_buf;
338
339   /**
340    * Size of the message buf
341    */
342   size_t message_buf_size;
343
344   /**
345    * Client responsible for queueing the message;
346    * used to check that a client has no two messages
347    * pending for the same target.  Can be NULL.
348    */
349   struct TransportClient *client;
350
351   /**
352    * Using which specific address should we send this message?
353    */
354   struct ForeignAddressList *specific_address;
355
356   /**
357    * Peer ID of the Neighbour this entry belongs to.
358    */
359   struct GNUNET_PeerIdentity neighbour_id;
360
361   /**
362    * Plugin that we used for the transmission.
363    * NULL until we scheduled a transmission.
364    */
365   struct TransportPlugin *plugin;
366
367   /**
368    * At what time should we fail?
369    */
370   struct GNUNET_TIME_Absolute timeout;
371
372   /**
373    * Internal message of the transport system that should not be
374    * included in the usual SEND-SEND_OK transmission confirmation
375    * traffic management scheme.  Typically, "internal_msg" will
376    * be set whenever "client" is NULL (but it is not strictly
377    * required).
378    */
379   int internal_msg;
380
381   /**
382    * How important is the message?
383    */
384   unsigned int priority;
385
386 };
387
388
389 /**
390  * For a given Neighbour, which plugins are available
391  * to talk to this peer and what are their costs?
392  */
393 struct ReadyList
394 {
395   /**
396    * This is a linked list.
397    */
398   struct ReadyList *next;
399
400   /**
401    * Which of our transport plugins does this entry
402    * represent?
403    */
404   struct TransportPlugin *plugin;
405
406   /**
407    * Transport addresses, latency, and readiness for
408    * this particular plugin.
409    */
410   struct ForeignAddressList *addresses;
411
412   /**
413    * To which neighbour does this ready list belong to?
414    */
415   struct NeighbourList *neighbour;
416
417 };
418
419
420 /**
421  * Entry in linked list of all of our current neighbours.
422  */
423 struct NeighbourList
424 {
425
426   /**
427    * This is a linked list.
428    */
429   struct NeighbourList *next;
430
431   /**
432    * Which of our transports is connected to this peer
433    * and what is their status?
434    */
435   struct ReadyList *plugins;
436
437   /**
438    * Head of list of messages we would like to send to this peer;
439    * must contain at most one message per client.
440    */
441   struct MessageQueue *messages_head;
442
443   /**
444    * Tail of list of messages we would like to send to this peer; must
445    * contain at most one message per client.
446    */
447   struct MessageQueue *messages_tail;
448
449   /**
450    * Context for peerinfo iteration.
451    * NULL after we are done processing peerinfo's information.
452    */
453   struct GNUNET_PEERINFO_IteratorContext *piter;
454
455   /**
456    * Public key for this peer.   Valid only if the respective flag is set below.
457    */
458   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
459
460   /**
461    * Identity of this neighbour.
462    */
463   struct GNUNET_PeerIdentity id;
464
465   /**
466    * ID of task scheduled to run when this peer is about to
467    * time out (will free resources associated with the peer).
468    */
469   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
470
471   /**
472    * ID of task scheduled to run when we should retry transmitting
473    * the head of the message queue.  Actually triggered when the
474    * transmission is timing out (we trigger instantly when we have
475    * a chance of success).
476    */
477   GNUNET_SCHEDULER_TaskIdentifier retry_task;
478
479   /**
480    * How long until we should consider this peer dead
481    * (if we don't receive another message in the
482    * meantime)?
483    */
484   struct GNUNET_TIME_Absolute peer_timeout;
485
486   /**
487    * Tracker for inbound bandwidth.
488    */
489   struct GNUNET_BANDWIDTH_Tracker in_tracker;
490
491   /**
492    * The latency we have seen for this particular address for
493    * this particular peer.  This latency may have been calculated
494    * over multiple transports.  This value reflects how long it took
495    * us to receive a response when SENDING via this particular
496    * transport/neighbour/address combination!
497    *
498    * FIXME: we need to periodically send PINGs to update this
499    * latency (at least more often than the current "huge" (11h?)
500    * update interval).
501    */
502   struct GNUNET_TIME_Relative latency;
503
504   /**
505    * How often has the other peer (recently) violated the
506    * inbound traffic limit?  Incremented by 10 per violation,
507    * decremented by 1 per non-violation (for each
508    * time interval).
509    */
510   unsigned int quota_violation_count;
511
512   /**
513    * DV distance to this peer (1 if no DV is used). 
514    */
515   uint32_t distance;
516
517   /**
518    * Have we seen an PONG from this neighbour in the past (and
519    * not had a disconnect since)?
520    */
521   int received_pong;
522
523   /**
524    * Do we have a valid public key for this neighbour?
525    */
526   int public_key_valid;
527
528 };
529
530 /**
531  * Message used to ask a peer to validate receipt (to check an address
532  * from a HELLO).  
533  */
534 struct TransportPingMessage
535 {
536
537   /**
538    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
539    */
540   struct GNUNET_MessageHeader header;
541
542   /**
543    * Random challenge number (in network byte order).
544    */
545   uint32_t challenge GNUNET_PACKED;
546
547   /**
548    * Who is the intended recipient?
549    */
550   struct GNUNET_PeerIdentity target;
551
552 };
553
554
555 /**
556  * Message used to validate a HELLO.  The challenge is included in the
557  * confirmation to make matching of replies to requests possible.  The
558  * signature signs the original challenge number, our public key, the
559  * sender's address (so that the sender can check that the address we
560  * saw is plausible for him and possibly detect a MiM attack) and a
561  * timestamp (to limit replay).<p>
562  *
563  * This message is followed by the address of the
564  * client that we are observing (which is part of what
565  * is being signed).
566  */
567 struct TransportPongMessage
568 {
569
570   /**
571    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
572    */
573   struct GNUNET_MessageHeader header;
574
575   /**
576    * For padding, always zero.
577    */
578   uint32_t reserved GNUNET_PACKED;
579
580   /**
581    * Signature.
582    */
583   struct GNUNET_CRYPTO_RsaSignature signature;
584
585   /**
586    * What are we signing and why?
587    */
588   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
589
590   /**
591    * Random challenge number (in network byte order).
592    */
593   uint32_t challenge GNUNET_PACKED;
594
595   /**
596    * Who signed this message?
597    */
598   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
599
600   /**
601    * Size of address appended to this message
602    */
603   size_t addrlen;
604
605 };
606
607
608 /**
609  * Linked list of messages to be transmitted to the client.  Each
610  * entry is followed by the actual message.
611  */
612 struct ClientMessageQueueEntry
613 {
614   /**
615    * This is a doubly-linked list.
616    */
617   struct ClientMessageQueueEntry *next;
618
619   /**
620    * This is a doubly-linked list.
621    */
622   struct ClientMessageQueueEntry *prev;
623 };
624
625
626 /**
627  * Client connected to the transport service.
628  */
629 struct TransportClient
630 {
631
632   /**
633    * This is a linked list.
634    */
635   struct TransportClient *next;
636
637   /**
638    * Handle to the client.
639    */
640   struct GNUNET_SERVER_Client *client;
641
642   /**
643    * Linked list of messages yet to be transmitted to
644    * the client.
645    */
646   struct ClientMessageQueueEntry *message_queue_head;
647
648   /**
649    * Tail of linked list of messages yet to be transmitted to the
650    * client.
651    */
652   struct ClientMessageQueueEntry *message_queue_tail;
653
654   /**
655    * Current transmit request handle.
656    */ 
657   struct GNUNET_CONNECTION_TransmitHandle *th;
658
659   /**
660    * Is a call to "transmit_send_continuation" pending?  If so, we
661    * must not free this struct (even if the corresponding client
662    * disconnects) and instead only remove it from the linked list and
663    * set the "client" field to NULL.
664    */
665   int tcs_pending;
666
667   /**
668    * Length of the list of messages pending for this client.
669    */
670   unsigned int message_count;
671
672 };
673
674
675 /**
676  * Entry in map of all HELLOs awaiting validation.
677  */
678 struct ValidationEntry
679 {
680
681   /**
682    * The address, actually a pointer to the end
683    * of this struct.  Do not free!
684    */
685   const void *addr;
686
687   /**
688    * Name of the transport.
689    */
690   char *transport_name;
691
692   /**
693    * The public key of the peer.
694    */
695   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
696
697   /**
698    * ID of task that will clean up this entry if we don't succeed
699    * with the validation first.
700    */
701   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
702
703   /**
704    * At what time did we send this validation?
705    */
706   struct GNUNET_TIME_Absolute send_time;
707
708   /**
709    * Length of addr.
710    */
711   size_t addrlen;
712
713   /**
714    * Challenge number we used.
715    */
716   uint32_t challenge;
717
718 };
719
720
721 /**
722  * Context of currently active requests to peerinfo
723  * for validation of HELLOs.
724  */
725 struct CheckHelloValidatedContext
726 {
727
728   /**
729    * This is a doubly-linked list.
730    */
731   struct CheckHelloValidatedContext *next;
732
733   /**
734    * This is a doubly-linked list.
735    */
736   struct CheckHelloValidatedContext *prev;
737
738   /**
739    * Hello that we are validating.
740    */
741   const struct GNUNET_HELLO_Message *hello;
742
743   /**
744    * Context for peerinfo iteration.
745    * NULL after we are done processing peerinfo's information.
746    */
747   struct GNUNET_PEERINFO_IteratorContext *piter;
748   
749   /**
750    * Was a HELLO known for this peer to peerinfo?
751    */
752   int hello_known;
753
754 };
755
756
757 /**
758  * Our HELLO message.
759  */
760 static struct GNUNET_HELLO_Message *our_hello;
761
762 /**
763  * "version" of "our_hello".  Used to see if a given neighbour has
764  * already been sent the latest version of our HELLO message.
765  */
766 static unsigned int our_hello_version;
767
768 /**
769  * Our public key.
770  */
771 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
772
773 /**
774  * Our identity.
775  */
776 static struct GNUNET_PeerIdentity my_identity;
777
778 /**
779  * Our private key.
780  */
781 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
782
783 /**
784  * Our scheduler.
785  */
786 struct GNUNET_SCHEDULER_Handle *sched;
787
788 /**
789  * Our configuration.
790  */
791 const struct GNUNET_CONFIGURATION_Handle *cfg;
792
793 /**
794  * Linked list of all clients to this service.
795  */
796 static struct TransportClient *clients;
797
798 /**
799  * All loaded plugins.
800  */
801 static struct TransportPlugin *plugins;
802
803 /**
804  * Our server.
805  */
806 static struct GNUNET_SERVER_Handle *server;
807
808 /**
809  * All known neighbours and their HELLOs.
810  */
811 static struct NeighbourList *neighbours;
812
813 /**
814  * Number of neighbours we'd like to have.
815  */
816 static uint32_t max_connect_per_transport;
817
818 /**
819  * Head of linked list.
820  */
821 static struct CheckHelloValidatedContext *chvc_head;
822
823 /**
824  * Tail of linked list.
825  */
826 static struct CheckHelloValidatedContext *chvc_tail;
827
828 /**
829  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
830  * of the given peer that we are currently validating).
831  */
832 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
833
834 /**
835  * Handle for reporting statistics.
836  */
837 static struct GNUNET_STATISTICS_Handle *stats;
838
839
840 /**
841  * The peer specified by the given neighbour has timed-out or a plugin
842  * has disconnected.  We may either need to do nothing (other plugins
843  * still up), or trigger a full disconnect and clean up.  This
844  * function updates our state and do the necessary notifications.
845  * Also notifies our clients that the neighbour is now officially
846  * gone.
847  *
848  * @param n the neighbour list entry for the peer
849  * @param check should we just check if all plugins
850  *        disconnected or must we ask all plugins to
851  *        disconnect?
852  */
853 static void disconnect_neighbour (struct NeighbourList *n, int check);
854
855 /**
856  * Check the ready list for the given neighbour and if a plugin is
857  * ready for transmission (and if we have a message), do so!
858  *
859  * @param neighbour target peer for which to transmit
860  */
861 static void try_transmission_to_peer (struct NeighbourList *neighbour);
862
863
864 /**
865  * Find an entry in the neighbour list for a particular peer.
866  *  
867  * @return NULL if not found.
868  */
869 static struct NeighbourList *
870 find_neighbour (const struct GNUNET_PeerIdentity *key)
871 {
872   struct NeighbourList *head = neighbours;
873
874   while ((head != NULL) &&
875         (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
876     head = head->next;
877   return head;
878 }
879
880
881 /**
882  * Find an entry in the transport list for a particular transport.
883  *
884  * @return NULL if not found.
885  */
886 static struct TransportPlugin *
887 find_transport (const char *short_name)
888 {
889   struct TransportPlugin *head = plugins;
890   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
891     head = head->next;
892   return head;
893 }
894
895
896 /**
897  * Function called to notify a client about the socket being ready to
898  * queue more data.  "buf" will be NULL and "size" zero if the socket
899  * was closed for writing in the meantime.
900  *
901  * @param cls closure
902  * @param size number of bytes available in buf
903  * @param buf where the callee should write the message
904  * @return number of bytes written to buf
905  */
906 static size_t
907 transmit_to_client_callback (void *cls, size_t size, void *buf)
908 {
909   struct TransportClient *client = cls;
910   struct ClientMessageQueueEntry *q;
911   uint16_t msize;
912   size_t tsize;
913   const struct GNUNET_MessageHeader *msg;
914   char *cbuf;
915
916   client->th = NULL;
917   if (buf == NULL)
918     {
919       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
920                   "Transmission to client failed, closing connection.\n");
921       /* fatal error with client, free message queue! */
922       while (NULL != (q = client->message_queue_head))
923         {
924           GNUNET_STATISTICS_update (stats,
925                                     gettext_noop ("# bytes discarded (could not transmit to client)"),
926                                     ntohs (((const struct GNUNET_MessageHeader*)&q[1])->size),
927                                     GNUNET_NO);      
928           GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
929                                        client->message_queue_tail,
930                                        q);
931           GNUNET_free (q);
932         }
933       client->message_count = 0;
934       return 0;
935     }
936   cbuf = buf;
937   tsize = 0;
938   while (NULL != (q = client->message_queue_head))
939     {
940       msg = (const struct GNUNET_MessageHeader *) &q[1];
941       msize = ntohs (msg->size);
942       if (msize + tsize > size)
943         break;
944 #if DEBUG_TRANSPORT
945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946                   "Transmitting message of type %u to client.\n",
947                   ntohs (msg->type));
948 #endif
949       GNUNET_CONTAINER_DLL_remove (client->message_queue_head,
950                                    client->message_queue_tail,
951                                    q);
952       memcpy (&cbuf[tsize], msg, msize);
953       tsize += msize;
954       GNUNET_free (q);
955       client->message_count--;
956     }
957   if (NULL != q)
958     {
959       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
960       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
961                                                         msize,
962                                                         GNUNET_TIME_UNIT_FOREVER_REL,
963                                                         &transmit_to_client_callback,
964                                                         client);
965       GNUNET_assert (client->th != NULL);
966     }
967   return tsize;
968 }
969
970
971 /**
972  * Send the specified message to the specified client.  Since multiple
973  * messages may be pending for the same client at a time, this code
974  * makes sure that no message is lost.
975  *
976  * @param client client to transmit the message to
977  * @param msg the message to send
978  * @param may_drop can this message be dropped if the
979  *        message queue for this client is getting far too large?
980  */
981 static void
982 transmit_to_client (struct TransportClient *client,
983                     const struct GNUNET_MessageHeader *msg, int may_drop)
984 {
985   struct ClientMessageQueueEntry *q;
986   uint16_t msize;
987
988   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
989     {
990       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
991                   _
992                   ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
993                   client->message_count, MAX_PENDING);
994       /* TODO: call to statistics... */
995       return;
996     }
997   msize = ntohs (msg->size);
998   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
999   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
1000   memcpy (&q[1], msg, msize);
1001   GNUNET_CONTAINER_DLL_insert_after (client->message_queue_head,
1002                                      client->message_queue_tail,
1003                                      client->message_queue_tail,
1004                                      q);                                     
1005   client->message_count++;
1006   if (client->th == NULL)
1007     {
1008       client->th = GNUNET_SERVER_notify_transmit_ready (client->client,
1009                                                         msize,
1010                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1011                                                         &transmit_to_client_callback,
1012                                                         client);
1013       GNUNET_assert (client->th != NULL);
1014     }
1015 }
1016
1017
1018 /**
1019  * Transmit a 'SEND_OK' notification to the given client for the
1020  * given neighbour.
1021  *
1022  * @param client who to notify
1023  * @param n neighbour to notify about
1024  * @param result status code for the transmission request
1025  */
1026 static void
1027 transmit_send_ok (struct TransportClient *client,
1028                   struct NeighbourList *n,
1029                   int result)
1030 {
1031   struct SendOkMessage send_ok_msg;
1032
1033   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1034   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1035   send_ok_msg.success = htonl (result);
1036   send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1037   send_ok_msg.peer = n->id;
1038   transmit_to_client (client, &send_ok_msg.header, GNUNET_NO); 
1039 }
1040
1041
1042 /**
1043  * Function called by the GNUNET_TRANSPORT_TransmitFunction
1044  * upon "completion" of a send request.  This tells the API
1045  * that it is now legal to send another message to the given
1046  * peer.
1047  *
1048  * @param cls closure, identifies the entry on the
1049  *            message queue that was transmitted and the
1050  *            client responsible for queueing the message
1051  * @param target the peer receiving the message
1052  * @param result GNUNET_OK on success, if the transmission
1053  *           failed, we should not tell the client to transmit
1054  *           more messages
1055  */
1056 static void
1057 transmit_send_continuation (void *cls,
1058                             const struct GNUNET_PeerIdentity *target,
1059                             int result)
1060 {
1061   struct MessageQueue *mq = cls;
1062   struct NeighbourList *n;
1063   
1064   GNUNET_STATISTICS_update (stats,
1065                             gettext_noop ("# bytes pending with plugins"),
1066                             - (int64_t) mq->message_buf_size,
1067                             GNUNET_NO);
1068   if (result == GNUNET_OK)
1069     {
1070       GNUNET_STATISTICS_update (stats,
1071                                 gettext_noop ("# bytes successfully transmitted by plugins"),
1072                                 mq->message_buf_size,
1073                                 GNUNET_NO);      
1074     }
1075   else
1076     {
1077       GNUNET_STATISTICS_update (stats,
1078                                 gettext_noop ("# bytes with transmission failure by plugins"),
1079                                 mq->message_buf_size,
1080                                 GNUNET_NO);      
1081     }  
1082   n = find_neighbour(&mq->neighbour_id);
1083   GNUNET_assert (n != NULL);
1084   if (mq->specific_address != NULL)
1085     {
1086       if (result == GNUNET_OK)    
1087         {
1088           mq->specific_address->timeout =
1089             GNUNET_TIME_relative_to_absolute
1090             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1091           if (mq->specific_address->connected != GNUNET_YES)
1092             {
1093               GNUNET_STATISTICS_update (stats,
1094                                         gettext_noop ("# connected addresses"),
1095                                         1,
1096                                         GNUNET_NO);
1097               mq->specific_address->connected = GNUNET_YES;
1098             }
1099         }    
1100       else
1101         {
1102           if (mq->specific_address->connected != GNUNET_NO)
1103             {
1104               GNUNET_STATISTICS_update (stats,
1105                                         gettext_noop ("# connected addresses"),
1106                                         -1,
1107                                         GNUNET_NO);
1108               mq->specific_address->connected = GNUNET_NO;
1109             }
1110         }    
1111       if (! mq->internal_msg) 
1112         mq->specific_address->in_transmit = GNUNET_NO;
1113     }
1114   if (mq->client != NULL)
1115     transmit_send_ok (mq->client, n, result);
1116   GNUNET_free (mq);
1117   try_transmission_to_peer (n);
1118 }
1119
1120
1121 /**
1122  * Find an address in any of the available transports for
1123  * the given neighbour that would be good for message
1124  * transmission.  This is essentially the transport selection
1125  * routine.
1126  *
1127  * @param neighbour for whom to select an address
1128  * @return selected address, NULL if we have none
1129  */
1130 struct ForeignAddressList *
1131 find_ready_address(struct NeighbourList *neighbour)
1132 {
1133   struct ReadyList *head = neighbour->plugins;
1134   struct ForeignAddressList *addresses;
1135   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1136   struct ForeignAddressList *best_address;
1137
1138   best_address = NULL;
1139   while (head != NULL)
1140     {
1141       addresses = head->addresses;
1142       while (addresses != NULL)
1143         {
1144           if ( (addresses->timeout.value < now.value) && 
1145                (addresses->connected == GNUNET_YES) )
1146             {
1147 #if DEBUG_TRANSPORT
1148               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149                           "Marking long-time inactive connection to `%4s' as down.\n",
1150                           GNUNET_i2s (&neighbour->id));
1151 #endif
1152               GNUNET_STATISTICS_update (stats,
1153                                         gettext_noop ("# connected addresses"),
1154                                         -1,
1155                                         GNUNET_NO);
1156               addresses->connected = GNUNET_NO;
1157             }
1158           addresses = addresses->next;
1159         }
1160
1161       addresses = head->addresses;
1162       while (addresses != NULL)
1163         {
1164           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1165                       "Have address `%s' for peer `%4s' (status: %d, %d, %d, %u, %llums, %u)\n",
1166                       GNUNET_a2s (addresses->addr,
1167                                   addresses->addrlen),
1168                       GNUNET_i2s (&neighbour->id),
1169                       addresses->connected,
1170                       addresses->in_transmit,
1171                       addresses->validated,
1172                       addresses->connect_attempts,
1173                       (unsigned long long) addresses->timeout.value,
1174                       (unsigned int) addresses->distance);
1175           if ( ( (best_address == NULL) || 
1176                  (addresses->connected == GNUNET_YES) ||
1177                  (best_address->connected == GNUNET_NO) ) &&
1178                (addresses->in_transmit == GNUNET_NO) &&
1179                ( (best_address == NULL) || 
1180                  (addresses->latency.value < best_address->latency.value)) )
1181             best_address = addresses;            
1182           /* FIXME: also give lower-latency addresses that are not
1183              connected a chance some times... */
1184           addresses = addresses->next;
1185         }
1186       head = head->next;
1187     }
1188   if (best_address != NULL)
1189     {
1190 #if DEBUG_TRANSPORT
1191       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192                   "Best address found has latency of %llu ms.\n",
1193                   best_address->latency.value);
1194 #endif
1195     }
1196   else
1197     {
1198       GNUNET_STATISTICS_update (stats,
1199                                 gettext_noop ("# transmission attempts failed (no address)"),
1200                                 1,
1201                                 GNUNET_NO);
1202     }
1203   return best_address;
1204
1205 }
1206
1207
1208 /**
1209  * We should re-try transmitting to the given peer,
1210  * hopefully we've learned something in the meantime.
1211  */
1212 static void
1213 retry_transmission_task (void *cls,
1214                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1215 {
1216   struct NeighbourList *n = cls;
1217
1218   n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1219   try_transmission_to_peer (n);
1220 }
1221
1222
1223 /**
1224  * Check the ready list for the given neighbour and if a plugin is
1225  * ready for transmission (and if we have a message), do so!
1226  *
1227  * @param neighbour target peer for which to transmit
1228  */
1229 static void
1230 try_transmission_to_peer (struct NeighbourList *neighbour)
1231 {
1232   struct ReadyList *rl;
1233   struct MessageQueue *mq;
1234   struct GNUNET_TIME_Relative timeout;
1235   ssize_t ret;
1236   int force_address;
1237
1238   if (neighbour->messages_head == NULL)
1239     {
1240       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1241                   "Transmission queue for `%4s' is empty\n",
1242                   GNUNET_i2s (&neighbour->id));
1243       return;                     /* nothing to do */
1244     }
1245   rl = NULL;
1246   mq = neighbour->messages_head;
1247   /* FIXME: support bi-directional use of TCP */
1248   force_address = GNUNET_YES;
1249   if (mq->specific_address == NULL)
1250     {
1251       mq->specific_address = find_ready_address(neighbour); 
1252       GNUNET_STATISTICS_update (stats,
1253                                 gettext_noop ("# transport selected peer address freely"),
1254                                 1,
1255                                 GNUNET_NO); 
1256       force_address = GNUNET_NO;
1257     }
1258   if (mq->specific_address == NULL)
1259     {
1260       GNUNET_STATISTICS_update (stats,
1261                                 gettext_noop ("# transport failed to selected peer address"),
1262                                 1,
1263                                 GNUNET_NO); 
1264       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1265       if (timeout.value == 0)
1266         {
1267 #if DEBUG_TRANSPORT
1268           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269                       "No destination address available to transmit message of size %u to peer `%4s'\n",
1270                       mq->message_buf_size,
1271                       GNUNET_i2s (&mq->neighbour_id));
1272 #endif
1273           GNUNET_STATISTICS_update (stats,
1274                                     gettext_noop ("# bytes in message queue for other peers"),
1275                                     - (int64_t) mq->message_buf_size,
1276                                     GNUNET_NO);
1277           GNUNET_STATISTICS_update (stats,
1278                                     gettext_noop ("# bytes discarded (no destination address available)"),
1279                                     mq->message_buf_size,
1280                                     GNUNET_NO);      
1281           if (mq->client != NULL)
1282             transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1283           GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1284                                        neighbour->messages_tail,
1285                                        mq);
1286           GNUNET_free (mq);
1287           return;               /* nobody ready */ 
1288         }
1289       GNUNET_STATISTICS_update (stats,
1290                                 gettext_noop ("# message delivery deferred (no address)"),
1291                                 1,
1292                                 GNUNET_NO);
1293       if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1294         GNUNET_SCHEDULER_cancel (sched,
1295                                  neighbour->retry_task);
1296       neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1297                                                             timeout,
1298                                                             &retry_transmission_task,
1299                                                             neighbour);
1300 #if DEBUG_TRANSPORT
1301       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302                   "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1303                   mq->message_buf_size,
1304                   GNUNET_i2s (&mq->neighbour_id),
1305                   timeout.value);
1306 #endif
1307       /* FIXME: might want to trigger peerinfo lookup here
1308          (unless that's already pending...) */
1309       return;    
1310     }
1311   GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1312                                neighbour->messages_tail,
1313                                mq);
1314   if (mq->specific_address->connected == GNUNET_NO)
1315     mq->specific_address->connect_attempts++;
1316   rl = mq->specific_address->ready_list;
1317   mq->plugin = rl->plugin;
1318   if (!mq->internal_msg)
1319     mq->specific_address->in_transmit = GNUNET_YES;
1320 #if DEBUG_TRANSPORT
1321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1322               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1323               mq->message_buf_size,
1324               GNUNET_i2s (&neighbour->id), 
1325               GNUNET_a2s (mq->specific_address->addr,
1326                           mq->specific_address->addrlen),
1327               rl->plugin->short_name);
1328 #endif
1329   GNUNET_STATISTICS_update (stats,
1330                             gettext_noop ("# bytes in message queue for other peers"),
1331                             - (int64_t) mq->message_buf_size,
1332                             GNUNET_NO);
1333   GNUNET_STATISTICS_update (stats,
1334                             gettext_noop ("# bytes pending with plugins"),
1335                             mq->message_buf_size,
1336                             GNUNET_NO);
1337   ret = rl->plugin->api->send (rl->plugin->api->cls,
1338                                &mq->neighbour_id,
1339                                mq->message_buf,
1340                                mq->message_buf_size,
1341                                mq->priority,
1342                                GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1343                                mq->specific_address->addr,
1344                                mq->specific_address->addrlen,
1345                                force_address,
1346                                &transmit_send_continuation, mq);
1347   if (ret == -1)
1348     {
1349       /* failure, but 'send' would not call continuation in this case,
1350          so we need to do it here! */
1351       transmit_send_continuation (mq, 
1352                                   &mq->neighbour_id,
1353                                   GNUNET_SYSERR);
1354     }
1355 }
1356
1357
1358 /**
1359  * Send the specified message to the specified peer.
1360  *
1361  * @param client source of the transmission request (can be NULL)
1362  * @param peer_address ForeignAddressList where we should send this message
1363  * @param priority how important is the message
1364  * @param timeout how long do we have to transmit?
1365  * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1366  * @param message_buf_size total size of all messages in message_buf
1367  * @param is_internal is this an internal message; these are pre-pended and
1368  *                    also do not count for plugins being "ready" to transmit
1369  * @param neighbour handle to the neighbour for transmission
1370  */
1371 static void
1372 transmit_to_peer (struct TransportClient *client,
1373                   struct ForeignAddressList *peer_address,
1374                   unsigned int priority,
1375                   struct GNUNET_TIME_Relative timeout,
1376                   const char *message_buf,
1377                   size_t message_buf_size,
1378                   int is_internal, struct NeighbourList *neighbour)
1379 {
1380   struct MessageQueue *mq;
1381
1382 #if EXTRA_CHECKS
1383   if (client != NULL)
1384     {
1385       /* check for duplicate submission */
1386       mq = neighbour->messages_head;
1387       while (NULL != mq)
1388         {
1389           if (mq->client == client)
1390             {
1391               /* client transmitted to same peer twice
1392                  before getting SEND_OK! */
1393               GNUNET_break (0);
1394               return;
1395             }
1396           mq = mq->next;
1397         }
1398     }
1399 #endif
1400   GNUNET_STATISTICS_update (stats,
1401                             gettext_noop ("# bytes in message queue for other peers"),
1402                             message_buf_size,
1403                             GNUNET_NO);
1404   mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1405   mq->specific_address = peer_address;
1406   mq->client = client;
1407   memcpy (&mq[1], message_buf, message_buf_size);
1408   mq->message_buf = (const char*) &mq[1];
1409   mq->message_buf_size = message_buf_size;
1410   memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1411   mq->internal_msg = is_internal;
1412   mq->priority = priority;
1413   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1414   if (is_internal)    
1415     GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1416                                  neighbour->messages_tail,
1417                                  mq);
1418   else
1419     GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1420                                        neighbour->messages_tail,
1421                                        neighbour->messages_tail,
1422                                        mq);
1423   try_transmission_to_peer (neighbour);
1424 }
1425
1426
1427 /**
1428  * FIXME: document.
1429  */
1430 struct GeneratorContext
1431 {
1432   struct TransportPlugin *plug_pos;
1433   struct OwnAddressList *addr_pos;
1434   struct GNUNET_TIME_Absolute expiration;
1435 };
1436
1437
1438 /**
1439  * FIXME: document.
1440  */
1441 static size_t
1442 address_generator (void *cls, size_t max, void *buf)
1443 {
1444   struct GeneratorContext *gc = cls;
1445   size_t ret;
1446
1447   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1448     {
1449       gc->plug_pos = gc->plug_pos->next;
1450       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1451     }
1452   if (NULL == gc->plug_pos)
1453     {
1454
1455       return 0;
1456     }
1457   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1458                                   gc->expiration,
1459                                   gc->addr_pos->addr,
1460                                   gc->addr_pos->addrlen, buf, max);
1461   gc->addr_pos = gc->addr_pos->next;
1462   return ret;
1463 }
1464
1465
1466 /**
1467  * Construct our HELLO message from all of the addresses of
1468  * all of the transports.
1469  */
1470 static void
1471 refresh_hello ()
1472 {
1473   struct GNUNET_HELLO_Message *hello;
1474   struct TransportClient *cpos;
1475   struct NeighbourList *npos;
1476   struct GeneratorContext gc;
1477
1478   gc.plug_pos = plugins;
1479   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1480   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1481   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1482 #if DEBUG_TRANSPORT
1483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1484               "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1485 #endif
1486   GNUNET_STATISTICS_update (stats,
1487                             gettext_noop ("# refreshed my HELLO"),
1488                             1,
1489                             GNUNET_NO);
1490   cpos = clients;
1491   while (cpos != NULL)
1492     {
1493       transmit_to_client (cpos,
1494                           (const struct GNUNET_MessageHeader *) hello,
1495                           GNUNET_NO);
1496       cpos = cpos->next;
1497     }
1498
1499   GNUNET_free_non_null (our_hello);
1500   our_hello = hello;
1501   our_hello_version++;
1502   GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1503   npos = neighbours;
1504   while (npos != NULL)
1505     {
1506 #if DEBUG_TRANSPORT
1507       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1508                   "Transmitting updated `%s' to neighbour `%4s'\n",
1509                   "HELLO", GNUNET_i2s (&npos->id));
1510 #endif
1511       GNUNET_STATISTICS_update (stats,
1512                                 gettext_noop ("# transmitted my HELLO to other peers"),
1513                                 1,
1514                                 GNUNET_NO);
1515       transmit_to_peer (NULL, NULL, 0,
1516                         HELLO_ADDRESS_EXPIRATION,
1517                         (const char *) our_hello, 
1518                         GNUNET_HELLO_size(our_hello),
1519                         GNUNET_NO, npos);
1520       npos = npos->next;
1521     }
1522 }
1523
1524
1525 /**
1526  * Task used to clean up expired addresses for a plugin.
1527  *
1528  * @param cls closure
1529  * @param tc context
1530  */
1531 static void
1532 expire_address_task (void *cls,
1533                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1534
1535
1536 /**
1537  * Update the list of addresses for this plugin,
1538  * expiring those that are past their expiration date.
1539  *
1540  * @param plugin addresses of which plugin should be recomputed?
1541  * @param fresh set to GNUNET_YES if a new address was added
1542  *        and we need to regenerate the HELLO even if nobody
1543  *        expired
1544  */
1545 static void
1546 update_addresses (struct TransportPlugin *plugin, int fresh)
1547 {
1548   struct GNUNET_TIME_Relative min_remaining;
1549   struct GNUNET_TIME_Relative remaining;
1550   struct GNUNET_TIME_Absolute now;
1551   struct OwnAddressList *pos;
1552   struct OwnAddressList *prev;
1553   struct OwnAddressList *next;
1554   int expired;
1555
1556   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1557     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1558   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1559   now = GNUNET_TIME_absolute_get ();
1560   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1561   expired = GNUNET_NO;
1562   prev = NULL;
1563   pos = plugin->addresses;
1564   while (pos != NULL)
1565     {
1566       next = pos->next;
1567       if (pos->expires.value < now.value)
1568         {
1569           expired = GNUNET_YES;
1570           if (prev == NULL)
1571             plugin->addresses = pos->next;
1572           else
1573             prev->next = pos->next;
1574
1575           
1576           GNUNET_free (pos);
1577         }
1578       else
1579         {
1580           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1581           if (remaining.value < min_remaining.value)
1582             min_remaining = remaining;
1583           prev = pos;
1584         }
1585       pos = next;
1586     }
1587
1588   if (expired || fresh)
1589     refresh_hello ();
1590   if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1591     plugin->address_update_task
1592       = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1593                                       min_remaining,
1594                                       &expire_address_task, plugin);
1595
1596 }
1597
1598
1599 /**
1600  * Task used to clean up expired addresses for a plugin.
1601  *
1602  * @param cls closure
1603  * @param tc context
1604  */
1605 static void
1606 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1607 {
1608   struct TransportPlugin *plugin = cls;
1609   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1610   update_addresses (plugin, GNUNET_NO);
1611 }
1612
1613
1614 /**
1615  * Function that must be called by each plugin to notify the
1616  * transport service about the addresses under which the transport
1617  * provided by the plugin can be reached.
1618  *
1619  * @param cls closure
1620  * @param name name of the transport that generated the address
1621  * @param addr one of the addresses of the host, NULL for the last address
1622  *        the specific address format depends on the transport
1623  * @param addrlen length of the address
1624  * @param expires when should this address automatically expire?
1625  */
1626 static void
1627 plugin_env_notify_address (void *cls,
1628                            const char *name,
1629                            const void *addr,
1630                            size_t addrlen,
1631                            struct GNUNET_TIME_Relative expires)
1632 {
1633   struct TransportPlugin *p = cls;
1634   struct OwnAddressList *al;
1635   struct GNUNET_TIME_Absolute abex;
1636
1637   abex = GNUNET_TIME_relative_to_absolute (expires);
1638   GNUNET_assert (p == find_transport (name));
1639
1640   al = p->addresses;
1641   while (al != NULL)
1642     {
1643       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1644         {
1645           if (al->expires.value < abex.value)
1646             al->expires = abex;
1647           return;
1648         }
1649       al = al->next;
1650     }
1651
1652   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1653   al->addr = &al[1];
1654   al->next = p->addresses;
1655   p->addresses = al;
1656   al->expires = abex;
1657   al->addrlen = addrlen;
1658   memcpy (&al[1], addr, addrlen);
1659   update_addresses (p, GNUNET_YES);
1660 }
1661
1662
1663 /**
1664  * Notify all of our clients about a peer connecting.
1665  */
1666 static void
1667 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1668                         struct GNUNET_TIME_Relative latency,
1669                         uint32_t distance)
1670 {
1671   struct ConnectInfoMessage cim;
1672   struct TransportClient *cpos;
1673
1674 #if DEBUG_TRANSPORT
1675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676               "Notifying clients about connection from `%s'\n",
1677               GNUNET_i2s (peer));
1678 #endif
1679   GNUNET_STATISTICS_update (stats,
1680                             gettext_noop ("# peers connected"),
1681                             1,
1682                             GNUNET_NO);
1683   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1684   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1685   cim.distance = htonl (distance);
1686   cim.latency = GNUNET_TIME_relative_hton (latency);
1687   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1688   cpos = clients;
1689   while (cpos != NULL)
1690     {
1691       transmit_to_client (cpos, &cim.header, GNUNET_NO);
1692       cpos = cpos->next;
1693     }
1694 }
1695
1696
1697 /**
1698  * Notify all of our clients about a peer disconnecting.
1699  */
1700 static void
1701 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1702 {
1703   struct DisconnectInfoMessage dim;
1704   struct TransportClient *cpos;
1705
1706 #if DEBUG_TRANSPORT
1707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1708               "Notifying clients about lost connection to `%s'\n",
1709               GNUNET_i2s (peer));
1710 #endif
1711   GNUNET_STATISTICS_update (stats,
1712                             gettext_noop ("# peers connected"),
1713                             -1,
1714                             GNUNET_NO);
1715   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1716   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1717   dim.reserved = htonl (0);
1718   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1719   cpos = clients;
1720   while (cpos != NULL)
1721     {
1722       transmit_to_client (cpos, &dim.header, GNUNET_NO);
1723       cpos = cpos->next;
1724     }
1725 }
1726
1727
1728 /**
1729  * Find a ForeignAddressList entry for the given neighbour
1730  * that matches the given address and transport.
1731  *
1732  * @param neighbour which peer we care about
1733  * @param tname name of the transport plugin
1734  * @param addr binary address
1735  * @param addrlen length of addr
1736  * @return NULL if no such entry exists
1737  */
1738 static struct ForeignAddressList *
1739 find_peer_address(struct NeighbourList *neighbour,
1740                   const char *tname,
1741                   const char *addr,
1742                   size_t addrlen)
1743 {
1744   struct ReadyList *head;
1745   struct ForeignAddressList *address_head;
1746
1747   head = neighbour->plugins;
1748   while (head != NULL)
1749     {
1750       if (0 == strcmp (tname, head->plugin->short_name))
1751         break;
1752       head = head->next;
1753     }
1754   if (head == NULL)
1755     return NULL;
1756
1757   address_head = head->addresses;
1758   while ( (address_head != NULL) &&
1759           ( (address_head->addrlen != addrlen) ||
1760             (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1761     address_head = address_head->next;
1762   return address_head;
1763 }
1764
1765
1766 /**
1767  * Get the peer address struct for the given neighbour and
1768  * address.  If it doesn't yet exist, create it.
1769  *
1770  * @param neighbour which peer we care about
1771  * @param tname name of the transport plugin
1772  * @param addr binary address
1773  * @param addrlen length of addr
1774  * @return NULL if we do not have a transport plugin for 'tname'
1775  */
1776 static struct ForeignAddressList *
1777 add_peer_address (struct NeighbourList *neighbour,
1778                   const char *tname,
1779                   const char *addr, 
1780                   size_t addrlen)
1781 {
1782   struct ReadyList *head;
1783   struct ForeignAddressList *ret;
1784
1785   ret = find_peer_address (neighbour, tname, addr, addrlen);
1786   if (ret != NULL)
1787     return ret;
1788   head = neighbour->plugins;
1789   while (head != NULL)
1790     {
1791       if (0 == strcmp (tname, head->plugin->short_name))
1792         break;
1793       head = head->next;
1794     }
1795   if (head == NULL)
1796     return NULL;
1797   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1798   ret->addr = (const char*) &ret[1];
1799   memcpy (&ret[1], addr, addrlen);
1800   ret->addrlen = addrlen;
1801   ret->expires = GNUNET_TIME_relative_to_absolute
1802     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1803   ret->latency = GNUNET_TIME_relative_get_forever();
1804   ret->distance = -1;
1805   ret->timeout = GNUNET_TIME_relative_to_absolute
1806     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); 
1807   ret->ready_list = head;
1808   ret->next = head->addresses;
1809   head->addresses = ret;
1810   return ret;
1811 }
1812
1813
1814 /**
1815  * Closure for 'add_validated_address'.
1816  */
1817 struct AddValidatedAddressContext
1818 {
1819   /**
1820    * Entry that has been validated.
1821    */
1822   const struct ValidationEntry *ve;
1823
1824   /**
1825    * Flag set after we have added the address so
1826    * that we terminate the iteration next time.
1827    */
1828   int done;
1829 };
1830
1831
1832 /**
1833  * Callback function used to fill a buffer of max bytes with a list of
1834  * addresses in the format used by HELLOs.  Should use
1835  * "GNUNET_HELLO_add_address" as a helper function.
1836  *
1837  * @param cls the 'struct AddValidatedAddressContext' with the validated address
1838  * @param max maximum number of bytes that can be written to buf
1839  * @param buf where to write the address information
1840  * @return number of bytes written, 0 to signal the
1841  *         end of the iteration.
1842  */
1843 static size_t
1844 add_validated_address (void *cls,
1845                        size_t max, void *buf)
1846 {
1847   struct AddValidatedAddressContext *avac = cls;
1848   const struct ValidationEntry *ve = avac->ve;
1849
1850   if (GNUNET_YES == avac->done)
1851     return 0;
1852   avac->done = GNUNET_YES;
1853   return GNUNET_HELLO_add_address (ve->transport_name,
1854                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1855                                    ve->addr,
1856                                    ve->addrlen,
1857                                    buf,
1858                                    max);
1859 }
1860
1861
1862
1863 /**
1864  * Closure for 'check_address_exists'.
1865  */
1866 struct CheckAddressExistsClosure
1867 {
1868   /**
1869    * Address to check for.
1870    */
1871   const void *addr;
1872
1873   /**
1874    * Name of the transport.
1875    */
1876   const char *tname;
1877
1878   /**
1879    * Length of addr.
1880    */
1881   size_t addrlen;
1882
1883   /**
1884    * Set to GNUNET_YES if the address exists.
1885    */
1886   int exists;
1887 };
1888
1889
1890 /**
1891  * Iterator over hash map entries.  Checks if the given
1892  * validation entry is for the same address as what is given
1893  * in the closure.
1894  *
1895  * @param cls the 'struct CheckAddressExistsClosure*'
1896  * @param key current key code (ignored)
1897  * @param value value in the hash map ('struct ValidationEntry')
1898  * @return GNUNET_YES if we should continue to
1899  *         iterate (mismatch), GNUNET_NO if not (entry matched)
1900  */
1901 static int
1902 check_address_exists (void *cls,
1903                       const GNUNET_HashCode * key,
1904                       void *value)
1905 {
1906   struct CheckAddressExistsClosure *caec = cls;
1907   struct ValidationEntry *ve = value;
1908   if ( (0 == strcmp (caec->tname,
1909                      ve->transport_name)) &&
1910        (caec->addrlen == ve->addrlen) &&
1911        (0 == memcmp (caec->addr,
1912                      ve->addr,
1913                      caec->addrlen)) )
1914     {
1915       caec->exists = GNUNET_YES;
1916       return GNUNET_NO;
1917     }
1918   return GNUNET_YES;
1919 }
1920
1921
1922 /**
1923  * HELLO validation cleanup task (validation failed).
1924  *
1925  * @param cls the 'struct ValidationEntry' that failed
1926  * @param tc scheduler context (unused)
1927  */
1928 static void
1929 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1930 {
1931   struct ValidationEntry *va = cls;
1932   struct GNUNET_PeerIdentity pid;
1933
1934   GNUNET_STATISTICS_update (stats,
1935                             gettext_noop ("# address validation timeouts"),
1936                             1,
1937                             GNUNET_NO);
1938   GNUNET_CRYPTO_hash (&va->publicKey,
1939                       sizeof (struct
1940                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1941                       &pid.hashPubKey);
1942   GNUNET_CONTAINER_multihashmap_remove (validation_map,
1943                                         &pid.hashPubKey,
1944                                         va);
1945   GNUNET_free (va->transport_name);
1946   GNUNET_free (va);
1947 }
1948
1949
1950 static void
1951 neighbour_timeout_task (void *cls,
1952                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1953 {
1954   struct NeighbourList *n = cls;
1955
1956 #if DEBUG_TRANSPORT
1957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1958               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1959 #endif
1960   GNUNET_STATISTICS_update (stats,
1961                             gettext_noop ("# disconnects due to timeout"),
1962                             1,
1963                             GNUNET_NO);
1964   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1965   disconnect_neighbour (n, GNUNET_NO);
1966 }
1967
1968
1969 /**
1970  * Schedule the job that will cause us to send a PING to the
1971  * foreign address to evaluate its validity and latency.
1972  *
1973  * @param fal address to PING
1974  */
1975 static void
1976 schedule_next_ping (struct ForeignAddressList *fal);
1977
1978
1979 /**
1980  * Add the given address to the list of foreign addresses
1981  * available for the given peer (check for duplicates).
1982  *
1983  * @param cls the respective 'struct NeighbourList' to update
1984  * @param tname name of the transport
1985  * @param expiration expiration time
1986  * @param addr the address
1987  * @param addrlen length of the address
1988  * @return GNUNET_OK (always)
1989  */
1990 static int
1991 add_to_foreign_address_list (void *cls,
1992                              const char *tname,
1993                              struct GNUNET_TIME_Absolute expiration,
1994                              const void *addr, size_t addrlen)
1995 {
1996   struct NeighbourList *n = cls;
1997   struct ForeignAddressList *fal;
1998   int try;
1999
2000   GNUNET_STATISTICS_update (stats,
2001                             gettext_noop ("# valid peer addresses returned by peerinfo"),
2002                             1,
2003                             GNUNET_NO);      
2004   try = GNUNET_NO;
2005   fal = find_peer_address (n, tname, addr, addrlen);
2006   if (fal == NULL)
2007     {
2008 #if DEBUG_TRANSPORT
2009       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010                   "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2011                   GNUNET_a2s (addr, addrlen),
2012                   tname,
2013                   GNUNET_i2s (&n->id),
2014                   expiration.value);
2015 #endif
2016       fal = add_peer_address (n, tname, addr, addrlen);
2017       if (fal == NULL)
2018         {
2019           GNUNET_STATISTICS_update (stats,
2020                                     gettext_noop ("# previously validated addresses lacking transport"),
2021                                     1,
2022                                     GNUNET_NO); 
2023         }
2024       else
2025         {
2026           fal->expires = GNUNET_TIME_absolute_max (expiration,
2027                                                    fal->expires);
2028           schedule_next_ping (fal);
2029         }
2030       try = GNUNET_YES;
2031     }
2032   else
2033     {
2034       fal->expires = GNUNET_TIME_absolute_max (expiration,
2035                                                fal->expires);
2036     }
2037   if (fal == NULL)
2038     {
2039       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040                   "Failed to add new address for `%4s'\n",
2041                   GNUNET_i2s (&n->id));
2042       return GNUNET_OK;
2043     }
2044   if (fal->validated == GNUNET_NO)
2045     {
2046       fal->validated = GNUNET_YES;  
2047       GNUNET_STATISTICS_update (stats,
2048                                 gettext_noop ("# peer addresses considered valid"),
2049                                 1,
2050                                 GNUNET_NO);      
2051     }
2052   if (try == GNUNET_YES)
2053     {
2054       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055                   "Have new addresses, will try to trigger transmissions.\n");
2056       try_transmission_to_peer (n);
2057     }
2058   return GNUNET_OK;
2059 }
2060
2061
2062 /**
2063  * Add addresses in validated HELLO "h" to the set of addresses
2064  * we have for this peer.
2065  *
2066  * @param cls closure ('struct NeighbourList*')
2067  * @param peer id of the peer, NULL for last call
2068  * @param h hello message for the peer (can be NULL)
2069  * @param trust amount of trust we have in the peer (not used)
2070  */
2071 static void
2072 add_hello_for_peer (void *cls,
2073                     const struct GNUNET_PeerIdentity *peer,
2074                     const struct GNUNET_HELLO_Message *h, 
2075                     uint32_t trust)
2076 {
2077   struct NeighbourList *n = cls;
2078
2079   if (peer == NULL)
2080     {
2081       n->piter = NULL;
2082       return;
2083     } 
2084   if (h == NULL)
2085     return; /* no HELLO available */
2086 #if DEBUG_TRANSPORT
2087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2088               "Peerinfo had `%s' message for peer `%4s', adding existing addresses.\n",
2089               "HELLO",
2090               GNUNET_i2s (peer));
2091 #endif
2092   if (GNUNET_YES != n->public_key_valid)
2093     {
2094       GNUNET_HELLO_get_key (h, &n->publicKey);
2095       n->public_key_valid = GNUNET_YES;
2096     }
2097   GNUNET_HELLO_iterate_addresses (h,
2098                                   GNUNET_NO,
2099                                   &add_to_foreign_address_list,
2100                                   n);
2101 }
2102
2103
2104 /**
2105  * Create a fresh entry in our neighbour list for the given peer.
2106  * Will try to transmit our current HELLO to the new neighbour.
2107  *
2108  * @param peer the peer for which we create the entry
2109  * @return the new neighbour list entry
2110  */
2111 static struct NeighbourList *
2112 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
2113 {
2114   struct NeighbourList *n;
2115   struct TransportPlugin *tp;
2116   struct ReadyList *rl;
2117
2118   GNUNET_assert (our_hello != NULL);
2119   GNUNET_STATISTICS_update (stats,
2120                             gettext_noop ("# active neighbours"),
2121                             1,
2122                             GNUNET_NO);
2123   n = GNUNET_malloc (sizeof (struct NeighbourList));
2124   n->next = neighbours;
2125   neighbours = n;
2126   n->id = *peer;
2127   n->peer_timeout =
2128     GNUNET_TIME_relative_to_absolute
2129     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2130   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
2131                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
2132                                  MAX_BANDWIDTH_CARRY_S);
2133   tp = plugins;
2134   while (tp != NULL)
2135     {
2136       if (tp->api->send != NULL)
2137         {
2138           rl = GNUNET_malloc (sizeof (struct ReadyList));
2139           rl->neighbour = n;
2140           rl->next = n->plugins;
2141           n->plugins = rl;
2142           rl->plugin = tp;
2143           rl->addresses = NULL;
2144         }
2145       tp = tp->next;
2146     }
2147   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
2148   n->distance = -1;
2149   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2150                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2151                                                   &neighbour_timeout_task, n);
2152   n->piter = GNUNET_PEERINFO_iterate (cfg, sched, peer,
2153                                       0, GNUNET_TIME_UNIT_FOREVER_REL,
2154                                       &add_hello_for_peer, n);
2155   transmit_to_peer (NULL, NULL, 0,
2156                     HELLO_ADDRESS_EXPIRATION,
2157                     (const char *) our_hello, GNUNET_HELLO_size(our_hello),
2158                     GNUNET_NO, n);
2159   return n;
2160 }
2161
2162
2163 /**
2164  * Send periodic PING messages to a give foreign address.
2165  *
2166  * @param cls our 'struct PeriodicValidationContext*'
2167  * @param tc task context
2168  */
2169 static void 
2170 send_periodic_ping (void *cls, 
2171                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2172 {
2173   struct ForeignAddressList *peer_address = cls;
2174   struct TransportPlugin *tp;
2175   struct ValidationEntry *va;
2176   struct NeighbourList *neighbour;
2177   struct TransportPingMessage ping;
2178   struct CheckAddressExistsClosure caec;
2179   char * message_buf;
2180   uint16_t hello_size;
2181   size_t tsize;
2182
2183   peer_address->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2184   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2185     return; 
2186   tp = peer_address->ready_list->plugin;
2187   neighbour = peer_address->ready_list->neighbour;
2188   if (GNUNET_YES != neighbour->public_key_valid)
2189     {
2190       /* no public key yet, try again later */
2191       schedule_next_ping (peer_address);     
2192       return;
2193     }
2194   caec.addr = peer_address->addr;
2195   caec.addrlen = peer_address->addrlen;
2196   caec.tname = tp->short_name;
2197   caec.exists = GNUNET_NO;
2198   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2199                                          &check_address_exists,
2200                                          &caec);
2201   if (caec.exists == GNUNET_YES)
2202     {
2203       /* During validation attempts we will likely trigger the other
2204          peer trying to validate our address which in turn will cause
2205          it to send us its HELLO, so we expect to hit this case rather
2206          frequently.  Only print something if we are very verbose. */
2207 #if DEBUG_TRANSPORT > 1
2208       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209                   "Some validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2210                   GNUNET_a2s (peer_address->addr,
2211                               peer_address->addrlen),
2212                   tp->short_name,
2213                   GNUNET_i2s (&neighbour->id));
2214 #endif
2215       schedule_next_ping (peer_address);     
2216       return;
2217     }
2218   va = GNUNET_malloc (sizeof (struct ValidationEntry) + peer_address->addrlen);
2219   va->transport_name = GNUNET_strdup (tp->short_name);
2220   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2221                                             (unsigned int) -1);
2222   va->send_time = GNUNET_TIME_absolute_get();
2223   va->addr = (const void*) &va[1];
2224   memcpy (&va[1], peer_address->addr, peer_address->addrlen);
2225   va->addrlen = peer_address->addrlen;
2226
2227   memcpy(&va->publicKey,
2228          &neighbour->publicKey, 
2229          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2230
2231   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2232                                                    HELLO_VERIFICATION_TIMEOUT,
2233                                                    &timeout_hello_validation,
2234                                                    va);
2235   GNUNET_CONTAINER_multihashmap_put (validation_map,
2236                                      &neighbour->id.hashPubKey,
2237                                      va,
2238                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2239   hello_size = GNUNET_HELLO_size(our_hello);
2240   tsize = sizeof(struct TransportPingMessage) + hello_size;
2241   message_buf = GNUNET_malloc(tsize);
2242   ping.challenge = htonl(va->challenge);
2243   ping.header.size = htons(sizeof(struct TransportPingMessage));
2244   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2245   memcpy(&ping.target, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
2246   memcpy(message_buf, our_hello, hello_size);
2247   memcpy(&message_buf[hello_size],
2248          &ping,
2249          sizeof(struct TransportPingMessage));
2250 #if DEBUG_TRANSPORT_REVALIDATION
2251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2252               "Performing re-validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2253               GNUNET_a2s (peer_address->addr,
2254                           peer_address->addrlen),
2255               tp->short_name,
2256               GNUNET_i2s (&neighbour->id),
2257               "HELLO", hello_size,
2258               "PING", sizeof (struct TransportPingMessage));
2259 #endif
2260   GNUNET_STATISTICS_update (stats,
2261                             gettext_noop ("# PING messages sent for re-validation"),
2262                             1,
2263                             GNUNET_NO);
2264   transmit_to_peer (NULL, peer_address,
2265                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2266                     HELLO_VERIFICATION_TIMEOUT,
2267                     message_buf, tsize,
2268                     GNUNET_YES, neighbour);
2269   GNUNET_free(message_buf);
2270   schedule_next_ping (peer_address);
2271 }
2272
2273
2274 /**
2275  * Schedule the job that will cause us to send a PING to the
2276  * foreign address to evaluate its validity and latency.
2277  *
2278  * @param fal address to PING
2279  */
2280 static void
2281 schedule_next_ping (struct ForeignAddressList *fal)
2282 {
2283   struct GNUNET_TIME_Relative delay;
2284
2285   if (fal->revalidate_task != GNUNET_SCHEDULER_NO_TASK)
2286     return;
2287   delay = GNUNET_TIME_absolute_get_remaining (fal->expires);
2288   delay.value /= 2; /* do before expiration */
2289   delay = GNUNET_TIME_relative_min (delay,
2290                                     LATENCY_EVALUATION_MAX_DELAY);
2291   if (GNUNET_YES != fal->estimated)
2292     {
2293       delay = GNUNET_TIME_UNIT_ZERO;
2294       fal->estimated = GNUNET_YES;
2295     }                               
2296   if (GNUNET_YES == fal->connected)
2297     {
2298       delay = GNUNET_TIME_relative_min (delay,
2299                                         CONNECTED_LATENCY_EVALUATION_MAX_DELAY);
2300     }  
2301   /* FIXME: also adjust delay based on how close the last
2302      observed latency is to the latency of the best alternative */
2303   /* bound how fast we can go */
2304   delay = GNUNET_TIME_relative_max (delay,
2305                                     GNUNET_TIME_UNIT_SECONDS);
2306   /* randomize a bit (to avoid doing all at the same time) */
2307   delay.value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000);
2308   fal->revalidate_task = GNUNET_SCHEDULER_add_delayed(sched, 
2309                                                       delay,
2310                                                       &send_periodic_ping, 
2311                                                       fal);
2312 }
2313
2314
2315 /**
2316  * Iterator over hash map entries.  Checks if the given validation
2317  * entry is for the same challenge as what is given in the PONG.
2318  *
2319  * @param cls the 'struct TransportPongMessage*'
2320  * @param key peer identity
2321  * @param value value in the hash map ('struct ValidationEntry')
2322  * @return GNUNET_YES if we should continue to
2323  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2324  */
2325 static int
2326 check_pending_validation (void *cls,
2327                           const GNUNET_HashCode * key,
2328                           void *value)
2329 {
2330   const struct TransportPongMessage *pong = cls;
2331   struct ValidationEntry *ve = value;
2332   struct AddValidatedAddressContext avac;
2333   unsigned int challenge = ntohl(pong->challenge);
2334   struct GNUNET_HELLO_Message *hello;
2335   struct GNUNET_PeerIdentity target;
2336   struct NeighbourList *n;
2337   struct ForeignAddressList *fal;
2338
2339   if (ve->challenge != challenge)
2340     return GNUNET_YES;
2341
2342 #if DEBUG_TRANSPORT
2343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344               "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
2345               GNUNET_h2s (key),
2346               GNUNET_a2s ((const struct sockaddr *) ve->addr,
2347                           ve->addrlen),
2348               ve->transport_name);
2349 #endif
2350   GNUNET_STATISTICS_update (stats,
2351                             gettext_noop ("# address validation successes"),
2352                             1,
2353                             GNUNET_NO);
2354   /* create the updated HELLO */
2355   GNUNET_CRYPTO_hash (&ve->publicKey,
2356                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2357                       &target.hashPubKey);
2358   avac.done = GNUNET_NO;
2359   avac.ve = ve;
2360   hello = GNUNET_HELLO_create (&ve->publicKey,
2361                                &add_validated_address,
2362                                &avac);
2363   GNUNET_PEERINFO_add_peer (cfg, sched,
2364                             &target,
2365                             hello);
2366   GNUNET_free (hello);
2367   n = find_neighbour (&target);
2368   if (n != NULL)
2369     {
2370       n->publicKey = ve->publicKey;
2371       n->public_key_valid = GNUNET_YES;
2372       fal = add_peer_address (n,
2373                               ve->transport_name,
2374                               ve->addr,
2375                               ve->addrlen);
2376       GNUNET_assert (fal != NULL);
2377       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
2378       fal->validated = GNUNET_YES;
2379       GNUNET_STATISTICS_update (stats,
2380                                 gettext_noop ("# peer addresses considered valid"),
2381                                 1,
2382                                 GNUNET_NO);      
2383       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
2384       schedule_next_ping (fal);
2385       if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
2386         n->latency = fal->latency;
2387       else
2388         n->latency.value = (fal->latency.value + n->latency.value) / 2;
2389       n->distance = fal->distance;
2390       if (GNUNET_NO == n->received_pong)
2391         {
2392           notify_clients_connect (&target, n->latency, n->distance);
2393           n->received_pong = GNUNET_YES;
2394         }
2395       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2396         {
2397           GNUNET_SCHEDULER_cancel (sched,
2398                                    n->retry_task);
2399           n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2400           try_transmission_to_peer (n);
2401         }
2402     }
2403
2404   /* clean up validation entry */
2405   GNUNET_assert (GNUNET_YES ==
2406                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
2407                                                        key,
2408                                                        ve));
2409   GNUNET_SCHEDULER_cancel (sched,
2410                            ve->timeout_task);
2411   GNUNET_free (ve->transport_name);
2412   GNUNET_free (ve);
2413   return GNUNET_NO;
2414 }
2415
2416
2417 /**
2418  * Function that will be called if we receive a validation
2419  * of an address challenge that we transmitted to another
2420  * peer.  Note that the validation should only be considered
2421  * acceptable if the challenge matches AND if the sender
2422  * address is at least a plausible address for this peer
2423  * (otherwise we may be seeing a MiM attack).
2424  *
2425  * @param cls closure
2426  * @param message the pong message
2427  * @param peer who responded to our challenge
2428  * @param sender_address string describing our sender address (as observed
2429  *         by the other peer in binary format)
2430  * @param sender_address_len number of bytes in 'sender_address'
2431  */
2432 static void
2433 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
2434              const struct GNUNET_PeerIdentity *peer,
2435              const char *sender_address,
2436              size_t sender_address_len)
2437 {
2438 #if DEBUG_TRANSPORT > 1
2439   /* we get tons of these that just get discarded, only log
2440      if we are quite verbose */
2441   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442               "Receiving `%s' message from `%4s'.\n", "PONG",
2443               GNUNET_i2s (peer));
2444 #endif
2445   GNUNET_STATISTICS_update (stats,
2446                             gettext_noop ("# PONG messages received"),
2447                             1,
2448                             GNUNET_NO);
2449   if (GNUNET_SYSERR !=
2450       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
2451                                                   &peer->hashPubKey,
2452                                                   &check_pending_validation,
2453                                                   (void*) message))
2454     {
2455       /* This is *expected* to happen a lot since we send
2456          PONGs to *all* known addresses of the sender of
2457          the PING, so most likely we get multiple PONGs
2458          per PING, and all but the first PONG will end up
2459          here. So really we should not print anything here
2460          unless we want to be very, very verbose... */
2461 #if DEBUG_TRANSPORT > 2
2462       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2463                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
2464                   "PONG",
2465                   GNUNET_i2s (peer),
2466                   "PING");
2467 #endif
2468       return;
2469     }
2470
2471 #if 0
2472   /* FIXME: add given address to potential pool of our addresses
2473      (for voting) */
2474   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
2475               _("Another peer saw us using the address `%s' via `%s'.\n"),
2476               GNUNET_a2s ((const struct sockaddr *) &pong[1],
2477                           ntohs(pong->addrlen)),
2478               va->transport_name);
2479 #endif
2480 }
2481
2482
2483 /**
2484  * Check if the given address is already being validated; if not,
2485  * append the given address to the list of entries that are being be
2486  * validated and initiate validation.
2487  *
2488  * @param cls closure ('struct CheckHelloValidatedContext *')
2489  * @param tname name of the transport
2490  * @param expiration expiration time
2491  * @param addr the address
2492  * @param addrlen length of the address
2493  * @return GNUNET_OK (always)
2494  */
2495 static int
2496 run_validation (void *cls,
2497                 const char *tname,
2498                 struct GNUNET_TIME_Absolute expiration,
2499                 const void *addr, size_t addrlen)
2500 {
2501   struct CheckHelloValidatedContext *chvc = cls;
2502   struct GNUNET_PeerIdentity id;
2503   struct TransportPlugin *tp;
2504   struct ValidationEntry *va;
2505   struct NeighbourList *neighbour;
2506   struct ForeignAddressList *peer_address;
2507   struct TransportPingMessage ping;
2508   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2509   struct CheckAddressExistsClosure caec;
2510   char * message_buf;
2511   uint16_t hello_size;
2512   size_t tsize;
2513
2514   GNUNET_STATISTICS_update (stats,
2515                             gettext_noop ("# peer addresses scheduled for validation"),
2516                             1,
2517                             GNUNET_NO);      
2518   tp = find_transport (tname);
2519   if (tp == NULL)
2520     {
2521       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2522                   GNUNET_ERROR_TYPE_BULK,
2523                   _
2524                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2525                   tname);
2526       GNUNET_STATISTICS_update (stats,
2527                                 gettext_noop ("# peer addresses not validated (no applicable transport plugin available)"),
2528                                 1,
2529                                 GNUNET_NO);      
2530       return GNUNET_OK;
2531     }
2532   GNUNET_HELLO_get_key (chvc->hello, &pk);
2533   GNUNET_CRYPTO_hash (&pk,
2534                       sizeof (struct
2535                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2536                       &id.hashPubKey);
2537   caec.addr = addr;
2538   caec.addrlen = addrlen;
2539   caec.tname = tname;
2540   caec.exists = GNUNET_NO;
2541   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2542                                          &check_address_exists,
2543                                          &caec);
2544   if (caec.exists == GNUNET_YES)
2545     {
2546       /* During validation attempts we will likely trigger the other
2547          peer trying to validate our address which in turn will cause
2548          it to send us its HELLO, so we expect to hit this case rather
2549          frequently.  Only print something if we are very verbose. */
2550 #if DEBUG_TRANSPORT > 1
2551       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2553                   GNUNET_a2s (addr, addrlen),
2554                   tname,
2555                   GNUNET_i2s (&id));
2556 #endif
2557       GNUNET_STATISTICS_update (stats,
2558                                 gettext_noop ("# peer addresses not validated (in progress)"),
2559                                 1,
2560                                 GNUNET_NO);      
2561       return GNUNET_OK;
2562     }
2563   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2564   va->transport_name = GNUNET_strdup (tname);
2565   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2566                                             (unsigned int) -1);
2567   va->send_time = GNUNET_TIME_absolute_get();
2568   va->addr = (const void*) &va[1];
2569   memcpy (&va[1], addr, addrlen);
2570   va->addrlen = addrlen;
2571   GNUNET_HELLO_get_key (chvc->hello,
2572                         &va->publicKey);
2573   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2574                                                    HELLO_VERIFICATION_TIMEOUT,
2575                                                    &timeout_hello_validation,
2576                                                    va);
2577   GNUNET_CONTAINER_multihashmap_put (validation_map,
2578                                      &id.hashPubKey,
2579                                      va,
2580                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2581   neighbour = find_neighbour(&id);
2582   if (neighbour == NULL)
2583     neighbour = setup_new_neighbour(&id);
2584   neighbour->publicKey = va->publicKey;
2585   neighbour->public_key_valid = GNUNET_YES;
2586   peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2587   GNUNET_assert(peer_address != NULL);
2588   hello_size = GNUNET_HELLO_size(our_hello);
2589   tsize = sizeof(struct TransportPingMessage) + hello_size;
2590   message_buf = GNUNET_malloc(tsize);
2591   ping.challenge = htonl(va->challenge);
2592   ping.header.size = htons(sizeof(struct TransportPingMessage));
2593   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2594   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2595   memcpy(message_buf, our_hello, hello_size);
2596   memcpy(&message_buf[hello_size],
2597          &ping,
2598          sizeof(struct TransportPingMessage));
2599 #if DEBUG_TRANSPORT
2600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2602               GNUNET_a2s (addr, addrlen),
2603               tname,
2604               GNUNET_i2s (&id),
2605               "HELLO", hello_size,
2606               "PING", sizeof (struct TransportPingMessage));
2607 #endif
2608   GNUNET_STATISTICS_update (stats,
2609                             gettext_noop ("# PING messages sent for initial validation"),
2610                             1,
2611                             GNUNET_NO);      
2612   transmit_to_peer (NULL, peer_address,
2613                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2614                     HELLO_VERIFICATION_TIMEOUT,
2615                     message_buf, tsize,
2616                     GNUNET_YES, neighbour);
2617   GNUNET_free(message_buf);
2618   return GNUNET_OK;
2619 }
2620
2621
2622 /**
2623  * Check if addresses in validated hello "h" overlap with
2624  * those in "chvc->hello" and validate the rest.
2625  *
2626  * @param cls closure
2627  * @param peer id of the peer, NULL for last call
2628  * @param h hello message for the peer (can be NULL)
2629  * @param trust amount of trust we have in the peer (not used)
2630  */
2631 static void
2632 check_hello_validated (void *cls,
2633                        const struct GNUNET_PeerIdentity *peer,
2634                        const struct GNUNET_HELLO_Message *h, 
2635                        uint32_t trust)
2636 {
2637   struct CheckHelloValidatedContext *chvc = cls;
2638   struct GNUNET_HELLO_Message *plain_hello;
2639   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2640   struct GNUNET_PeerIdentity target;
2641   struct NeighbourList *n;
2642
2643   if (peer == NULL)
2644     {
2645       chvc->piter = NULL;
2646       GNUNET_CONTAINER_DLL_remove (chvc_head,
2647                                    chvc_tail,
2648                                    chvc);
2649       if (GNUNET_NO == chvc->hello_known)
2650         {
2651           /* notify PEERINFO about the peer now, so that we at least
2652              have the public key if some other component needs it */
2653           GNUNET_HELLO_get_key (chvc->hello, &pk);
2654           GNUNET_CRYPTO_hash (&pk,
2655                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2656                               &target.hashPubKey);
2657           plain_hello = GNUNET_HELLO_create (&pk,
2658                                              NULL, 
2659                                              NULL);
2660           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2661           GNUNET_free (plain_hello);
2662 #if DEBUG_TRANSPORT
2663           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2664                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2665                       "HELLO",
2666                       GNUNET_i2s (&target));
2667 #endif
2668           GNUNET_STATISTICS_update (stats,
2669                                     gettext_noop ("# new HELLOs requiring full validation"),
2670                                     1,
2671                                     GNUNET_NO);      
2672           GNUNET_HELLO_iterate_addresses (chvc->hello,
2673                                           GNUNET_NO, 
2674                                           &run_validation, 
2675                                           chvc);
2676         }
2677       else
2678         {
2679           GNUNET_STATISTICS_update (stats,
2680                                     gettext_noop ("# duplicate HELLO (peer known)"),
2681                                     1,
2682                                     GNUNET_NO);      
2683         }
2684       GNUNET_free (chvc);
2685       return;
2686     } 
2687   if (h == NULL)
2688     return;
2689 #if DEBUG_TRANSPORT
2690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2691               "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2692               "HELLO",
2693               GNUNET_i2s (peer));
2694 #endif
2695   chvc->hello_known = GNUNET_YES;
2696   n = find_neighbour (peer);
2697   if (n != NULL)
2698     {
2699       GNUNET_HELLO_iterate_addresses (h,
2700                                       GNUNET_NO,
2701                                       &add_to_foreign_address_list,
2702                                       n);
2703       try_transmission_to_peer (n);
2704     }
2705   else
2706     {
2707       GNUNET_STATISTICS_update (stats,
2708                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
2709                                 1,
2710                                 GNUNET_NO);      
2711     }
2712   GNUNET_STATISTICS_update (stats,
2713                             gettext_noop ("# HELLO validations (update case)"),
2714                             1,
2715                             GNUNET_NO);      
2716   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2717                                       h,
2718                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2719                                       &run_validation, 
2720                                       chvc);
2721 }
2722
2723 /**
2724  * Process HELLO-message.
2725  *
2726  * @param plugin transport involved, may be NULL
2727  * @param message the actual message
2728  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2729  */
2730 static int
2731 process_hello (struct TransportPlugin *plugin,
2732                const struct GNUNET_MessageHeader *message)
2733 {
2734   uint16_t hsize;
2735   struct GNUNET_PeerIdentity target;
2736   const struct GNUNET_HELLO_Message *hello;
2737   struct CheckHelloValidatedContext *chvc;
2738   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2739
2740   hsize = ntohs (message->size);
2741   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2742       (hsize < sizeof (struct GNUNET_MessageHeader)))
2743     {
2744       GNUNET_break (0);
2745       return GNUNET_SYSERR;
2746     }
2747   GNUNET_STATISTICS_update (stats,
2748                             gettext_noop ("# HELLOs received for validation"),
2749                             1,
2750                             GNUNET_NO);      
2751   /* first, check if load is too high */
2752   if (GNUNET_SCHEDULER_get_load (sched,
2753                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2754     {
2755       GNUNET_STATISTICS_update (stats,
2756                                 gettext_noop ("# HELLOs ignored due to high load"),
2757                                 1,
2758                                 GNUNET_NO);      
2759       return GNUNET_OK;
2760     }
2761   hello = (const struct GNUNET_HELLO_Message *) message;
2762   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2763     {
2764       GNUNET_break_op (0);
2765       return GNUNET_SYSERR;
2766     }
2767   GNUNET_CRYPTO_hash (&publicKey,
2768                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2769                       &target.hashPubKey);
2770   if (0 == memcmp (&my_identity,
2771                    &target,
2772                    sizeof (struct GNUNET_PeerIdentity)))
2773     {
2774       GNUNET_STATISTICS_update (stats,
2775                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
2776                                 1,
2777                                 GNUNET_NO);      
2778       return GNUNET_OK;      
2779     }
2780 #if DEBUG_TRANSPORT > 1
2781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2782               "Processing `%s' message for `%4s' of size %u\n",
2783               "HELLO", 
2784               GNUNET_i2s (&target), 
2785               GNUNET_HELLO_size(hello));
2786 #endif
2787   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2788   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2789   memcpy (&chvc[1], hello, hsize);
2790   GNUNET_CONTAINER_DLL_insert (chvc_head,
2791                                chvc_tail,
2792                                chvc);
2793   /* finally, check if HELLO was previously validated
2794      (continuation will then schedule actual validation) */
2795   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2796                                          sched,
2797                                          &target,
2798                                          0,
2799                                          HELLO_VERIFICATION_TIMEOUT,
2800                                          &check_hello_validated, chvc);
2801   return GNUNET_OK;
2802 }
2803
2804
2805 /**
2806  * The peer specified by the given neighbour has timed-out or a plugin
2807  * has disconnected.  We may either need to do nothing (other plugins
2808  * still up), or trigger a full disconnect and clean up.  This
2809  * function updates our state and does the necessary notifications.
2810  * Also notifies our clients that the neighbour is now officially
2811  * gone.
2812  *
2813  * @param n the neighbour list entry for the peer
2814  * @param check should we just check if all plugins
2815  *        disconnected or must we ask all plugins to
2816  *        disconnect?
2817  */
2818 static void
2819 disconnect_neighbour (struct NeighbourList *n, int check)
2820 {
2821   struct ReadyList *rpos;
2822   struct NeighbourList *npos;
2823   struct NeighbourList *nprev;
2824   struct MessageQueue *mq;
2825   struct ForeignAddressList *peer_addresses;
2826   struct ForeignAddressList *peer_pos;
2827
2828   if (GNUNET_YES == check)
2829     {
2830       rpos = n->plugins;
2831       while (NULL != rpos)
2832         {
2833           peer_addresses = rpos->addresses;
2834           while (peer_addresses != NULL)
2835             {
2836               if (GNUNET_YES == peer_addresses->connected)
2837                 return;             /* still connected */
2838               peer_addresses = peer_addresses->next;
2839             }
2840           rpos = rpos->next;
2841         }
2842     }
2843 #if DEBUG_TRANSPORT
2844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2845               "Disconnecting from `%4s'\n",
2846               GNUNET_i2s (&n->id));
2847 #endif
2848   /* remove n from neighbours list */
2849   nprev = NULL;
2850   npos = neighbours;
2851   while ((npos != NULL) && (npos != n))
2852     {
2853       nprev = npos;
2854       npos = npos->next;
2855     }
2856   GNUNET_assert (npos != NULL);
2857   if (nprev == NULL)
2858     neighbours = n->next;
2859   else
2860     nprev->next = n->next;
2861
2862   /* notify all clients about disconnect */
2863   if (GNUNET_YES == n->received_pong)
2864     notify_clients_disconnect (&n->id);
2865
2866   /* clean up all plugins, cancel connections and pending transmissions */
2867   while (NULL != (rpos = n->plugins))
2868     {
2869       n->plugins = rpos->next;
2870       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2871       while (rpos->addresses != NULL)
2872         {
2873           peer_pos = rpos->addresses;
2874           rpos->addresses = peer_pos->next;
2875           if (peer_pos->connected == GNUNET_YES)
2876             GNUNET_STATISTICS_update (stats,
2877                                       gettext_noop ("# connected addresses"),
2878                                       -1,
2879                                       GNUNET_NO); 
2880           if (GNUNET_YES == peer_pos->validated)
2881             GNUNET_STATISTICS_update (stats,
2882                                       gettext_noop ("# peer addresses considered valid"),
2883                                       -1,
2884                                       GNUNET_NO);      
2885           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
2886             {
2887               GNUNET_SCHEDULER_cancel (sched,
2888                                        peer_pos->revalidate_task);
2889               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
2890             }
2891           GNUNET_free(peer_pos);
2892         }
2893       GNUNET_free (rpos);
2894     }
2895
2896   /* free all messages on the queue */
2897   while (NULL != (mq = n->messages_head))
2898     {
2899       GNUNET_STATISTICS_update (stats,
2900                                 gettext_noop ("# bytes in message queue for other peers"),
2901                                 - (int64_t) mq->message_buf_size,
2902                                 GNUNET_NO);
2903       GNUNET_STATISTICS_update (stats,
2904                                 gettext_noop ("# bytes discarded due to disconnect"),
2905                                 mq->message_buf_size,
2906                                 GNUNET_NO);
2907       GNUNET_CONTAINER_DLL_remove (n->messages_head,
2908                                    n->messages_tail,
2909                                    mq);
2910       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
2911                                  &n->id,
2912                                  sizeof(struct GNUNET_PeerIdentity)));
2913       GNUNET_free (mq);
2914     }
2915   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2916     {
2917       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2918       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2919     }
2920   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2921     {
2922       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2923       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2924     }
2925   if (n->piter != NULL)
2926     {
2927       GNUNET_PEERINFO_iterate_cancel (n->piter);
2928       n->piter = NULL;
2929     }
2930   /* finally, free n itself */
2931   GNUNET_STATISTICS_update (stats,
2932                             gettext_noop ("# active neighbours"),
2933                             -1,
2934                             GNUNET_NO);
2935   GNUNET_free (n);
2936 }
2937
2938
2939 /**
2940  * We have received a PING message from someone.  Need to send a PONG message
2941  * in response to the peer by any means necessary. 
2942  *
2943  * FIXME: With something like TCP where a connection exists, we may
2944  * want to send it that way.  But the current API does not seem to
2945  * allow us to do so (can't tell this to the transport!)
2946  */
2947 static int 
2948 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2949             const struct GNUNET_PeerIdentity *peer,
2950             const char *sender_address,
2951             size_t sender_address_len)
2952 {
2953   struct TransportPlugin *plugin = cls;
2954   struct TransportPingMessage *ping;
2955   struct TransportPongMessage *pong;
2956   struct NeighbourList *n;
2957   struct ReadyList *rl;
2958   struct ForeignAddressList *fal;
2959
2960   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2961     {
2962       GNUNET_break_op (0);
2963       return GNUNET_SYSERR;
2964     }
2965   ping = (struct TransportPingMessage *) message;
2966   if (0 != memcmp (&ping->target,
2967                    plugin->env.my_identity,
2968                    sizeof (struct GNUNET_PeerIdentity)))
2969     {
2970       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2971                   _("Received `%s' message not destined for me!\n"), 
2972                   "PING");
2973       return GNUNET_SYSERR;
2974     }
2975 #if DEBUG_TRANSPORT
2976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2977               "Processing `%s' from `%s'\n",
2978               "PING", 
2979               GNUNET_a2s ((const struct sockaddr *)sender_address, 
2980                           sender_address_len));
2981 #endif
2982   GNUNET_STATISTICS_update (stats,
2983                             gettext_noop ("# PING messages received"),
2984                             1,
2985                             GNUNET_NO);
2986   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2987   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2988   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2989   pong->purpose.size =
2990     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2991            sizeof (uint32_t) +
2992            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2993   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2994   pong->challenge = ping->challenge;
2995   pong->addrlen = htons(sender_address_len);
2996   memcpy(&pong->signer, 
2997          &my_public_key, 
2998          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2999   memcpy (&pong[1], sender_address, sender_address_len);
3000   GNUNET_assert (GNUNET_OK ==
3001                  GNUNET_CRYPTO_rsa_sign (my_private_key,
3002                                          &pong->purpose, &pong->signature));
3003   n = find_neighbour(peer);
3004   if (n == NULL)
3005     n = setup_new_neighbour(peer);
3006   /* first try reliable response transmission */
3007   rl = n->plugins;
3008   while (rl != NULL)
3009     {
3010       fal = rl->addresses;
3011       while (fal != NULL)
3012         {
3013           if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3014                                            peer,
3015                                            (const char*) pong,
3016                                            ntohs (pong->header.size),
3017                                            TRANSPORT_PONG_PRIORITY, 
3018                                            HELLO_VERIFICATION_TIMEOUT,
3019                                            fal->addr,
3020                                            fal->addrlen,
3021                                            GNUNET_SYSERR,
3022                                            NULL, NULL))
3023             {
3024               /* done! */
3025               GNUNET_STATISTICS_update (stats,
3026                                         gettext_noop ("# PONGs unicast via reliable transport"),
3027                                         1,
3028                                         GNUNET_NO);      
3029               GNUNET_free (pong);
3030               return GNUNET_OK;
3031             }
3032           fal = fal->next;
3033         }
3034       rl = rl->next;
3035     }
3036   /* no reliable method found, do multicast */
3037   GNUNET_STATISTICS_update (stats,
3038                             gettext_noop ("# PONGs multicast to all available addresses"),
3039                             1,
3040                             GNUNET_NO);      
3041   rl = n->plugins;
3042   while (rl != NULL)
3043     {
3044       fal = rl->addresses;
3045       while (fal != NULL)
3046         {
3047           transmit_to_peer(NULL, fal,
3048                            TRANSPORT_PONG_PRIORITY, 
3049                            HELLO_VERIFICATION_TIMEOUT,
3050                            (const char *)pong, 
3051                            ntohs(pong->header.size), 
3052                            GNUNET_YES, 
3053                            n);
3054           fal = fal->next;
3055         }
3056       rl = rl->next;
3057     }
3058   GNUNET_free(pong);
3059   return GNUNET_OK;
3060 }
3061
3062
3063 /**
3064  * Function called by the plugin for each received message.
3065  * Update data volumes, possibly notify plugins about
3066  * reducing the rate at which they read from the socket
3067  * and generally forward to our receive callback.
3068  *
3069  * @param cls the "struct TransportPlugin *" we gave to the plugin
3070  * @param peer (claimed) identity of the other peer
3071  * @param message the message, NULL if we only care about
3072  *                learning about the delay until we should receive again
3073  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3074  * @param sender_address binary address of the sender (if observed)
3075  * @param sender_address_len number of bytes in sender_address
3076  * @return how long the plugin should wait until receiving more data
3077  *         (plugins that do not support this, can ignore the return value)
3078  */
3079 static struct GNUNET_TIME_Relative
3080 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3081                     const struct GNUNET_MessageHeader *message,
3082                     unsigned int distance, const char *sender_address,
3083                     size_t sender_address_len)
3084 {
3085   struct ReadyList *service_context;
3086   struct TransportPlugin *plugin = cls;
3087   struct TransportClient *cpos;
3088   struct InboundMessage *im;
3089   struct ForeignAddressList *peer_address;
3090   uint16_t msize;
3091   struct NeighbourList *n;
3092   struct GNUNET_TIME_Relative ret;
3093
3094   n = find_neighbour (peer);
3095   if (n == NULL)
3096     n = setup_new_neighbour (peer);    
3097   service_context = n->plugins;
3098   while ((service_context != NULL) && (plugin != service_context->plugin))
3099     service_context = service_context->next;
3100   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3101   if (message != NULL)
3102     {
3103       peer_address = add_peer_address(n, 
3104                                       plugin->short_name,
3105                                       sender_address, 
3106                                       sender_address_len);  
3107       if (peer_address != NULL)
3108         {
3109           peer_address->distance = distance;
3110           if (peer_address->connected == GNUNET_NO)
3111             {
3112               /* FIXME: be careful here to not mark
3113                  MULTIPLE addresses as connected! */
3114               peer_address->connected = GNUNET_YES;
3115               GNUNET_STATISTICS_update (stats,
3116                                         gettext_noop ("# connected addresses"),
3117                                         1,
3118                                         GNUNET_NO);
3119             }
3120           peer_address->timeout
3121             =
3122             GNUNET_TIME_relative_to_absolute
3123             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3124           schedule_next_ping (peer_address);
3125         }
3126       /* update traffic received amount ... */
3127       msize = ntohs (message->size);      
3128       GNUNET_STATISTICS_update (stats,
3129                                 gettext_noop ("# bytes received from other peers"),
3130                                 msize,
3131                                 GNUNET_NO);
3132       n->distance = distance;
3133       n->peer_timeout =
3134         GNUNET_TIME_relative_to_absolute
3135         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3136       GNUNET_SCHEDULER_cancel (sched,
3137                                n->timeout_task);
3138       n->timeout_task =
3139         GNUNET_SCHEDULER_add_delayed (sched,
3140                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3141                                       &neighbour_timeout_task, n);
3142       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3143         {
3144           /* dropping message due to frequent inbound volume violations! */
3145           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3146                       GNUNET_ERROR_TYPE_BULK,
3147                       _
3148                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
3149                       n->in_tracker.available_bytes_per_s__,
3150                       n->quota_violation_count);
3151           GNUNET_STATISTICS_update (stats,
3152                                     gettext_noop ("# bandwidth quota violations by other peers"),
3153                                     1,
3154                                     GNUNET_NO);
3155           return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
3156         }
3157       switch (ntohs (message->type))
3158         {
3159         case GNUNET_MESSAGE_TYPE_HELLO:
3160           GNUNET_STATISTICS_update (stats,
3161                                     gettext_noop ("# HELLO messages received from other peers"),
3162                                     1,
3163                                     GNUNET_NO);
3164           process_hello (plugin, message);
3165           break;
3166         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3167           handle_ping(plugin, message, peer, sender_address, sender_address_len);
3168           break;
3169         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3170           handle_pong(plugin, message, peer, sender_address, sender_address_len);
3171           break;
3172         default:
3173 #if DEBUG_TRANSPORT
3174           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3175                       "Received message of type %u from `%4s', sending to all clients.\n",
3176                       ntohs (message->type), GNUNET_i2s (peer));
3177 #endif
3178           if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
3179                                                               msize))
3180             n->quota_violation_count++;
3181           else 
3182             n->quota_violation_count = 0; /* back within limits */
3183           GNUNET_STATISTICS_update (stats,
3184                                     gettext_noop ("# payload received from other peers"),
3185                                     msize,
3186                                     GNUNET_NO);
3187           /* transmit message to all clients */
3188           im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
3189           im->header.size = htons (sizeof (struct InboundMessage) + msize);
3190           im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
3191           im->latency = GNUNET_TIME_relative_hton (n->latency);
3192           im->peer = *peer;
3193           memcpy (&im[1], message, msize);
3194           cpos = clients;
3195           while (cpos != NULL)
3196             {
3197               transmit_to_client (cpos, &im->header, GNUNET_YES);
3198               cpos = cpos->next;
3199             }
3200           GNUNET_free (im);
3201         }
3202     }  
3203   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3204   if (ret.value > 0)
3205     {
3206       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3207                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3208                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
3209                   (unsigned int) n->in_tracker.available_bytes_per_s__,
3210                   (unsigned long long) ret.value);
3211       GNUNET_STATISTICS_update (stats,
3212                                 gettext_noop ("# ms throttling suggested"),
3213                                 (int64_t) ret.value,
3214                                 GNUNET_NO);      
3215     }
3216   return ret;
3217 }
3218
3219
3220 /**
3221  * Handle START-message.  This is the first message sent to us
3222  * by any client which causes us to add it to our list.
3223  *
3224  * @param cls closure (always NULL)
3225  * @param client identification of the client
3226  * @param message the actual message
3227  */
3228 static void
3229 handle_start (void *cls,
3230               struct GNUNET_SERVER_Client *client,
3231               const struct GNUNET_MessageHeader *message)
3232 {
3233   struct TransportClient *c;
3234   struct ConnectInfoMessage cim;
3235   struct NeighbourList *n;
3236
3237 #if DEBUG_TRANSPORT
3238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3239               "Received `%s' request from client\n", "START");
3240 #endif
3241   c = clients;
3242   while (c != NULL)
3243     {
3244       if (c->client == client)
3245         {
3246           /* client already on our list! */
3247           GNUNET_break (0);
3248           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3249           return;
3250         }
3251       c = c->next;
3252     }
3253   c = GNUNET_malloc (sizeof (struct TransportClient));
3254   c->next = clients;
3255   clients = c;
3256   c->client = client;
3257   if (our_hello != NULL)
3258     {
3259 #if DEBUG_TRANSPORT
3260       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3261                   "Sending our own `%s' to new client\n", "HELLO");
3262 #endif
3263       transmit_to_client (c,
3264                           (const struct GNUNET_MessageHeader *) our_hello,
3265                           GNUNET_NO);
3266       /* tell new client about all existing connections */
3267       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3268       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3269       n = neighbours; 
3270       while (n != NULL)
3271         {
3272           if (GNUNET_YES == n->received_pong)
3273             {
3274               cim.id = n->id;
3275               cim.latency = GNUNET_TIME_relative_hton (n->latency);
3276               cim.distance = htonl (n->distance);
3277               transmit_to_client (c, &cim.header, GNUNET_NO);
3278             }
3279             n = n->next;
3280         }
3281     }
3282   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3283 }
3284
3285
3286 /**
3287  * Handle HELLO-message.
3288  *
3289  * @param cls closure (always NULL)
3290  * @param client identification of the client
3291  * @param message the actual message
3292  */
3293 static void
3294 handle_hello (void *cls,
3295               struct GNUNET_SERVER_Client *client,
3296               const struct GNUNET_MessageHeader *message)
3297 {
3298   int ret;
3299
3300   GNUNET_STATISTICS_update (stats,
3301                             gettext_noop ("# HELLOs received from clients"),
3302                             1,
3303                             GNUNET_NO);      
3304   ret = process_hello (NULL, message);
3305   GNUNET_SERVER_receive_done (client, ret);
3306 }
3307
3308
3309 /**
3310  * Handle SEND-message.
3311  *
3312  * @param cls closure (always NULL)
3313  * @param client identification of the client
3314  * @param message the actual message
3315  */
3316 static void
3317 handle_send (void *cls,
3318              struct GNUNET_SERVER_Client *client,
3319              const struct GNUNET_MessageHeader *message)
3320 {
3321   struct TransportClient *tc;
3322   struct NeighbourList *n;
3323   const struct OutboundMessage *obm;
3324   const struct GNUNET_MessageHeader *obmm;
3325   uint16_t size;
3326   uint16_t msize;
3327
3328   size = ntohs (message->size);
3329   if (size <
3330       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3331     {
3332       GNUNET_break (0);
3333       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3334       return;
3335     }
3336   GNUNET_STATISTICS_update (stats,
3337                             gettext_noop ("# payload received for other peers"),
3338                             size,
3339                             GNUNET_NO);      
3340   obm = (const struct OutboundMessage *) message;
3341 #if DEBUG_TRANSPORT
3342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3343               "Received `%s' request from client with target `%4s'\n",
3344               "SEND", GNUNET_i2s (&obm->peer));
3345 #endif
3346   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3347   msize = ntohs (obmm->size);
3348   if (size != msize + sizeof (struct OutboundMessage))
3349     {
3350       GNUNET_break (0);
3351       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3352       return;
3353     }
3354   n = find_neighbour (&obm->peer);
3355   if (n == NULL)
3356     n = setup_new_neighbour (&obm->peer);
3357   tc = clients;
3358   while ((tc != NULL) && (tc->client != client))
3359     tc = tc->next;
3360
3361 #if DEBUG_TRANSPORT
3362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3363               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3364               ntohs (obmm->size),
3365               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3366 #endif
3367   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
3368                     GNUNET_TIME_relative_ntoh (obm->timeout),
3369                     (char *)obmm, 
3370                     ntohs (obmm->size), GNUNET_NO, n);
3371   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3372 }
3373
3374
3375 /**
3376  * Handle SET_QUOTA-message.
3377  *
3378  * @param cls closure (always NULL)
3379  * @param client identification of the client
3380  * @param message the actual message
3381  */
3382 static void
3383 handle_set_quota (void *cls,
3384                   struct GNUNET_SERVER_Client *client,
3385                   const struct GNUNET_MessageHeader *message)
3386 {
3387   const struct QuotaSetMessage *qsm =
3388     (const struct QuotaSetMessage *) message;
3389   struct NeighbourList *n;
3390   
3391   GNUNET_STATISTICS_update (stats,
3392                             gettext_noop ("# SET QUOTA messages received"),
3393                             1,
3394                             GNUNET_NO);      
3395   n = find_neighbour (&qsm->peer);
3396   if (n == NULL)
3397     {
3398       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3399       GNUNET_STATISTICS_update (stats,
3400                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3401                                 1,
3402                                 GNUNET_NO);      
3403       return;
3404     }
3405 #if DEBUG_TRANSPORT
3406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3407               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3408               "SET_QUOTA", 
3409               (unsigned int) ntohl (qsm->quota.value__),
3410               (unsigned int) n->in_tracker.available_bytes_per_s__,
3411               GNUNET_i2s (&qsm->peer));
3412 #endif
3413   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3414                                          qsm->quota);
3415   if (0 == ntohl (qsm->quota.value__)) 
3416     disconnect_neighbour (n, GNUNET_NO);    
3417   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3418 }
3419
3420
3421 /**
3422  * Take the given address and append it to the set of results send back to
3423  * the client.
3424  * 
3425  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3426  * @param address the resolved name, NULL to indicate the last response
3427  */
3428 static void
3429 transmit_address_to_client (void *cls, const char *address)
3430 {
3431   struct GNUNET_SERVER_TransmitContext *tc = cls;
3432   size_t slen;
3433
3434   if (NULL == address)
3435     slen = 0;
3436   else
3437     slen = strlen (address) + 1;
3438   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3439                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3440   if (NULL == address)
3441     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3442 }
3443
3444
3445 /**
3446  * Handle AddressLookup-message.
3447  *
3448  * @param cls closure (always NULL)
3449  * @param client identification of the client
3450  * @param message the actual message
3451  */
3452 static void
3453 handle_address_lookup (void *cls,
3454                        struct GNUNET_SERVER_Client *client,
3455                        const struct GNUNET_MessageHeader *message)
3456 {
3457   const struct AddressLookupMessage *alum;
3458   struct TransportPlugin *lsPlugin;
3459   const char *nameTransport;
3460   const char *address;
3461   uint16_t size;
3462   struct GNUNET_SERVER_TransmitContext *tc;
3463   struct GNUNET_TIME_Absolute timeout;
3464   struct GNUNET_TIME_Relative rtimeout;
3465   int32_t numeric;
3466
3467   size = ntohs (message->size);
3468   if (size < sizeof (struct AddressLookupMessage))
3469     {
3470       GNUNET_break_op (0);
3471       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3472       return;
3473     }
3474   alum = (const struct AddressLookupMessage *) message;
3475   uint32_t addressLen = ntohl (alum->addrlen);
3476   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3477     {
3478       GNUNET_break_op (0);
3479       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3480       return;
3481     }
3482   address = (const char *) &alum[1];
3483   nameTransport = (const char *) &address[addressLen];
3484   if (nameTransport
3485       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3486     {
3487       GNUNET_break_op (0);
3488       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3489       return;
3490     }
3491   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3492   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3493   numeric = ntohl (alum->numeric_only);
3494   lsPlugin = find_transport (nameTransport);
3495   if (NULL == lsPlugin)
3496     {
3497       tc = GNUNET_SERVER_transmit_context_create (client);
3498       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3499                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3500       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3501       return;
3502     }
3503   tc = GNUNET_SERVER_transmit_context_create (client);
3504   lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
3505                                          nameTransport,
3506                                          address, addressLen, 
3507                                          numeric,
3508                                          rtimeout,
3509                                          &transmit_address_to_client, tc);
3510 }
3511
3512 /**
3513  * List of handlers for the messages understood by this
3514  * service.
3515  */
3516 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3517   {&handle_start, NULL,
3518    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3519   {&handle_hello, NULL,
3520    GNUNET_MESSAGE_TYPE_HELLO, 0},
3521   {&handle_send, NULL,
3522    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3523   {&handle_set_quota, NULL,
3524    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3525   {&handle_address_lookup, NULL,
3526    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3527    0},
3528   {NULL, NULL, 0, 0}
3529 };
3530
3531
3532 /**
3533  * Setup the environment for this plugin.
3534  */
3535 static void
3536 create_environment (struct TransportPlugin *plug)
3537 {
3538   plug->env.cfg = cfg;
3539   plug->env.sched = sched;
3540   plug->env.my_identity = &my_identity;
3541   plug->env.cls = plug;
3542   plug->env.receive = &plugin_env_receive;
3543   plug->env.notify_address = &plugin_env_notify_address;
3544   plug->env.max_connections = max_connect_per_transport;
3545   plug->env.stats = stats;
3546 }
3547
3548
3549 /**
3550  * Start the specified transport (load the plugin).
3551  */
3552 static void
3553 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3554 {
3555   struct TransportPlugin *plug;
3556   char *libname;
3557
3558   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3559               _("Loading `%s' transport plugin\n"), name);
3560   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3561   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3562   create_environment (plug);
3563   plug->short_name = GNUNET_strdup (name);
3564   plug->lib_name = libname;
3565   plug->next = plugins;
3566   plugins = plug;
3567   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3568   if (plug->api == NULL)
3569     {
3570       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3571                   _("Failed to load transport plugin for `%s'\n"), name);
3572       GNUNET_free (plug->short_name);
3573       plugins = plug->next;
3574       GNUNET_free (libname);
3575       GNUNET_free (plug);
3576     }
3577 }
3578
3579
3580 /**
3581  * Called whenever a client is disconnected.  Frees our
3582  * resources associated with that client.
3583  *
3584  * @param cls closure
3585  * @param client identification of the client
3586  */
3587 static void
3588 client_disconnect_notification (void *cls,
3589                                 struct GNUNET_SERVER_Client *client)
3590 {
3591   struct TransportClient *pos;
3592   struct TransportClient *prev;
3593   struct ClientMessageQueueEntry *mqe;
3594
3595   if (client == NULL)
3596     return;
3597 #if DEBUG_TRANSPORT
3598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3599               "Client disconnected, cleaning up.\n");
3600 #endif
3601   prev = NULL;
3602   pos = clients;
3603   while ((pos != NULL) && (pos->client != client))
3604     {
3605       prev = pos;
3606       pos = pos->next;
3607     }
3608   if (pos == NULL)
3609     return;
3610   while (NULL != (mqe = pos->message_queue_head))
3611     {
3612       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3613                                    pos->message_queue_tail,
3614                                    mqe);
3615       pos->message_count--;
3616       GNUNET_free (mqe);
3617     }
3618   if (prev == NULL)
3619     clients = pos->next;
3620   else
3621     prev->next = pos->next;
3622   if (GNUNET_YES == pos->tcs_pending)
3623     {
3624       pos->client = NULL;
3625       return;
3626     }
3627   if (pos->th != NULL)
3628     {
3629       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3630       pos->th = NULL;
3631     }
3632   GNUNET_break (0 == pos->message_count);
3633   GNUNET_free (pos);
3634 }
3635
3636
3637 /**
3638  * Iterator to free entries in the validation_map.
3639  *
3640  * @param cls closure (unused)
3641  * @param key current key code
3642  * @param value value in the hash map (validation to abort)
3643  * @return GNUNET_YES (always)
3644  */
3645 static int 
3646 abort_validation (void *cls,
3647                   const GNUNET_HashCode * key,
3648                   void *value)
3649 {
3650   struct ValidationEntry *va = value;
3651
3652   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3653   GNUNET_free (va->transport_name);
3654   GNUNET_free (va);
3655   return GNUNET_YES;
3656 }
3657
3658
3659 /**
3660  * Function called when the service shuts down.  Unloads our plugins
3661  * and cancels pending validations.
3662  *
3663  * @param cls closure, unused
3664  * @param tc task context (unused)
3665  */
3666 static void
3667 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3668 {
3669   struct TransportPlugin *plug;
3670   struct OwnAddressList *al;
3671   struct CheckHelloValidatedContext *chvc;
3672
3673   while (neighbours != NULL)
3674     disconnect_neighbour (neighbours, GNUNET_NO);
3675 #if DEBUG_TRANSPORT
3676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3677               "Transport service is unloading plugins...\n");
3678 #endif
3679   while (NULL != (plug = plugins))
3680     {
3681       plugins = plug->next;
3682       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3683       GNUNET_free (plug->lib_name);
3684       GNUNET_free (plug->short_name);
3685       while (NULL != (al = plug->addresses))
3686         {
3687           plug->addresses = al->next;
3688           GNUNET_free (al);
3689         }
3690       GNUNET_free (plug);
3691     }
3692   if (my_private_key != NULL)
3693     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3694   GNUNET_free_non_null (our_hello);
3695
3696   /* free 'chvc' data structure */
3697   while (NULL != (chvc = chvc_head))
3698     {
3699       chvc_head = chvc->next;
3700       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3701       GNUNET_free (chvc);
3702     }
3703   chvc_tail = NULL;
3704
3705   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3706                                          &abort_validation,
3707                                          NULL);
3708   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3709   validation_map = NULL;
3710   if (stats != NULL)
3711     {
3712       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3713       stats = NULL;
3714     }
3715 }
3716
3717
3718 /**
3719  * Initiate transport service.
3720  *
3721  * @param cls closure
3722  * @param s scheduler to use
3723  * @param serv the initialized server
3724  * @param c configuration to use
3725  */
3726 static void
3727 run (void *cls,
3728      struct GNUNET_SCHEDULER_Handle *s,
3729      struct GNUNET_SERVER_Handle *serv,
3730      const struct GNUNET_CONFIGURATION_Handle *c)
3731 {
3732   char *plugs;
3733   char *pos;
3734   int no_transports;
3735   unsigned long long tneigh;
3736   char *keyfile;
3737
3738   sched = s;
3739   cfg = c;
3740   stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3741   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3742   /* parse configuration */
3743   if ((GNUNET_OK !=
3744        GNUNET_CONFIGURATION_get_value_number (c,
3745                                               "TRANSPORT",
3746                                               "NEIGHBOUR_LIMIT",
3747                                               &tneigh)) ||
3748       (GNUNET_OK !=
3749        GNUNET_CONFIGURATION_get_value_filename (c,
3750                                                 "GNUNETD",
3751                                                 "HOSTKEY", &keyfile)))
3752     {
3753       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3754                   _
3755                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
3756       GNUNET_SCHEDULER_shutdown (s);
3757       if (stats != NULL)
3758         {
3759           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3760           stats = NULL;
3761         }
3762       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3763       validation_map = NULL;
3764       return;
3765     }
3766   max_connect_per_transport = (uint32_t) tneigh;
3767   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3768   GNUNET_free (keyfile);
3769   if (my_private_key == NULL)
3770     {
3771       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3772                   _
3773                   ("Transport service could not access hostkey.  Exiting.\n"));
3774       GNUNET_SCHEDULER_shutdown (s);
3775       if (stats != NULL)
3776         {
3777           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3778           stats = NULL;
3779         }
3780       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3781       validation_map = NULL;
3782       return;
3783     }
3784   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3785   GNUNET_CRYPTO_hash (&my_public_key,
3786                       sizeof (my_public_key), &my_identity.hashPubKey);
3787   /* setup notification */
3788   server = serv;
3789   GNUNET_SERVER_disconnect_notify (server,
3790                                    &client_disconnect_notification, NULL);
3791   /* load plugins... */
3792   no_transports = 1;
3793   if (GNUNET_OK ==
3794       GNUNET_CONFIGURATION_get_value_string (c,
3795                                              "TRANSPORT", "PLUGINS", &plugs))
3796     {
3797       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3798                   _("Starting transport plugins `%s'\n"), plugs);
3799       pos = strtok (plugs, " ");
3800       while (pos != NULL)
3801         {
3802           start_transport (server, pos);
3803           no_transports = 0;
3804           pos = strtok (NULL, " ");
3805         }
3806       GNUNET_free (plugs);
3807     }
3808   GNUNET_SCHEDULER_add_delayed (sched,
3809                                 GNUNET_TIME_UNIT_FOREVER_REL,
3810                                 &shutdown_task, NULL);
3811   if (no_transports)
3812     refresh_hello ();
3813
3814 #if DEBUG_TRANSPORT
3815   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3816 #endif
3817   /* process client requests */
3818   GNUNET_SERVER_add_handlers (server, handlers);
3819 }
3820
3821
3822 /**
3823  * The main function for the transport service.
3824  *
3825  * @param argc number of arguments from the command line
3826  * @param argv command line arguments
3827  * @return 0 ok, 1 on error
3828  */
3829 int
3830 main (int argc, char *const *argv)
3831 {
3832   return (GNUNET_OK ==
3833           GNUNET_SERVICE_run (argc,
3834                               argv,
3835                               "transport",
3836                               GNUNET_SERVICE_OPTION_NONE,
3837                               &run, NULL)) ? 0 : 1;
3838 }
3839
3840 /* end of gnunet-service-transport.c */