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