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