b89bc8bce0d202f7e5630ec2b6e1ccd5f2e4da45
[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  * Linked list of messages to be transmitted to
578  * the client.  Each entry is followed by the
579  * actual message.
580  */
581 struct ClientMessageQueueEntry
582 {
583   /**
584    * This is a linked list.
585    */
586   struct ClientMessageQueueEntry *next;
587 };
588
589
590 /**
591  * Client connected to the transport service.
592  */
593 struct TransportClient
594 {
595
596   /**
597    * This is a linked list.
598    */
599   struct TransportClient *next;
600
601   /**
602    * Handle to the client.
603    */
604   struct GNUNET_SERVER_Client *client;
605
606   /**
607    * Linked list of messages yet to be transmitted to
608    * the client.
609    */
610   struct ClientMessageQueueEntry *message_queue_head;
611
612   /**
613    * Tail of linked list of messages yet to be transmitted to the
614    * client.
615    */
616   struct ClientMessageQueueEntry *message_queue_tail;
617
618   /**
619    * Is a call to "transmit_send_continuation" pending?  If so, we
620    * must not free this struct (even if the corresponding client
621    * disconnects) and instead only remove it from the linked list and
622    * set the "client" field to NULL.
623    */
624   int tcs_pending;
625
626   /**
627    * Length of the list of messages pending for this client.
628    */
629   unsigned int message_count;
630
631 };
632
633
634 /**
635  * Entry in map of all HELLOs awaiting validation.
636  */
637 struct ValidationEntry
638 {
639
640   /**
641    * The address, actually a pointer to the end
642    * of this struct.  Do not free!
643    */
644   const void *addr;
645
646   /**
647    * Name of the transport.
648    */
649   char *transport_name;
650
651   /**
652    * The public key of the peer.
653    */
654   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
655
656   /**
657    * ID of task that will clean up this entry if we don't succeed
658    * with the validation first.
659    */
660   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
661
662   /**
663    * At what time did we send this validation?
664    */
665   struct GNUNET_TIME_Absolute send_time;
666
667   /**
668    * Length of addr.
669    */
670   size_t addrlen;
671
672   /**
673    * Challenge number we used.
674    */
675   uint32_t challenge;
676
677 };
678
679
680 /**
681  * Context of currently active requests to peerinfo
682  * for validation of HELLOs.
683  */
684 struct CheckHelloValidatedContext
685 {
686
687   /**
688    * This is a doubly-linked list.
689    */
690   struct CheckHelloValidatedContext *next;
691
692   /**
693    * This is a doubly-linked list.
694    */
695   struct CheckHelloValidatedContext *prev;
696
697   /**
698    * Hello that we are validating.
699    */
700   const struct GNUNET_HELLO_Message *hello;
701
702   /**
703    * Context for peerinfo iteration.
704    * NULL after we are done processing peerinfo's information.
705    */
706   struct GNUNET_PEERINFO_IteratorContext *piter;
707   
708   /**
709    * Was a HELLO known for this peer to peerinfo?
710    */
711   int hello_known;
712
713 };
714
715
716 /**
717  * Our HELLO message.
718  */
719 static struct GNUNET_HELLO_Message *our_hello;
720
721 /**
722  * "version" of "our_hello".  Used to see if a given neighbour has
723  * already been sent the latest version of our HELLO message.
724  */
725 static unsigned int our_hello_version;
726
727 /**
728  * Our public key.
729  */
730 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
731
732 /**
733  * Our identity.
734  */
735 static struct GNUNET_PeerIdentity my_identity;
736
737 /**
738  * Our private key.
739  */
740 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
741
742 /**
743  * Our scheduler.
744  */
745 struct GNUNET_SCHEDULER_Handle *sched;
746
747 /**
748  * Our configuration.
749  */
750 const struct GNUNET_CONFIGURATION_Handle *cfg;
751
752 /**
753  * Linked list of all clients to this service.
754  */
755 static struct TransportClient *clients;
756
757 /**
758  * All loaded plugins.
759  */
760 static struct TransportPlugin *plugins;
761
762 /**
763  * Our server.
764  */
765 static struct GNUNET_SERVER_Handle *server;
766
767 /**
768  * All known neighbours and their HELLOs.
769  */
770 static struct NeighbourList *neighbours;
771
772 /**
773  * Number of neighbours we'd like to have.
774  */
775 static uint32_t max_connect_per_transport;
776
777 /**
778  * Head of linked list.
779  */
780 static struct CheckHelloValidatedContext *chvc_head;
781
782 /**
783  * Tail of linked list.
784  */
785 static struct CheckHelloValidatedContext *chvc_tail;
786
787
788 /**
789  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
790  * of the given peer that we are currently validating).
791  */
792 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
793
794
795 /**
796  * The peer specified by the given neighbour has timed-out or a plugin
797  * has disconnected.  We may either need to do nothing (other plugins
798  * still up), or trigger a full disconnect and clean up.  This
799  * function updates our state and do the necessary notifications.
800  * Also notifies our clients that the neighbour is now officially
801  * gone.
802  *
803  * @param n the neighbour list entry for the peer
804  * @param check should we just check if all plugins
805  *        disconnected or must we ask all plugins to
806  *        disconnect?
807  */
808 static void disconnect_neighbour (struct NeighbourList *n, int check);
809
810 /**
811  * Check the ready list for the given neighbour and if a plugin is
812  * ready for transmission (and if we have a message), do so!
813  *
814  * @param neighbour target peer for which to transmit
815  */
816 static void try_transmission_to_peer (struct NeighbourList *neighbour);
817
818
819 /**
820  * Find an entry in the neighbour list for a particular peer.
821  * if sender_address is not specified (NULL) then return the
822  * first matching entry.  If sender_address is specified, then
823  * make sure that the address and address_len also matches.
824  *
825  * @return NULL if not found.
826  */
827 static struct NeighbourList *
828 find_neighbour (const struct GNUNET_PeerIdentity *key)
829 {
830   struct NeighbourList *head = neighbours;
831
832   while ((head != NULL) &&
833         (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
834     head = head->next;
835   return head;
836 }
837
838
839 /**
840  * Find an entry in the transport list for a particular transport.
841  *
842  * @return NULL if not found.
843  */
844 static struct TransportPlugin *
845 find_transport (const char *short_name)
846 {
847   struct TransportPlugin *head = plugins;
848   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
849     head = head->next;
850   return head;
851 }
852
853
854 /**
855  * Update the quota values for the given neighbour now.
856  */
857 static void
858 update_quota (struct NeighbourList *n)
859 {
860   struct GNUNET_TIME_Relative delta;
861   uint64_t allowed;
862   uint64_t remaining;
863
864   delta = GNUNET_TIME_absolute_get_duration (n->last_quota_update);
865   if (delta.value < MIN_QUOTA_REFRESH_TIME)
866     return;                     /* not enough time passed for doing quota update */
867   allowed = delta.value * n->quota_in;
868
869   if (n->last_received < allowed)
870     {
871       remaining = allowed - n->last_received;
872       if (n->quota_in > 0)
873         remaining /= n->quota_in;
874       else
875         remaining = 0;
876       if (remaining > MAX_BANDWIDTH_CARRY)
877         remaining = MAX_BANDWIDTH_CARRY;
878       n->last_received = 0;
879       n->last_quota_update = GNUNET_TIME_absolute_get ();
880       n->last_quota_update.value -= remaining;
881       if (n->quota_violation_count > 0)
882         n->quota_violation_count--;
883     }
884   else
885     {
886       n->last_received -= allowed;
887       n->last_quota_update = GNUNET_TIME_absolute_get ();
888       if (n->last_received > allowed)
889         {
890           /* more than twice the allowed rate! */
891           n->quota_violation_count += 10;
892         }
893     }
894 }
895
896
897 /**
898  * Function called to notify a client about the socket being ready to
899  * queue more data.  "buf" will be NULL and "size" zero if the socket
900  * was closed for writing in the meantime.
901  *
902  * @param cls closure
903  * @param size number of bytes available in buf
904  * @param buf where the callee should write the message
905  * @return number of bytes written to buf
906  */
907 static size_t
908 transmit_to_client_callback (void *cls, size_t size, void *buf)
909 {
910   struct TransportClient *client = cls;
911   struct ClientMessageQueueEntry *q;
912   uint16_t msize;
913   size_t tsize;
914   const struct GNUNET_MessageHeader *msg;
915   struct GNUNET_CONNECTION_TransmitHandle *th;
916   char *cbuf;
917
918   if (buf == NULL)
919     {
920       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
921                   "Transmission to client failed, closing connection.\n");
922       /* fatal error with client, free message queue! */
923       while (NULL != (q = client->message_queue_head))
924         {
925           client->message_queue_head = q->next;
926           GNUNET_free (q);
927         }
928       client->message_queue_tail = NULL;
929       client->message_count = 0;
930       return 0;
931     }
932   cbuf = buf;
933   tsize = 0;
934   while (NULL != (q = client->message_queue_head))
935     {
936       msg = (const struct GNUNET_MessageHeader *) &q[1];
937       msize = ntohs (msg->size);
938       if (msize + tsize > size)
939         break;
940 #if DEBUG_TRANSPORT
941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942                   "Transmitting message of type %u to client.\n",
943                   ntohs (msg->type));
944 #endif
945       client->message_queue_head = q->next;
946       if (q->next == NULL)
947         client->message_queue_tail = NULL;
948       memcpy (&cbuf[tsize], msg, msize);
949       tsize += msize;
950       GNUNET_free (q);
951       client->message_count--;
952     }
953   if (NULL != q)
954     {
955       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
956       th = GNUNET_SERVER_notify_transmit_ready (client->client,
957                                                 msize,
958                                                 GNUNET_TIME_UNIT_FOREVER_REL,
959                                                 &transmit_to_client_callback,
960                                                 client);
961       GNUNET_assert (th != NULL);
962     }
963   return tsize;
964 }
965
966
967 /**
968  * Send the specified message to the specified client.  Since multiple
969  * messages may be pending for the same client at a time, this code
970  * makes sure that no message is lost.
971  *
972  * @param client client to transmit the message to
973  * @param msg the message to send
974  * @param may_drop can this message be dropped if the
975  *        message queue for this client is getting far too large?
976  */
977 static void
978 transmit_to_client (struct TransportClient *client,
979                     const struct GNUNET_MessageHeader *msg, int may_drop)
980 {
981   struct ClientMessageQueueEntry *q;
982   uint16_t msize;
983   struct GNUNET_CONNECTION_TransmitHandle *th;
984
985   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
986     {
987       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
988                   _
989                   ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
990                   client->message_count, MAX_PENDING);
991       /* TODO: call to statistics... */
992       return;
993     }
994   client->message_count++;
995   msize = ntohs (msg->size);
996   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
997   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
998   memcpy (&q[1], msg, msize);
999   /* append to message queue */
1000   if (client->message_queue_tail == NULL)
1001     {
1002       client->message_queue_tail = q;
1003     }
1004   else
1005     {
1006       client->message_queue_tail->next = q;
1007       client->message_queue_tail = q;
1008     }
1009   if (client->message_queue_head == NULL)
1010     {
1011       client->message_queue_head = q;
1012       th = GNUNET_SERVER_notify_transmit_ready (client->client,
1013                                                 msize,
1014                                                 GNUNET_TIME_UNIT_FOREVER_REL,
1015                                                 &transmit_to_client_callback,
1016                                                 client);
1017       GNUNET_assert (th != NULL);
1018     }
1019 }
1020
1021
1022 /**
1023  * Transmit a 'SEND_OK' notification to the given client for the
1024  * given neighbour.
1025  *
1026  * @param client who to notify
1027  * @param n neighbour to notify about
1028  * @param result status code for the transmission request
1029  */
1030 static void
1031 transmit_send_ok (struct TransportClient *client,
1032                   struct NeighbourList *n,
1033                   int result)
1034 {
1035   struct SendOkMessage send_ok_msg;
1036
1037   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
1038   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
1039   send_ok_msg.success = htonl (result);
1040   send_ok_msg.latency = GNUNET_TIME_relative_hton (n->latency);
1041   send_ok_msg.peer = n->id;
1042   transmit_to_client (client, &send_ok_msg.header, GNUNET_NO); 
1043 }
1044
1045
1046 /**
1047  * Function called by the GNUNET_TRANSPORT_TransmitFunction
1048  * upon "completion" of a send request.  This tells the API
1049  * that it is now legal to send another message to the given
1050  * peer.
1051  *
1052  * @param cls closure, identifies the entry on the
1053  *            message queue that was transmitted and the
1054  *            client responsible for queueing the message
1055  * @param target the peer receiving the message
1056  * @param result GNUNET_OK on success, if the transmission
1057  *           failed, we should not tell the client to transmit
1058  *           more messages
1059  */
1060 static void
1061 transmit_send_continuation (void *cls,
1062                             const struct GNUNET_PeerIdentity *target,
1063                             int result)
1064 {
1065   struct MessageQueue *mq = cls;
1066   struct NeighbourList *n;
1067
1068   n = find_neighbour(&mq->neighbour_id);
1069   GNUNET_assert (n != NULL);
1070   if (mq->specific_address != NULL)
1071     {
1072       if (result == GNUNET_OK)    
1073         {
1074           mq->specific_address->timeout =
1075             GNUNET_TIME_relative_to_absolute
1076             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1077           mq->specific_address->connected = GNUNET_YES;
1078         }    
1079       else
1080         {
1081           mq->specific_address->connected = GNUNET_NO;
1082         }    
1083       if (! mq->internal_msg) 
1084         mq->specific_address->in_transmit = GNUNET_NO;
1085     }
1086   if (mq->client != NULL)
1087     transmit_send_ok (mq->client, n, result);
1088   GNUNET_free (mq);
1089   try_transmission_to_peer (n);
1090   if (result != GNUNET_OK)
1091     disconnect_neighbour (n, GNUNET_YES);    
1092 }
1093
1094
1095 /**
1096  * Find an address in any of the available transports for
1097  * the given neighbour that would be good for message
1098  * transmission.  This is essentially the transport selection
1099  * routine.
1100  *
1101  * @param neighbour for whom to select an address
1102  * @return selected address, NULL if we have none
1103  */
1104 struct ForeignAddressList *
1105 find_ready_address(struct NeighbourList *neighbour)
1106 {
1107   struct ReadyList *head = neighbour->plugins;
1108   struct ForeignAddressList *addresses;
1109   struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1110   struct ForeignAddressList *best_address;
1111
1112   best_address = NULL;
1113   while (head != NULL)
1114     {
1115       addresses = head->addresses;
1116       while (addresses != NULL)
1117         {
1118           if ( (addresses->timeout.value < now.value) && 
1119                (addresses->connected == GNUNET_YES) )
1120             {
1121 #if DEBUG_TRANSPORT
1122               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123                           "Marking long-time inactive connection to `%4s' as down.\n",
1124                           GNUNET_i2s (&neighbour->id));
1125 #endif
1126               addresses->connected = GNUNET_NO;
1127             }
1128           addresses = addresses->next;
1129         }
1130
1131       addresses = head->addresses;
1132       while (addresses != NULL)
1133         {
1134           if ( ( (best_address == NULL) || 
1135                  (addresses->connected == GNUNET_YES) ||
1136                  (best_address->connected == GNUNET_NO) ) &&
1137                (addresses->in_transmit == GNUNET_NO) &&
1138                ( (best_address == NULL) || 
1139                  (addresses->latency.value < best_address->latency.value)) )
1140             best_address = addresses;            
1141           /* FIXME: also give lower-latency addresses that are not
1142              connected a chance some times... */
1143           addresses = addresses->next;
1144         }
1145       head = head->next;
1146     }
1147 #if DEBUG_TRANSPORT
1148   if (best_address != NULL)
1149     {
1150       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151                   "Best address found has latency of %llu ms.\n",
1152                   best_address->latency.value);
1153     }
1154 #endif
1155   return best_address;
1156
1157 }
1158
1159
1160 /**
1161  * We should re-try transmitting to the given peer,
1162  * hopefully we've learned something in the meantime.
1163  */
1164 static void
1165 retry_transmission_task (void *cls,
1166                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1167 {
1168   struct NeighbourList *n = cls;
1169
1170   n->retry_task = GNUNET_SCHEDULER_NO_TASK;
1171   try_transmission_to_peer (n);
1172 }
1173
1174
1175 /**
1176  * Check the ready list for the given neighbour and if a plugin is
1177  * ready for transmission (and if we have a message), do so!
1178  *
1179  * @param neighbour target peer for which to transmit
1180  */
1181 static void
1182 try_transmission_to_peer (struct NeighbourList *neighbour)
1183 {
1184   struct GNUNET_TIME_Relative min_latency;
1185   struct ReadyList *rl;
1186   struct MessageQueue *mq;
1187   struct GNUNET_TIME_Relative timeout;
1188
1189   if (neighbour->messages_head == NULL)
1190     return;                     /* nothing to do */
1191   min_latency = GNUNET_TIME_UNIT_FOREVER_REL;
1192   rl = NULL;
1193   mq = neighbour->messages_head;
1194   /* FIXME: support bi-directional use of TCP */
1195   if (mq->specific_address == NULL)
1196     mq->specific_address = find_ready_address(neighbour); 
1197   if (mq->specific_address == NULL)
1198     {
1199       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1200       if (timeout.value == 0)
1201         {
1202 #if DEBUG_TRANSPORT
1203           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204                       "No destination address available to transmit message of size %u to peer `%4s'\n",
1205                       mq->message_buf_size,
1206                       GNUNET_i2s (&mq->neighbour_id));
1207 #endif
1208           if (mq->client != NULL)
1209             transmit_send_ok (mq->client, neighbour, GNUNET_NO);
1210           GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1211                                        neighbour->messages_tail,
1212                                        mq);
1213           GNUNET_free (mq);
1214           return;               /* nobody ready */ 
1215         }
1216       if (neighbour->retry_task != GNUNET_SCHEDULER_NO_TASK)
1217         GNUNET_SCHEDULER_cancel (sched,
1218                                  neighbour->retry_task);
1219       neighbour->retry_task = GNUNET_SCHEDULER_add_delayed (sched,
1220                                                             timeout,
1221                                                             &retry_transmission_task,
1222                                                             neighbour);
1223 #if DEBUG_TRANSPORT
1224       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1225                   "No validated destination address available to transmit message of size %u to peer `%4s', will wait %llums to find an address.\n",
1226                   mq->message_buf_size,
1227                   GNUNET_i2s (&mq->neighbour_id),
1228                   timeout.value);
1229 #endif
1230       return;    
1231     }
1232   GNUNET_CONTAINER_DLL_remove (neighbour->messages_head,
1233                                neighbour->messages_tail,
1234                                mq);
1235   if (mq->specific_address->connected == GNUNET_NO)
1236     mq->specific_address->connect_attempts++;
1237   rl = mq->specific_address->ready_list;
1238   mq->plugin = rl->plugin;
1239   if (!mq->internal_msg)
1240     mq->specific_address->in_transmit = GNUNET_YES;
1241 #if DEBUG_TRANSPORT
1242   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1243               "Sending message of size %u for `%4s' to `%s' via plugin `%s'\n",
1244               mq->message_buf_size,
1245               GNUNET_i2s (&neighbour->id), 
1246               GNUNET_a2s (mq->specific_address->addr,
1247                           mq->specific_address->addrlen),
1248               rl->plugin->short_name);
1249 #endif
1250   rl->plugin->api->send (rl->plugin->api->cls,
1251                          &mq->neighbour_id,
1252                          mq->message_buf,
1253                          mq->message_buf_size,
1254                          mq->priority,
1255                          GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1256                          mq->specific_address->addr,
1257                          mq->specific_address->addrlen,
1258                          GNUNET_YES /* FIXME: sometimes, we want to be more tolerant here! */,
1259                          &transmit_send_continuation, mq);
1260 }
1261
1262
1263 /**
1264  * Send the specified message to the specified peer.
1265  *
1266  * @param client source of the transmission request (can be NULL)
1267  * @param peer_address ForeignAddressList where we should send this message
1268  * @param priority how important is the message
1269  * @param timeout how long do we have to transmit?
1270  * @param message_buf message(s) to send GNUNET_MessageHeader(s)
1271  * @param message_buf_size total size of all messages in message_buf
1272  * @param is_internal is this an internal message; these are pre-pended and
1273  *                    also do not count for plugins being "ready" to transmit
1274  * @param neighbour handle to the neighbour for transmission
1275  */
1276 static void
1277 transmit_to_peer (struct TransportClient *client,
1278                   struct ForeignAddressList *peer_address,
1279                   unsigned int priority,
1280                   struct GNUNET_TIME_Relative timeout,
1281                   const char *message_buf,
1282                   size_t message_buf_size,
1283                   int is_internal, struct NeighbourList *neighbour)
1284 {
1285   struct MessageQueue *mq;
1286
1287 #if EXTRA_CHECKS
1288   if (client != NULL)
1289     {
1290       /* check for duplicate submission */
1291       mq = neighbour->messages_head;
1292       while (NULL != mq)
1293         {
1294           if (mq->client == client)
1295             {
1296               /* client transmitted to same peer twice
1297                  before getting SendOk! */
1298               GNUNET_break (0);
1299               return;
1300             }
1301           mq = mq->next;
1302         }
1303     }
1304 #endif
1305   mq = GNUNET_malloc (sizeof (struct MessageQueue) + message_buf_size);
1306   mq->specific_address = peer_address;
1307   mq->client = client;
1308   memcpy (&mq[1], message_buf, message_buf_size);
1309   mq->message_buf = (const char*) &mq[1];
1310   mq->message_buf_size = message_buf_size;
1311   memcpy(&mq->neighbour_id, &neighbour->id, sizeof(struct GNUNET_PeerIdentity));
1312   mq->internal_msg = is_internal;
1313   mq->priority = priority;
1314   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1315   if (is_internal)    
1316     GNUNET_CONTAINER_DLL_insert (neighbour->messages_head,
1317                                  neighbour->messages_tail,
1318                                  mq);
1319   else
1320     GNUNET_CONTAINER_DLL_insert_after (neighbour->messages_head,
1321                                        neighbour->messages_tail,
1322                                        neighbour->messages_tail,
1323                                        mq);
1324   try_transmission_to_peer (neighbour);
1325 }
1326
1327
1328 /**
1329  * FIXME: document.
1330  */
1331 struct GeneratorContext
1332 {
1333   struct TransportPlugin *plug_pos;
1334   struct OwnAddressList *addr_pos;
1335   struct GNUNET_TIME_Absolute expiration;
1336 };
1337
1338
1339 /**
1340  * FIXME: document.
1341  */
1342 static size_t
1343 address_generator (void *cls, size_t max, void *buf)
1344 {
1345   struct GeneratorContext *gc = cls;
1346   size_t ret;
1347
1348   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1349     {
1350       gc->plug_pos = gc->plug_pos->next;
1351       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1352     }
1353   if (NULL == gc->plug_pos)
1354     {
1355
1356       return 0;
1357     }
1358   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1359                                   gc->expiration,
1360                                   gc->addr_pos->addr,
1361                                   gc->addr_pos->addrlen, buf, max);
1362   gc->addr_pos = gc->addr_pos->next;
1363   return ret;
1364 }
1365
1366
1367 /**
1368  * Construct our HELLO message from all of the addresses of
1369  * all of the transports.
1370  */
1371 static void
1372 refresh_hello ()
1373 {
1374   struct GNUNET_HELLO_Message *hello;
1375   struct TransportClient *cpos;
1376   struct NeighbourList *npos;
1377   struct GeneratorContext gc;
1378
1379   gc.plug_pos = plugins;
1380   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1381   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1382   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1383 #if DEBUG_TRANSPORT
1384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1385               "Refreshed my `%s', new size is %d\n", "HELLO", GNUNET_HELLO_size(hello));
1386 #endif
1387   cpos = clients;
1388   while (cpos != NULL)
1389     {
1390       transmit_to_client (cpos,
1391                           (const struct GNUNET_MessageHeader *) hello,
1392                           GNUNET_NO);
1393       cpos = cpos->next;
1394     }
1395
1396   GNUNET_free_non_null (our_hello);
1397   our_hello = hello;
1398   our_hello_version++;
1399   GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1400   npos = neighbours;
1401   while (npos != NULL)
1402     {
1403 #if DEBUG_TRANSPORT
1404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1405                   "Transmitting updated `%s' to neighbour `%4s'\n",
1406                   "HELLO", GNUNET_i2s (&npos->id));
1407 #endif
1408       transmit_to_peer (NULL, NULL, 0,
1409                         HELLO_ADDRESS_EXPIRATION,
1410                         (const char *) our_hello, 
1411                         GNUNET_HELLO_size(our_hello),
1412                         GNUNET_NO, npos);
1413       npos = npos->next;
1414     }
1415 }
1416
1417
1418 /**
1419  * Task used to clean up expired addresses for a plugin.
1420  *
1421  * @param cls closure
1422  * @param tc context
1423  */
1424 static void
1425 expire_address_task (void *cls,
1426                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1427
1428
1429 /**
1430  * Update the list of addresses for this plugin,
1431  * expiring those that are past their expiration date.
1432  *
1433  * @param plugin addresses of which plugin should be recomputed?
1434  * @param fresh set to GNUNET_YES if a new address was added
1435  *        and we need to regenerate the HELLO even if nobody
1436  *        expired
1437  */
1438 static void
1439 update_addresses (struct TransportPlugin *plugin, int fresh)
1440 {
1441   struct GNUNET_TIME_Relative min_remaining;
1442   struct GNUNET_TIME_Relative remaining;
1443   struct GNUNET_TIME_Absolute now;
1444   struct OwnAddressList *pos;
1445   struct OwnAddressList *prev;
1446   struct OwnAddressList *next;
1447   int expired;
1448
1449   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1450     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1451   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1452   now = GNUNET_TIME_absolute_get ();
1453   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1454   expired = GNUNET_NO;
1455   prev = NULL;
1456   pos = plugin->addresses;
1457   while (pos != NULL)
1458     {
1459       next = pos->next;
1460       if (pos->expires.value < now.value)
1461         {
1462           expired = GNUNET_YES;
1463           if (prev == NULL)
1464             plugin->addresses = pos->next;
1465           else
1466             prev->next = pos->next;
1467           GNUNET_free (pos);
1468         }
1469       else
1470         {
1471           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1472           if (remaining.value < min_remaining.value)
1473             min_remaining = remaining;
1474           prev = pos;
1475         }
1476       pos = next;
1477     }
1478
1479   if (expired || fresh)
1480     refresh_hello ();
1481   if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1482     plugin->address_update_task
1483       = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1484                                       min_remaining,
1485                                       &expire_address_task, plugin);
1486
1487 }
1488
1489
1490 /**
1491  * Task used to clean up expired addresses for a plugin.
1492  *
1493  * @param cls closure
1494  * @param tc context
1495  */
1496 static void
1497 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1498 {
1499   struct TransportPlugin *plugin = cls;
1500   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1501   update_addresses (plugin, GNUNET_NO);
1502 }
1503
1504
1505 /**
1506  * Function that must be called by each plugin to notify the
1507  * transport service about the addresses under which the transport
1508  * provided by the plugin can be reached.
1509  *
1510  * @param cls closure
1511  * @param name name of the transport that generated the address
1512  * @param addr one of the addresses of the host, NULL for the last address
1513  *        the specific address format depends on the transport
1514  * @param addrlen length of the address
1515  * @param expires when should this address automatically expire?
1516  */
1517 static void
1518 plugin_env_notify_address (void *cls,
1519                            const char *name,
1520                            const void *addr,
1521                            size_t addrlen,
1522                            struct GNUNET_TIME_Relative expires)
1523 {
1524   struct TransportPlugin *p = cls;
1525   struct OwnAddressList *al;
1526   struct GNUNET_TIME_Absolute abex;
1527
1528   abex = GNUNET_TIME_relative_to_absolute (expires);
1529   GNUNET_assert (p == find_transport (name));
1530
1531   al = p->addresses;
1532   while (al != NULL)
1533     {
1534       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1535         {
1536           if (al->expires.value < abex.value)
1537             al->expires = abex;
1538           return;
1539         }
1540       al = al->next;
1541     }
1542
1543   al = GNUNET_malloc (sizeof (struct OwnAddressList) + addrlen);
1544   al->addr = &al[1];
1545   al->next = p->addresses;
1546   p->addresses = al;
1547   al->expires = abex;
1548   al->addrlen = addrlen;
1549   memcpy (&al[1], addr, addrlen);
1550   update_addresses (p, GNUNET_YES);
1551 }
1552
1553
1554 /**
1555  * Notify all of our clients about a peer connecting.
1556  */
1557 static void
1558 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1559                         struct GNUNET_TIME_Relative latency,
1560                         uint32_t distance)
1561 {
1562   struct ConnectInfoMessage cim;
1563   struct TransportClient *cpos;
1564
1565 #if DEBUG_TRANSPORT
1566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1567               "Notifying clients about connection from `%s'\n",
1568               GNUNET_i2s (peer));
1569 #endif
1570   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1571   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1572   cim.distance = htonl (distance);
1573   cim.latency = GNUNET_TIME_relative_hton (latency);
1574   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1575   cpos = clients;
1576   while (cpos != NULL)
1577     {
1578       transmit_to_client (cpos, &cim.header, GNUNET_NO);
1579       cpos = cpos->next;
1580     }
1581 }
1582
1583
1584 /**
1585  * Notify all of our clients about a peer disconnecting.
1586  */
1587 static void
1588 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1589 {
1590   struct DisconnectInfoMessage dim;
1591   struct TransportClient *cpos;
1592
1593 #if DEBUG_TRANSPORT
1594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595               "Notifying clients about lost connection to `%s'\n",
1596               GNUNET_i2s (peer));
1597 #endif
1598   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1599   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1600   dim.reserved = htonl (0);
1601   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1602   cpos = clients;
1603   while (cpos != NULL)
1604     {
1605       transmit_to_client (cpos, &dim.header, GNUNET_NO);
1606       cpos = cpos->next;
1607     }
1608 }
1609
1610
1611 /**
1612  * Find a ForeignAddressList entry for the given neighbour
1613  * that matches the given address and transport.
1614  *
1615  * @param neighbour which peer we care about
1616  * @param tname name of the transport plugin
1617  * @param addr binary address
1618  * @param addrlen length of addr
1619  * @return NULL if no such entry exists
1620  */
1621 static struct ForeignAddressList *
1622 find_peer_address(struct NeighbourList *neighbour,
1623                   const char *tname,
1624                   const char *addr,
1625                   size_t addrlen)
1626 {
1627   struct ReadyList *head;
1628   struct ForeignAddressList *address_head;
1629
1630   head = neighbour->plugins;
1631   while (head != NULL)
1632     {
1633       if (0 == strcmp (tname, head->plugin->short_name))
1634         break;
1635       head = head->next;
1636     }
1637   if (head == NULL)
1638     return NULL;
1639
1640   address_head = head->addresses;
1641   while ( (address_head != NULL) &&
1642           ( (address_head->addrlen != addrlen) ||
1643             (memcmp(address_head->addr, addr, addrlen) != 0) ) )
1644     address_head = address_head->next;
1645   return address_head;
1646 }
1647
1648
1649 /**
1650  * Get the peer address struct for the given neighbour and
1651  * address.  If it doesn't yet exist, create it.
1652  *
1653  * @param neighbour which peer we care about
1654  * @param tname name of the transport plugin
1655  * @param addr binary address
1656  * @param addrlen length of addr
1657  * @return NULL if we do not have a transport plugin for 'tname'
1658  */
1659 static struct ForeignAddressList *
1660 add_peer_address(struct NeighbourList *neighbour,
1661                  const char *tname,
1662                  const char *addr, 
1663                  size_t addrlen)
1664 {
1665   struct ReadyList *head;
1666   struct ForeignAddressList *ret;
1667
1668   ret = find_peer_address (neighbour, tname, addr, addrlen);
1669   if (ret != NULL)
1670     return ret;
1671   head = neighbour->plugins;
1672   while (head != NULL)
1673     {
1674       if (0 == strcmp (tname, head->plugin->short_name))
1675         break;
1676       head = head->next;
1677     }
1678   if (head == NULL)
1679     return NULL;
1680   ret = GNUNET_malloc(sizeof(struct ForeignAddressList) + addrlen);
1681   ret->addr = (const char*) &ret[1];
1682   memcpy (&ret[1], addr, addrlen);
1683   ret->addrlen = addrlen;
1684   ret->expires = GNUNET_TIME_relative_to_absolute
1685     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1686   ret->latency = GNUNET_TIME_relative_get_forever();
1687   ret->distance = -1;
1688   ret->timeout = GNUNET_TIME_relative_to_absolute
1689     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); 
1690   ret->ready_list = head;
1691   ret->next = head->addresses;
1692   head->addresses = ret;
1693   return ret;
1694 }
1695
1696
1697 /**
1698  * Closure for 'add_validated_address'.
1699  */
1700 struct AddValidatedAddressContext
1701 {
1702   /**
1703    * Entry that has been validated.
1704    */
1705   const struct ValidationEntry *ve;
1706
1707   /**
1708    * Flag set after we have added the address so
1709    * that we terminate the iteration next time.
1710    */
1711   int done;
1712 };
1713
1714
1715 /**
1716  * Callback function used to fill a buffer of max bytes with a list of
1717  * addresses in the format used by HELLOs.  Should use
1718  * "GNUNET_HELLO_add_address" as a helper function.
1719  *
1720  * @param cls the 'struct AddValidatedAddressContext' with the validated address
1721  * @param max maximum number of bytes that can be written to buf
1722  * @param buf where to write the address information
1723  * @return number of bytes written, 0 to signal the
1724  *         end of the iteration.
1725  */
1726 static size_t
1727 add_validated_address (void *cls,
1728                        size_t max, void *buf)
1729 {
1730   struct AddValidatedAddressContext *avac = cls;
1731   const struct ValidationEntry *ve = avac->ve;
1732
1733   if (GNUNET_YES == avac->done)
1734     return 0;
1735   avac->done = GNUNET_YES;
1736   return GNUNET_HELLO_add_address (ve->transport_name,
1737                                    GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION),
1738                                    ve->addr,
1739                                    ve->addrlen,
1740                                    buf,
1741                                    max);
1742 }
1743
1744
1745 /**
1746  * Iterator over hash map entries.  Checks if the given
1747  * validation entry is for the same challenge as what
1748  * is given in the PONG.
1749  *
1750  * @param cls the 'struct TransportPongMessage*'
1751  * @param key peer identity 
1752  * @param value value in the hash map ('struct ValidationEntry')
1753  * @return GNUNET_YES if we should continue to
1754  *         iterate (mismatch), GNUNET_NO if not (entry matched)
1755  */
1756 static int
1757 check_pending_validation (void *cls,
1758                           const GNUNET_HashCode * key,
1759                           void *value)
1760 {
1761   const struct TransportPongMessage *pong = cls;
1762   struct ValidationEntry *ve = value;
1763   struct AddValidatedAddressContext avac;
1764   unsigned int challenge = ntohl(pong->challenge);
1765   struct GNUNET_HELLO_Message *hello;
1766   struct GNUNET_PeerIdentity target;
1767   struct NeighbourList *n;
1768   struct ForeignAddressList *fal;
1769
1770   if (ve->challenge != challenge)
1771     return GNUNET_YES;
1772   
1773 #if DEBUG_TRANSPORT
1774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775               "Confirmed validity of address, peer `%4s' has address `%s' (%s).\n",
1776               GNUNET_h2s (key),
1777               GNUNET_a2s ((const struct sockaddr *) ve->addr,
1778                           ve->addrlen),
1779               ve->transport_name);
1780 #endif
1781   /* create the updated HELLO */
1782   GNUNET_CRYPTO_hash (&ve->publicKey,
1783                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1784                       &target.hashPubKey);
1785   avac.done = GNUNET_NO;
1786   avac.ve = ve;
1787   hello = GNUNET_HELLO_create (&ve->publicKey,
1788                                &add_validated_address,
1789                                &avac);
1790   GNUNET_PEERINFO_add_peer (cfg, sched,
1791                             &target, 
1792                             hello);
1793   GNUNET_free (hello);
1794   n = find_neighbour (&target);
1795   if (n != NULL)
1796     {
1797       fal = add_peer_address (n, ve->transport_name, 
1798                               ve->addr,
1799                               ve->addrlen);
1800       fal->expires = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1801       fal->validated = GNUNET_YES;
1802       fal->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1803       if (n->latency.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1804         n->latency = fal->latency;
1805       else
1806         n->latency.value = (fal->latency.value + n->latency.value) / 2;
1807       n->distance = fal->distance;
1808       if (GNUNET_NO == n->received_pong)
1809         {
1810           notify_clients_connect (&target, n->latency, n->distance);
1811           n->received_pong = GNUNET_YES;
1812         }
1813       if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
1814         {
1815           GNUNET_SCHEDULER_cancel (sched,
1816                                    n->retry_task);
1817           n->retry_task = GNUNET_SCHEDULER_NO_TASK;     
1818           try_transmission_to_peer (n);
1819         }
1820     }
1821
1822   /* clean up validation entry */
1823   GNUNET_assert (GNUNET_YES ==
1824                  GNUNET_CONTAINER_multihashmap_remove (validation_map,
1825                                                        key,
1826                                                        ve));
1827   GNUNET_SCHEDULER_cancel (sched,
1828                            ve->timeout_task);
1829   GNUNET_free (ve->transport_name);
1830   GNUNET_free (ve);
1831   return GNUNET_NO;
1832 }
1833
1834
1835 /**
1836  * Function that will be called if we receive a validation
1837  * of an address challenge that we transmitted to another
1838  * peer.  Note that the validation should only be considered
1839  * acceptable if the challenge matches AND if the sender
1840  * address is at least a plausible address for this peer
1841  * (otherwise we may be seeing a MiM attack).
1842  *
1843  * @param cls closure
1844  * @param name name of the transport that generated the address
1845  * @param peer who responded to our challenge
1846  * @param challenge the challenge number we presumably used
1847  * @param sender_addr string describing our sender address (as observed
1848  *         by the other peer in human-readable format)
1849  */
1850 static void
1851 handle_pong (void *cls, const struct GNUNET_MessageHeader *message,
1852              const struct GNUNET_PeerIdentity *peer,
1853              const char *sender_address,
1854              size_t sender_address_len)
1855 {
1856 #if DEBUG_TRANSPORT > 1
1857   /* we get tons of these that just get discarded, only log
1858      if we are quite verbose */
1859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1860               "Receiving `%s' message from `%4s'.\n", "PONG",
1861               GNUNET_i2s (peer));
1862 #endif
1863   if (GNUNET_SYSERR != 
1864       GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1865                                                   &peer->hashPubKey,
1866                                                   &check_pending_validation,
1867                                                   (void*) message))
1868     {
1869       /* This is *expected* to happen a lot since we send
1870          PONGs to *all* known addresses of the sender of
1871          the PING, so most likely we get multiple PONGs
1872          per PING, and all but the first PONG will end up
1873          here. So really we should not print anything here
1874          unless we want to be very, very verbose... */
1875 #if DEBUG_TRANSPORT > 2
1876       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1877                   "Received `%s' message from `%4s' but have no record of a matching `%s' message. Ignoring.\n",
1878                   "PONG",
1879                   GNUNET_i2s (peer),
1880                   "PING");
1881 #endif
1882       return;
1883     }
1884   
1885 #if 0
1886   /* FIXME: add given address to potential pool of our addresses
1887      (for voting) */
1888   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1889               _("Another peer saw us using the address `%s' via `%s'.\n"),
1890               GNUNET_a2s ((const struct sockaddr *) &pong[1],
1891                           ntohs(pong->addrlen)), 
1892               va->transport_name);  
1893 #endif
1894 }
1895
1896
1897 static void
1898 neighbour_timeout_task (void *cls,
1899                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1900 {
1901   struct NeighbourList *n = cls;
1902
1903 #if DEBUG_TRANSPORT
1904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1905               "Neighbour `%4s' has timed out!\n", GNUNET_i2s (&n->id));
1906 #endif
1907   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1908   disconnect_neighbour (n, GNUNET_NO);
1909 }
1910
1911
1912 /**
1913  * Create a fresh entry in our neighbour list for the given peer.
1914  * Will try to transmit our current HELLO to the new neighbour.  Also
1915  * notifies our clients about the new "connection".
1916  *
1917  * @param peer the peer for which we create the entry
1918  * @return the new neighbour list entry
1919  */
1920 static struct NeighbourList *
1921 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1922 {
1923   struct NeighbourList *n;
1924   struct TransportPlugin *tp;
1925   struct ReadyList *rl;
1926
1927   GNUNET_assert (our_hello != NULL);
1928   n = GNUNET_malloc (sizeof (struct NeighbourList));
1929   n->next = neighbours;
1930   neighbours = n;
1931   n->id = *peer;
1932   n->last_quota_update = GNUNET_TIME_absolute_get ();
1933   n->peer_timeout =
1934     GNUNET_TIME_relative_to_absolute
1935     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1936   n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1937   tp = plugins;
1938   while (tp != NULL)
1939     {
1940       if (tp->api->send != NULL)
1941         {
1942           rl = GNUNET_malloc (sizeof (struct ReadyList));
1943           rl->next = n->plugins;
1944           n->plugins = rl;
1945           rl->plugin = tp;
1946           rl->addresses = NULL;
1947         }
1948       tp = tp->next;
1949     }
1950   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1951   n->distance = -1;
1952   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1953                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1954                                                   &neighbour_timeout_task, n);
1955   transmit_to_peer (NULL, NULL, 0,
1956                     HELLO_ADDRESS_EXPIRATION,
1957                     (const char *) our_hello, GNUNET_HELLO_size(our_hello),
1958                     GNUNET_NO, n);
1959   return n;
1960 }
1961
1962
1963 /**
1964  * Closure for 'check_address_exists'.
1965  */
1966 struct CheckAddressExistsClosure
1967 {
1968   /**
1969    * Address to check for.
1970    */
1971   const void *addr;
1972
1973   /**
1974    * Name of the transport.
1975    */
1976   const char *tname;
1977
1978   /**
1979    * Length of addr.
1980    */
1981   size_t addrlen;
1982
1983   /**
1984    * Set to GNUNET_YES if the address exists.
1985    */
1986   int exists;
1987 };
1988
1989
1990 /**
1991  * Iterator over hash map entries.  Checks if the given
1992  * validation entry is for the same address as what is given
1993  * in the closure.
1994  *
1995  * @param cls the 'struct CheckAddressExistsClosure*'
1996  * @param key current key code (ignored)
1997  * @param value value in the hash map ('struct ValidationEntry')
1998  * @return GNUNET_YES if we should continue to
1999  *         iterate (mismatch), GNUNET_NO if not (entry matched)
2000  */
2001 static int
2002 check_address_exists (void *cls,
2003                       const GNUNET_HashCode * key,
2004                       void *value)
2005 {
2006   struct CheckAddressExistsClosure *caec = cls;
2007   struct ValidationEntry *ve = value;
2008   if ( (0 == strcmp (caec->tname,
2009                      ve->transport_name)) &&
2010        (caec->addrlen == ve->addrlen) &&
2011        (0 == memcmp (caec->addr,
2012                      ve->addr,
2013                      caec->addrlen)) )
2014     {
2015       caec->exists = GNUNET_YES;
2016       return GNUNET_NO;
2017     }
2018   return GNUNET_YES;
2019 }
2020
2021
2022 /**
2023  * HELLO validation cleanup task (validation failed).
2024  *
2025  * @param cls the 'struct ValidationEntry' that failed
2026  * @param tc scheduler context (unused)
2027  */
2028 static void
2029 timeout_hello_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2030 {
2031   struct ValidationEntry *va = cls;
2032   struct GNUNET_PeerIdentity pid;
2033
2034   GNUNET_CRYPTO_hash (&va->publicKey,
2035                       sizeof (struct
2036                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2037                       &pid.hashPubKey);
2038   GNUNET_CONTAINER_multihashmap_remove (validation_map,
2039                                         &pid.hashPubKey,
2040                                         va);
2041   GNUNET_free (va->transport_name);
2042   GNUNET_free (va);
2043 }
2044
2045
2046 /**
2047  * Check if the given address is already being validated; if not,
2048  * append the given address to the list of entries that are being be
2049  * validated and initiate validation.
2050  *
2051  * @param cls closure ('struct CheckHelloValidatedContext *')
2052  * @param tname name of the transport
2053  * @param expiration expiration time
2054  * @param addr the address
2055  * @param addrlen length of the address
2056  * @return GNUNET_OK (always)
2057  */
2058 static int
2059 run_validation (void *cls,
2060                 const char *tname,
2061                 struct GNUNET_TIME_Absolute expiration,
2062                 const void *addr, size_t addrlen)
2063 {
2064   struct CheckHelloValidatedContext *chvc = cls;
2065   struct GNUNET_PeerIdentity id;
2066   struct TransportPlugin *tp;
2067   struct ValidationEntry *va;
2068   struct NeighbourList *neighbour;
2069   struct ForeignAddressList *peer_address;
2070   struct TransportPingMessage ping;
2071   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2072   struct CheckAddressExistsClosure caec;
2073   char * message_buf;
2074   uint16_t hello_size;
2075   size_t tsize;
2076
2077   tp = find_transport (tname);
2078   if (tp == NULL)
2079     {
2080       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2081                   GNUNET_ERROR_TYPE_BULK,
2082                   _
2083                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2084                   tname);
2085       return GNUNET_OK;
2086     }
2087   GNUNET_HELLO_get_key (chvc->hello, &pk);
2088   GNUNET_CRYPTO_hash (&pk,
2089                       sizeof (struct
2090                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2091                       &id.hashPubKey);
2092   caec.addr = addr;
2093   caec.addrlen = addrlen;
2094   caec.tname = tname;
2095   caec.exists = GNUNET_NO;
2096   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2097                                          &check_address_exists,
2098                                          &caec);
2099   if (caec.exists == GNUNET_YES)
2100     {
2101       /* During validation attempts we will likely trigger the other
2102          peer trying to validate our address which in turn will cause
2103          it to send us its HELLO, so we expect to hit this case rather
2104          frequently.  Only print something if we are very verbose. */
2105 #if DEBUG_TRANSPORT > 1
2106       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2107                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2108                   GNUNET_a2s (addr, addrlen), 
2109                   tname, 
2110                   GNUNET_i2s (&id));
2111 #endif
2112       return GNUNET_OK;
2113     } 
2114   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2115   va->transport_name = GNUNET_strdup (tname);
2116   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2117                                             (unsigned int) -1);
2118   va->send_time = GNUNET_TIME_absolute_get();
2119   va->addr = (const void*) &va[1];
2120   memcpy (&va[1], addr, addrlen);
2121   va->addrlen = addrlen;
2122   GNUNET_HELLO_get_key (chvc->hello,
2123                         &va->publicKey);
2124   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2125                                                    HELLO_VERIFICATION_TIMEOUT,
2126                                                    &timeout_hello_validation,
2127                                                    va);  
2128   GNUNET_CONTAINER_multihashmap_put (validation_map,
2129                                      &id.hashPubKey,
2130                                      va,
2131                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2132   neighbour = find_neighbour(&id);  
2133   if (neighbour == NULL)
2134     neighbour = setup_new_neighbour(&id);
2135   peer_address = add_peer_address(neighbour, tname, addr, addrlen);    
2136   GNUNET_assert(peer_address != NULL);
2137   hello_size = GNUNET_HELLO_size(our_hello);
2138   tsize = sizeof(struct TransportPingMessage) + hello_size;
2139   message_buf = GNUNET_malloc(tsize);
2140   ping.challenge = htonl(va->challenge);
2141   ping.header.size = htons(sizeof(struct TransportPingMessage));
2142   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2143   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2144   memcpy(message_buf, our_hello, hello_size);
2145   memcpy(&message_buf[hello_size], 
2146          &ping, 
2147          sizeof(struct TransportPingMessage));
2148 #if DEBUG_TRANSPORT
2149   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2151               GNUNET_a2s (addr, addrlen), 
2152               tname, 
2153               GNUNET_i2s (&id),
2154               "HELLO", hello_size,
2155               "PING", sizeof (struct TransportPingMessage));
2156 #endif
2157   transmit_to_peer (NULL, peer_address, 
2158                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2159                     HELLO_VERIFICATION_TIMEOUT,
2160                     message_buf, tsize, 
2161                     GNUNET_YES, neighbour);
2162   GNUNET_free(message_buf);
2163   return GNUNET_OK;
2164 }
2165
2166
2167 /**
2168  * Add the given address to the list of foreign addresses
2169  * available for the given peer (check for duplicates).
2170  *
2171  * @param cls the respective 'struct NeighbourList' to update
2172  * @param tname name of the transport
2173  * @param expiration expiration time
2174  * @param addr the address
2175  * @param addrlen length of the address
2176  * @return GNUNET_OK (always)
2177  */
2178 static int
2179 add_to_foreign_address_list (void *cls,
2180                              const char *tname,
2181                              struct GNUNET_TIME_Absolute expiration,
2182                              const void *addr, size_t addrlen)
2183 {
2184   struct NeighbourList *n = cls;
2185   struct ForeignAddressList *fal;
2186
2187   fal = find_peer_address (n, tname, addr, addrlen);
2188   if (fal == NULL)
2189     {
2190 #if DEBUG_TRANSPORT
2191       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192                   "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2193                   GNUNET_a2s (addr, addrlen),
2194                   tname,
2195                   GNUNET_i2s (&n->id),
2196                   expiration.value);
2197 #endif
2198       fal = add_peer_address (n, tname, addr, addrlen);
2199     }
2200   if (fal == NULL)
2201     return GNUNET_OK;
2202   fal->expires = GNUNET_TIME_absolute_max (expiration,
2203                                            fal->expires);
2204   fal->validated = GNUNET_YES;
2205   return GNUNET_OK;
2206 }
2207
2208
2209 /**
2210  * Check if addresses in validated hello "h" overlap with
2211  * those in "chvc->hello" and validate the rest.
2212  *
2213  * @param cls closure
2214  * @param peer id of the peer, NULL for last call
2215  * @param hello hello message for the peer (can be NULL)
2216  * @param trust amount of trust we have in the peer (not used)
2217  */
2218 static void
2219 check_hello_validated (void *cls,
2220                        const struct GNUNET_PeerIdentity *peer,
2221                        const struct GNUNET_HELLO_Message *h, 
2222                        uint32_t trust)
2223 {
2224   struct CheckHelloValidatedContext *chvc = cls;
2225   struct GNUNET_HELLO_Message *plain_hello;
2226   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2227   struct GNUNET_PeerIdentity target;
2228   struct NeighbourList *n;
2229
2230   if (peer == NULL)
2231     {
2232       chvc->piter = NULL;
2233       GNUNET_CONTAINER_DLL_remove (chvc_head,
2234                                    chvc_tail,
2235                                    chvc);
2236       if (GNUNET_NO == chvc->hello_known)
2237         {
2238           /* notify PEERINFO about the peer now, so that we at least
2239              have the public key if some other component needs it */
2240           GNUNET_HELLO_get_key (chvc->hello, &pk);
2241           GNUNET_CRYPTO_hash (&pk,
2242                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2243                               &target.hashPubKey);
2244           plain_hello = GNUNET_HELLO_create (&pk,
2245                                              NULL, 
2246                                              NULL);
2247           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2248           GNUNET_free (plain_hello);
2249 #if DEBUG_TRANSPORT
2250           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2251                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2252                       "HELLO",
2253                       GNUNET_i2s (&target));
2254 #endif
2255           GNUNET_HELLO_iterate_addresses (chvc->hello,
2256                                           GNUNET_NO, 
2257                                           &run_validation, 
2258                                           chvc);
2259         }
2260       GNUNET_free (chvc);
2261       return;
2262     }
2263   if (h == NULL)
2264     return;
2265   chvc->hello_known = GNUNET_YES;
2266   n = find_neighbour (peer);
2267   if (n != NULL)
2268     {
2269       GNUNET_HELLO_iterate_addresses (h,
2270                                       GNUNET_NO,
2271                                       &add_to_foreign_address_list,
2272                                       n);
2273       try_transmission_to_peer (n);
2274     }
2275   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2276                                       h,
2277                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2278                                       &run_validation, 
2279                                       chvc);
2280 }
2281
2282 /**
2283  * Process HELLO-message.
2284  *
2285  * @param plugin transport involved, may be NULL
2286  * @param message the actual message
2287  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2288  */
2289 static int
2290 process_hello (struct TransportPlugin *plugin,
2291                const struct GNUNET_MessageHeader *message)
2292 {
2293   uint16_t hsize;
2294   struct GNUNET_PeerIdentity target;
2295   const struct GNUNET_HELLO_Message *hello;
2296   struct CheckHelloValidatedContext *chvc;
2297   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2298
2299   hsize = ntohs (message->size);
2300   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2301       (hsize < sizeof (struct GNUNET_MessageHeader)))
2302     {
2303       GNUNET_break (0);
2304       return GNUNET_SYSERR;
2305     }
2306   /* first, check if load is too high */
2307   if (GNUNET_SCHEDULER_get_load (sched,
2308                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2309     {
2310       /* TODO: call to stats? */
2311       return GNUNET_OK;
2312     }
2313   hello = (const struct GNUNET_HELLO_Message *) message;
2314   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2315     {
2316       GNUNET_break_op (0);
2317       return GNUNET_SYSERR;
2318     }
2319   GNUNET_CRYPTO_hash (&publicKey,
2320                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2321                       &target.hashPubKey);
2322 #if DEBUG_TRANSPORT
2323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324               "Processing `%s' message for `%4s' of size %u\n",
2325               "HELLO", 
2326               GNUNET_i2s (&target), 
2327               GNUNET_HELLO_size(hello));
2328 #endif
2329
2330   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2331   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2332   memcpy (&chvc[1], hello, hsize);
2333   GNUNET_CONTAINER_DLL_insert (chvc_head,
2334                                chvc_tail,
2335                                chvc);
2336   /* finally, check if HELLO was previously validated
2337      (continuation will then schedule actual validation) */
2338   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2339                                          sched,
2340                                          &target,
2341                                          0,
2342                                          HELLO_VERIFICATION_TIMEOUT,
2343                                          &check_hello_validated, chvc);
2344   return GNUNET_OK;
2345 }
2346
2347
2348 /**
2349  * The peer specified by the given neighbour has timed-out or a plugin
2350  * has disconnected.  We may either need to do nothing (other plugins
2351  * still up), or trigger a full disconnect and clean up.  This
2352  * function updates our state and does the necessary notifications.
2353  * Also notifies our clients that the neighbour is now officially
2354  * gone.
2355  *
2356  * @param n the neighbour list entry for the peer
2357  * @param check should we just check if all plugins
2358  *        disconnected or must we ask all plugins to
2359  *        disconnect?
2360  */
2361 static void
2362 disconnect_neighbour (struct NeighbourList *n, int check)
2363 {
2364   struct ReadyList *rpos;
2365   struct NeighbourList *npos;
2366   struct NeighbourList *nprev;
2367   struct MessageQueue *mq;
2368   struct ForeignAddressList *peer_addresses;
2369   struct ForeignAddressList *peer_pos;
2370
2371   if (GNUNET_YES == check)
2372     {
2373       rpos = n->plugins;
2374       while (NULL != rpos)
2375         {
2376           peer_addresses = rpos->addresses;
2377           while (peer_addresses != NULL)
2378             {
2379               if (GNUNET_YES == peer_addresses->connected)
2380                 return;             /* still connected */
2381               peer_addresses = peer_addresses->next;
2382             }
2383           rpos = rpos->next;
2384         }
2385     }
2386 #if DEBUG_TRANSPORT
2387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2388               "Disconnecting from `%4s'\n",
2389               GNUNET_i2s (&n->id));
2390 #endif
2391   /* remove n from neighbours list */
2392   nprev = NULL;
2393   npos = neighbours;
2394   while ((npos != NULL) && (npos != n))
2395     {
2396       nprev = npos;
2397       npos = npos->next;
2398     }
2399   GNUNET_assert (npos != NULL);
2400   if (nprev == NULL)
2401     neighbours = n->next;
2402   else
2403     nprev->next = n->next;
2404
2405   /* notify all clients about disconnect */
2406   if (GNUNET_YES == n->received_pong)
2407     notify_clients_disconnect (&n->id);
2408
2409   /* clean up all plugins, cancel connections and pending transmissions */
2410   while (NULL != (rpos = n->plugins))
2411     {
2412       n->plugins = rpos->next;
2413       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2414
2415       while (rpos->addresses != NULL)
2416         {
2417           peer_pos = rpos->addresses;
2418           rpos->addresses = peer_pos->next;
2419           GNUNET_free(peer_pos);
2420         }
2421       GNUNET_free (rpos);
2422     }
2423
2424   /* free all messages on the queue */
2425   while (NULL != (mq = n->messages_head))
2426     {
2427       GNUNET_CONTAINER_DLL_remove (n->messages_head,
2428                                    n->messages_tail,
2429                                    mq);
2430       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
2431                                  &n->id,
2432                                  sizeof(struct GNUNET_PeerIdentity)));
2433       GNUNET_free (mq);
2434     }
2435   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2436     {
2437       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2438       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2439     }
2440   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2441     {
2442       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2443       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2444     }
2445   /* finally, free n itself */
2446   GNUNET_free (n);
2447 }
2448
2449
2450 /**
2451  * We have received a PING message from someone.  Need to send a PONG message
2452  * in response to the peer by any means necessary. 
2453  *
2454  * FIXME: With something like TCP where a connection exists, we may
2455  * want to send it that way.  But the current API does not seem to
2456  * allow us to do so (can't tell this to the transport!)
2457  */
2458 static int 
2459 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2460             const struct GNUNET_PeerIdentity *peer,
2461             const char *sender_address,
2462             size_t sender_address_len)
2463 {
2464   struct TransportPlugin *plugin = cls;
2465   struct TransportPingMessage *ping;
2466   struct TransportPongMessage *pong;
2467   uint16_t msize;
2468   struct NeighbourList *n;
2469   struct ReadyList *rl;
2470   struct ForeignAddressList *fal;
2471
2472   msize = ntohs (message->size);
2473   if (msize < sizeof (struct TransportPingMessage))
2474     {
2475       GNUNET_break_op (0);
2476       return GNUNET_SYSERR;
2477     }
2478   ping = (struct TransportPingMessage *) message;
2479   if (0 != memcmp (&ping->target,
2480                    plugin->env.my_identity,
2481                    sizeof (struct GNUNET_PeerIdentity)))
2482     {
2483       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2484                   _("Received `%s' message not destined for me!\n"), 
2485                   "PING");
2486       return GNUNET_SYSERR;
2487     }
2488 #if DEBUG_TRANSPORT
2489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2490               "Processing `%s' from `%s'\n",
2491               "PING", 
2492               GNUNET_a2s ((const struct sockaddr *)sender_address, 
2493                           sender_address_len));
2494 #endif
2495   msize -= sizeof (struct TransportPingMessage);
2496   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2497   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2498   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2499   pong->purpose.size =
2500     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2501            sizeof (uint32_t) +
2502            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2503   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2504   pong->challenge = ping->challenge;
2505   pong->addrlen = htons(sender_address_len);
2506   memcpy(&pong->signer, 
2507          &my_public_key, 
2508          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2509   memcpy (&pong[1], sender_address, sender_address_len);
2510   GNUNET_assert (GNUNET_OK ==
2511                  GNUNET_CRYPTO_rsa_sign (my_private_key,
2512                                          &pong->purpose, &pong->signature));
2513
2514   n = find_neighbour(peer);
2515   if (n == NULL)
2516     n = setup_new_neighbour(peer);
2517   /* broadcast 'PONG' to all available addresses */
2518   rl = n->plugins;
2519   while (rl != NULL)
2520     {
2521       fal = rl->addresses;
2522       while (fal != NULL)
2523         {
2524           transmit_to_peer(NULL, fal,
2525                            TRANSPORT_PONG_PRIORITY, 
2526                            HELLO_VERIFICATION_TIMEOUT,
2527                            (const char *)pong, 
2528                            ntohs(pong->header.size), 
2529                            GNUNET_YES, 
2530                            n);
2531           fal = fal->next;
2532         }
2533       rl = rl->next;
2534     }
2535   GNUNET_free(pong);
2536   return GNUNET_OK;
2537 }
2538
2539
2540 /**
2541  * Function called by the plugin for each received message.
2542  * Update data volumes, possibly notify plugins about
2543  * reducing the rate at which they read from the socket
2544  * and generally forward to our receive callback.
2545  *
2546  * @param cls the "struct TransportPlugin *" we gave to the plugin
2547  * @param message the message, NULL if peer was disconnected
2548  * @param distance the transport cost to this peer (not latency!)
2549  * @param sender_address the address that the sender reported
2550  *        (opaque to transport service)
2551  * @param sender_address_len the length of the sender address
2552  * @param peer (claimed) identity of the other peer
2553  * @return the new service_context that the plugin should use
2554  *         for future receive calls for messages from this
2555  *         particular peer
2556  *
2557  */
2558 static void
2559 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2560                     const struct GNUNET_MessageHeader *message,
2561                     unsigned int distance, const char *sender_address,
2562                     size_t sender_address_len)
2563 {
2564   struct ReadyList *service_context;
2565   struct TransportPlugin *plugin = cls;
2566   struct TransportClient *cpos;
2567   struct InboundMessage *im;
2568   struct ForeignAddressList *peer_address;
2569   uint16_t msize;
2570   struct NeighbourList *n;
2571
2572   n = find_neighbour (peer);
2573   if (n == NULL)
2574     {
2575       if (message == NULL)
2576         return;                 /* disconnect of peer already marked down */
2577       n = setup_new_neighbour (peer);
2578     }
2579   service_context = n->plugins;
2580   while ((service_context != NULL) && (plugin != service_context->plugin))
2581     service_context = service_context->next;
2582   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2583   if (message == NULL)
2584     {
2585 #if DEBUG_TRANSPORT
2586       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2587                   "Receive failed from `%4s', triggering disconnect\n",
2588                   GNUNET_i2s (&n->id));
2589 #endif
2590       /* TODO: call stats */
2591       disconnect_neighbour (n, GNUNET_YES);
2592       return;
2593     }
2594   peer_address = add_peer_address(n, 
2595                                   plugin->short_name,
2596                                   sender_address, 
2597                                   sender_address_len);  
2598   if (peer_address != NULL)
2599     {
2600       peer_address->distance = distance;
2601       if (peer_address->connected == GNUNET_NO)
2602         {
2603           peer_address->connected = GNUNET_YES;
2604           peer_address->connect_attempts++;
2605         }
2606       peer_address->timeout
2607         =
2608         GNUNET_TIME_relative_to_absolute
2609         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2610     }
2611   /* update traffic received amount ... */
2612   msize = ntohs (message->size);
2613   n->last_received += msize;
2614   n->distance = distance;
2615   n->peer_timeout =
2616     GNUNET_TIME_relative_to_absolute
2617     (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2618   GNUNET_SCHEDULER_cancel (sched,
2619                            n->timeout_task);
2620   n->timeout_task =
2621     GNUNET_SCHEDULER_add_delayed (sched,
2622                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2623                                   &neighbour_timeout_task, n);
2624   update_quota (n);
2625   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2626     {
2627       /* dropping message due to frequent inbound volume violations! */
2628       GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2629                   GNUNET_ERROR_TYPE_BULK,
2630                   _
2631                   ("Dropping incoming message due to repeated bandwidth quota violations (total of %u).\n"), n->quota_violation_count);
2632       /* TODO: call stats */
2633       return;
2634     }
2635   switch (ntohs (message->type))
2636     {
2637     case GNUNET_MESSAGE_TYPE_HELLO:
2638       process_hello (plugin, message);
2639       break;
2640     case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2641       handle_ping(plugin, message, peer, sender_address, sender_address_len);
2642       break;
2643     case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2644       handle_pong(plugin, message, peer, sender_address, sender_address_len);
2645       break;
2646     default:
2647 #if DEBUG_TRANSPORT
2648       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649                   "Received message of type %u from `%4s', sending to all clients.\n",
2650                   ntohs (message->type), GNUNET_i2s (peer));
2651 #endif
2652       /* transmit message to all clients */
2653       im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2654       im->header.size = htons (sizeof (struct InboundMessage) + msize);
2655       im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2656       im->latency = GNUNET_TIME_relative_hton (n->latency);
2657       im->peer = *peer;
2658       memcpy (&im[1], message, msize);
2659       cpos = clients;
2660       while (cpos != NULL)
2661         {
2662           transmit_to_client (cpos, &im->header, GNUNET_YES);
2663           cpos = cpos->next;
2664         }
2665       GNUNET_free (im);
2666     }
2667 }
2668
2669
2670 /**
2671  * Handle START-message.  This is the first message sent to us
2672  * by any client which causes us to add it to our list.
2673  *
2674  * @param cls closure (always NULL)
2675  * @param client identification of the client
2676  * @param message the actual message
2677  */
2678 static void
2679 handle_start (void *cls,
2680               struct GNUNET_SERVER_Client *client,
2681               const struct GNUNET_MessageHeader *message)
2682 {
2683   struct TransportClient *c;
2684   struct ConnectInfoMessage cim;
2685   struct NeighbourList *n;
2686
2687 #if DEBUG_TRANSPORT
2688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689               "Received `%s' request from client\n", "START");
2690 #endif
2691   c = clients;
2692   while (c != NULL)
2693     {
2694       if (c->client == client)
2695         {
2696           /* client already on our list! */
2697           GNUNET_break (0);
2698           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2699           return;
2700         }
2701       c = c->next;
2702     }
2703   c = GNUNET_malloc (sizeof (struct TransportClient));
2704   c->next = clients;
2705   clients = c;
2706   c->client = client;
2707   if (our_hello != NULL)
2708     {
2709 #if DEBUG_TRANSPORT
2710       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711                   "Sending our own `%s' to new client\n", "HELLO");
2712 #endif
2713       transmit_to_client (c,
2714                           (const struct GNUNET_MessageHeader *) our_hello,
2715                           GNUNET_NO);
2716       /* tell new client about all existing connections */
2717       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2718       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2719       n = neighbours; 
2720       while (n != NULL)
2721         {
2722           if (GNUNET_YES == n->received_pong)
2723             {
2724               cim.id = n->id;
2725               cim.latency = GNUNET_TIME_relative_hton (n->latency);
2726               cim.distance = htonl (n->distance);
2727               transmit_to_client (c, &cim.header, GNUNET_NO);
2728             }
2729             n = n->next;
2730         }
2731     }
2732   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2733 }
2734
2735
2736 /**
2737  * Handle HELLO-message.
2738  *
2739  * @param cls closure (always NULL)
2740  * @param client identification of the client
2741  * @param message the actual message
2742  */
2743 static void
2744 handle_hello (void *cls,
2745               struct GNUNET_SERVER_Client *client,
2746               const struct GNUNET_MessageHeader *message)
2747 {
2748   int ret;
2749
2750 #if DEBUG_TRANSPORT
2751   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2752               "Received `%s' request from client\n", "HELLO");
2753 #endif
2754   ret = process_hello (NULL, message);
2755   GNUNET_SERVER_receive_done (client, ret);
2756 }
2757
2758
2759 /**
2760  * Handle SEND-message.
2761  *
2762  * @param cls closure (always NULL)
2763  * @param client identification of the client
2764  * @param message the actual message
2765  */
2766 static void
2767 handle_send (void *cls,
2768              struct GNUNET_SERVER_Client *client,
2769              const struct GNUNET_MessageHeader *message)
2770 {
2771   struct TransportClient *tc;
2772   struct NeighbourList *n;
2773   const struct OutboundMessage *obm;
2774   const struct GNUNET_MessageHeader *obmm;
2775   uint16_t size;
2776   uint16_t msize;
2777
2778   size = ntohs (message->size);
2779   if (size <
2780       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2781     {
2782       GNUNET_break (0);
2783       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2784       return;
2785     }
2786   obm = (const struct OutboundMessage *) message;
2787 #if DEBUG_TRANSPORT
2788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789               "Received `%s' request from client with target `%4s'\n",
2790               "SEND", GNUNET_i2s (&obm->peer));
2791 #endif
2792   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2793   msize = ntohs (obmm->size);
2794   if (size != msize + sizeof (struct OutboundMessage))
2795     {
2796       GNUNET_break (0);
2797       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2798       return;
2799     }
2800   n = find_neighbour (&obm->peer);
2801   if (n == NULL)
2802     n = setup_new_neighbour (&obm->peer);
2803   tc = clients;
2804   while ((tc != NULL) && (tc->client != client))
2805     tc = tc->next;
2806
2807 #if DEBUG_TRANSPORT
2808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2809               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2810               ntohs (obmm->size),
2811               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2812 #endif
2813   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
2814                     GNUNET_TIME_relative_ntoh (obm->timeout),
2815                     (char *)obmm, 
2816                     ntohs (obmm->size), GNUNET_NO, n);
2817   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2818 }
2819
2820
2821 /**
2822  * Handle SET_QUOTA-message.
2823  *
2824  * @param cls closure (always NULL)
2825  * @param client identification of the client
2826  * @param message the actual message
2827  */
2828 static void
2829 handle_set_quota (void *cls,
2830                   struct GNUNET_SERVER_Client *client,
2831                   const struct GNUNET_MessageHeader *message)
2832 {
2833   const struct QuotaSetMessage *qsm =
2834     (const struct QuotaSetMessage *) message;
2835   struct NeighbourList *n;
2836   struct TransportPlugin *p;
2837   struct ReadyList *rl;
2838
2839   n = find_neighbour (&qsm->peer);
2840   if (n == NULL)
2841     {
2842       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2843       return;
2844     }
2845
2846 #if DEBUG_TRANSPORT
2847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2848               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
2849               "SET_QUOTA", ntohl(qsm->quota_in), n->quota_in, GNUNET_i2s (&qsm->peer));
2850 #endif
2851
2852   update_quota (n);
2853   if (n->quota_in < ntohl (qsm->quota_in))
2854     n->last_quota_update = GNUNET_TIME_absolute_get ();
2855   n->quota_in = ntohl (qsm->quota_in);
2856   rl = n->plugins;
2857   while (rl != NULL)
2858     {
2859       p = rl->plugin;
2860       p->api->set_receive_quota (p->api->cls,
2861                                  &qsm->peer, ntohl (qsm->quota_in));
2862       rl = rl->next;
2863     }
2864   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2865 }
2866
2867
2868 static void
2869 transmit_address_to_client (void *cls, const char *address)
2870 {
2871   struct GNUNET_SERVER_TransmitContext *tc = cls;
2872   size_t slen;
2873
2874   if (NULL == address)
2875     slen = 0;
2876   else
2877     slen = strlen (address) + 1;
2878   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
2879                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2880   if (NULL == address)
2881     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
2882 }
2883
2884
2885 /**
2886  * Handle AddressLookup-message.
2887  *
2888  * @param cls closure (always NULL)
2889  * @param client identification of the client
2890  * @param message the actual message
2891  */
2892 static void
2893 handle_address_lookup (void *cls,
2894                        struct GNUNET_SERVER_Client *client,
2895                        const struct GNUNET_MessageHeader *message)
2896 {
2897   const struct AddressLookupMessage *alum;
2898   struct TransportPlugin *lsPlugin;
2899   const char *nameTransport;
2900   const char *address;
2901   uint16_t size;
2902   struct GNUNET_SERVER_TransmitContext *tc;
2903
2904   size = ntohs (message->size);
2905   if (size < sizeof (struct AddressLookupMessage))
2906     {
2907       GNUNET_break_op (0);
2908       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2909       return;
2910     }
2911   alum = (const struct AddressLookupMessage *) message;
2912   uint32_t addressLen = ntohl (alum->addrlen);
2913   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
2914     {
2915       GNUNET_break_op (0);
2916       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2917       return;
2918     }
2919   address = (const char *) &alum[1];
2920   nameTransport = (const char *) &address[addressLen];
2921   if (nameTransport
2922       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
2923     {
2924       GNUNET_break_op (0);
2925       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2926       return;
2927     }
2928   struct GNUNET_TIME_Absolute timeout =
2929     GNUNET_TIME_absolute_ntoh (alum->timeout);
2930   struct GNUNET_TIME_Relative rtimeout =
2931     GNUNET_TIME_absolute_get_remaining (timeout);
2932   lsPlugin = find_transport (nameTransport);
2933   if (NULL == lsPlugin)
2934     {
2935       tc = GNUNET_SERVER_transmit_context_create (client);
2936       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
2937                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2938       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2939       return;
2940     }
2941   tc = GNUNET_SERVER_transmit_context_create (client);
2942   lsPlugin->api->address_pretty_printer (cls, nameTransport,
2943                                          address, addressLen, GNUNET_YES,
2944                                          rtimeout,
2945                                          &transmit_address_to_client, tc);
2946 }
2947
2948 /**
2949  * List of handlers for the messages understood by this
2950  * service.
2951  */
2952 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2953   {&handle_start, NULL,
2954    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2955   {&handle_hello, NULL,
2956    GNUNET_MESSAGE_TYPE_HELLO, 0},
2957   {&handle_send, NULL,
2958    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2959   {&handle_set_quota, NULL,
2960    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2961   {&handle_address_lookup, NULL,
2962    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2963    0},
2964   {NULL, NULL, 0, 0}
2965 };
2966
2967
2968 /**
2969  * Setup the environment for this plugin.
2970  */
2971 static void
2972 create_environment (struct TransportPlugin *plug)
2973 {
2974   plug->env.cfg = cfg;
2975   plug->env.sched = sched;
2976   plug->env.my_identity = &my_identity;
2977   plug->env.cls = plug;
2978   plug->env.receive = &plugin_env_receive;
2979   plug->env.notify_address = &plugin_env_notify_address;
2980   plug->env.default_quota_in =
2981     (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2982   plug->env.max_connections = max_connect_per_transport;
2983 }
2984
2985
2986 /**
2987  * Start the specified transport (load the plugin).
2988  */
2989 static void
2990 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2991 {
2992   struct TransportPlugin *plug;
2993   char *libname;
2994
2995   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2996               _("Loading `%s' transport plugin\n"), name);
2997   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2998   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2999   create_environment (plug);
3000   plug->short_name = GNUNET_strdup (name);
3001   plug->lib_name = libname;
3002   plug->next = plugins;
3003   plugins = plug;
3004   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3005   if (plug->api == NULL)
3006     {
3007       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3008                   _("Failed to load transport plugin for `%s'\n"), name);
3009       GNUNET_free (plug->short_name);
3010       plugins = plug->next;
3011       GNUNET_free (libname);
3012       GNUNET_free (plug);
3013     }
3014 }
3015
3016
3017 /**
3018  * Called whenever a client is disconnected.  Frees our
3019  * resources associated with that client.
3020  *
3021  * @param cls closure
3022  * @param client identification of the client
3023  */
3024 static void
3025 client_disconnect_notification (void *cls,
3026                                 struct GNUNET_SERVER_Client *client)
3027 {
3028   struct TransportClient *pos;
3029   struct TransportClient *prev;
3030   struct ClientMessageQueueEntry *mqe;
3031
3032   if (client == NULL)
3033     return;
3034 #if DEBUG_TRANSPORT
3035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3036               "Client disconnected, cleaning up.\n");
3037 #endif
3038   prev = NULL;
3039   pos = clients;
3040   while ((pos != NULL) && (pos->client != client))
3041     {
3042       prev = pos;
3043       pos = pos->next;
3044     }
3045   if (pos == NULL)
3046     return;
3047   while (NULL != (mqe = pos->message_queue_head))
3048     {
3049       pos->message_queue_head = mqe->next;
3050       GNUNET_free (mqe);
3051     }
3052   pos->message_queue_head = NULL;
3053   if (prev == NULL)
3054     clients = pos->next;
3055   else
3056     prev->next = pos->next;
3057   if (GNUNET_YES == pos->tcs_pending)
3058     {
3059       pos->client = NULL;
3060       return;
3061     }
3062   GNUNET_free (pos);
3063 }
3064
3065
3066 /**
3067  * Iterator to free entries in the validation_map.
3068  *
3069  * @param cls closure (unused)
3070  * @param key current key code
3071  * @param value value in the hash map (validation to abort)
3072  * @return GNUNET_YES (always)
3073  */
3074 static int 
3075 abort_validation (void *cls,
3076                   const GNUNET_HashCode * key,
3077                   void *value)
3078 {
3079   struct ValidationEntry *va = value;
3080
3081   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3082   GNUNET_free (va->transport_name);
3083   GNUNET_free (va);
3084   return GNUNET_YES;
3085 }
3086
3087
3088 /**
3089  * Function called when the service shuts down.  Unloads our plugins
3090  * and cancels pending validations.
3091  *
3092  * @param cls closure, unused
3093  * @param tc task context (unused)
3094  */
3095 static void
3096 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3097 {
3098   struct TransportPlugin *plug;
3099   struct OwnAddressList *al;
3100   struct CheckHelloValidatedContext *chvc;
3101
3102   while (neighbours != NULL)
3103     disconnect_neighbour (neighbours, GNUNET_NO);
3104 #if DEBUG_TRANSPORT
3105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3106               "Transport service is unloading plugins...\n");
3107 #endif
3108   while (NULL != (plug = plugins))
3109     {
3110       plugins = plug->next;
3111       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3112       GNUNET_free (plug->lib_name);
3113       GNUNET_free (plug->short_name);
3114       while (NULL != (al = plug->addresses))
3115         {
3116           plug->addresses = al->next;
3117           GNUNET_free (al);
3118         }
3119       GNUNET_free (plug);
3120     }
3121   if (my_private_key != NULL)
3122     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3123   GNUNET_free_non_null (our_hello);
3124
3125   /* free 'chvc' data structure */
3126   while (NULL != (chvc = chvc_head))
3127     {
3128       chvc_head = chvc->next;
3129       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3130       GNUNET_free (chvc);
3131     }
3132   chvc_tail = NULL;
3133
3134   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3135                                          &abort_validation,
3136                                          NULL);
3137   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3138 }
3139
3140
3141 /**
3142  * Initiate transport service.
3143  *
3144  * @param cls closure
3145  * @param s scheduler to use
3146  * @param serv the initialized server
3147  * @param c configuration to use
3148  */
3149 static void
3150 run (void *cls,
3151      struct GNUNET_SCHEDULER_Handle *s,
3152      struct GNUNET_SERVER_Handle *serv,
3153      const struct GNUNET_CONFIGURATION_Handle *c)
3154 {
3155   char *plugs;
3156   char *pos;
3157   int no_transports;
3158   unsigned long long tneigh;
3159   char *keyfile;
3160
3161   sched = s;
3162   cfg = c;
3163   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3164   /* parse configuration */
3165   if ((GNUNET_OK !=
3166        GNUNET_CONFIGURATION_get_value_number (c,
3167                                               "TRANSPORT",
3168                                               "NEIGHBOUR_LIMIT",
3169                                               &tneigh)) ||
3170       (GNUNET_OK !=
3171        GNUNET_CONFIGURATION_get_value_filename (c,
3172                                                 "GNUNETD",
3173                                                 "HOSTKEY", &keyfile)))
3174     {
3175       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3176                   _
3177                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
3178       GNUNET_SCHEDULER_shutdown (s);
3179       return;
3180     }
3181   max_connect_per_transport = (uint32_t) tneigh;
3182   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3183   GNUNET_free (keyfile);
3184   if (my_private_key == NULL)
3185     {
3186       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3187                   _
3188                   ("Transport service could not access hostkey.  Exiting.\n"));
3189       GNUNET_SCHEDULER_shutdown (s);
3190       return;
3191     }
3192   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3193   GNUNET_CRYPTO_hash (&my_public_key,
3194                       sizeof (my_public_key), &my_identity.hashPubKey);
3195   /* setup notification */
3196   server = serv;
3197   GNUNET_SERVER_disconnect_notify (server,
3198                                    &client_disconnect_notification, NULL);
3199   /* load plugins... */
3200   no_transports = 1;
3201   if (GNUNET_OK ==
3202       GNUNET_CONFIGURATION_get_value_string (c,
3203                                              "TRANSPORT", "PLUGINS", &plugs))
3204     {
3205       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3206                   _("Starting transport plugins `%s'\n"), plugs);
3207       pos = strtok (plugs, " ");
3208       while (pos != NULL)
3209         {
3210           start_transport (server, pos);
3211           no_transports = 0;
3212           pos = strtok (NULL, " ");
3213         }
3214       GNUNET_free (plugs);
3215     }
3216   GNUNET_SCHEDULER_add_delayed (sched,
3217                                 GNUNET_TIME_UNIT_FOREVER_REL,
3218                                 &shutdown_task, NULL);
3219   if (no_transports)
3220     refresh_hello ();
3221
3222 #if DEBUG_TRANSPORT
3223   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3224 #endif
3225   /* process client requests */
3226   GNUNET_SERVER_add_handlers (server, handlers);
3227 }
3228
3229
3230 /**
3231  * The main function for the transport service.
3232  *
3233  * @param argc number of arguments from the command line
3234  * @param argv command line arguments
3235  * @return 0 ok, 1 on error
3236  */
3237 int
3238 main (int argc, char *const *argv)
3239 {
3240   return (GNUNET_OK ==
3241           GNUNET_SERVICE_run (argc,
3242                               argv,
3243                               "transport",
3244                               GNUNET_SERVICE_OPTION_NONE,
3245                               &run, NULL)) ? 0 : 1;
3246 }
3247
3248 /* end of gnunet-service-transport.c */