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