6f689100247e4cadb48cb5528924c6cba85769c3
[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"),
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   tp = find_transport (tname);
2281   if (tp == NULL)
2282     {
2283       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
2284                   GNUNET_ERROR_TYPE_BULK,
2285                   _
2286                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
2287                   tname);
2288       return GNUNET_OK;
2289     }
2290   GNUNET_HELLO_get_key (chvc->hello, &pk);
2291   GNUNET_CRYPTO_hash (&pk,
2292                       sizeof (struct
2293                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2294                       &id.hashPubKey);
2295   caec.addr = addr;
2296   caec.addrlen = addrlen;
2297   caec.tname = tname;
2298   caec.exists = GNUNET_NO;
2299   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2300                                          &check_address_exists,
2301                                          &caec);
2302   if (caec.exists == GNUNET_YES)
2303     {
2304       /* During validation attempts we will likely trigger the other
2305          peer trying to validate our address which in turn will cause
2306          it to send us its HELLO, so we expect to hit this case rather
2307          frequently.  Only print something if we are very verbose. */
2308 #if DEBUG_TRANSPORT > 1
2309       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2311                   GNUNET_a2s (addr, addrlen),
2312                   tname,
2313                   GNUNET_i2s (&id));
2314 #endif
2315       return GNUNET_OK;
2316     }
2317   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2318   va->transport_name = GNUNET_strdup (tname);
2319   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2320                                             (unsigned int) -1);
2321   va->send_time = GNUNET_TIME_absolute_get();
2322   va->addr = (const void*) &va[1];
2323   memcpy (&va[1], addr, addrlen);
2324   va->addrlen = addrlen;
2325   GNUNET_HELLO_get_key (chvc->hello,
2326                         &va->publicKey);
2327   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2328                                                    HELLO_VERIFICATION_TIMEOUT,
2329                                                    &timeout_hello_validation,
2330                                                    va);
2331   GNUNET_CONTAINER_multihashmap_put (validation_map,
2332                                      &id.hashPubKey,
2333                                      va,
2334                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2335   neighbour = find_neighbour(&id);
2336   if (neighbour == NULL)
2337     neighbour = setup_new_neighbour(&id);
2338   peer_address = add_peer_address(neighbour, tname, addr, addrlen);
2339   GNUNET_assert(peer_address != NULL);
2340   hello_size = GNUNET_HELLO_size(our_hello);
2341   tsize = sizeof(struct TransportPingMessage) + hello_size;
2342   message_buf = GNUNET_malloc(tsize);
2343   ping.challenge = htonl(va->challenge);
2344   ping.header.size = htons(sizeof(struct TransportPingMessage));
2345   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2346   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2347   memcpy(message_buf, our_hello, hello_size);
2348   memcpy(&message_buf[hello_size],
2349          &ping,
2350          sizeof(struct TransportPingMessage));
2351 #if DEBUG_TRANSPORT
2352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2353               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2354               GNUNET_a2s (addr, addrlen),
2355               tname,
2356               GNUNET_i2s (&id),
2357               "HELLO", hello_size,
2358               "PING", sizeof (struct TransportPingMessage));
2359 #endif
2360   transmit_to_peer (NULL, peer_address,
2361                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2362                     HELLO_VERIFICATION_TIMEOUT,
2363                     message_buf, tsize,
2364                     GNUNET_YES, neighbour);
2365   GNUNET_free(message_buf);
2366   return GNUNET_OK;
2367 }
2368
2369
2370 /**
2371  * Add the given address to the list of foreign addresses
2372  * available for the given peer (check for duplicates).
2373  *
2374  * @param cls the respective 'struct NeighbourList' to update
2375  * @param tname name of the transport
2376  * @param expiration expiration time
2377  * @param addr the address
2378  * @param addrlen length of the address
2379  * @return GNUNET_OK (always)
2380  */
2381 static int
2382 add_to_foreign_address_list (void *cls,
2383                              const char *tname,
2384                              struct GNUNET_TIME_Absolute expiration,
2385                              const void *addr, size_t addrlen)
2386 {
2387   struct NeighbourList *n = cls;
2388   struct ForeignAddressList *fal;
2389   int try;
2390
2391   try = GNUNET_NO;
2392   fal = find_peer_address (n, tname, addr, addrlen);
2393   if (fal == NULL)
2394     {
2395 #if DEBUG_TRANSPORT
2396       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397                   "Adding address `%s' (%s) for peer `%4s' due to peerinfo data for %llums.\n",
2398                   GNUNET_a2s (addr, addrlen),
2399                   tname,
2400                   GNUNET_i2s (&n->id),
2401                   expiration.value);
2402 #endif
2403       fal = add_peer_address (n, tname, addr, addrlen);
2404       try = GNUNET_YES;
2405     }
2406   if (fal == NULL)
2407     return GNUNET_OK;
2408   fal->expires = GNUNET_TIME_absolute_max (expiration,
2409                                            fal->expires);
2410   fal->validated = GNUNET_YES;  
2411   if (try == GNUNET_YES)
2412     try_transmission_to_peer (n);
2413   return GNUNET_OK;
2414 }
2415
2416
2417 /**
2418  * Check if addresses in validated hello "h" overlap with
2419  * those in "chvc->hello" and validate the rest.
2420  *
2421  * @param cls closure
2422  * @param peer id of the peer, NULL for last call
2423  * @param h hello message for the peer (can be NULL)
2424  * @param trust amount of trust we have in the peer (not used)
2425  */
2426 static void
2427 check_hello_validated (void *cls,
2428                        const struct GNUNET_PeerIdentity *peer,
2429                        const struct GNUNET_HELLO_Message *h, 
2430                        uint32_t trust)
2431 {
2432   struct CheckHelloValidatedContext *chvc = cls;
2433   struct GNUNET_HELLO_Message *plain_hello;
2434   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2435   struct GNUNET_PeerIdentity target;
2436   struct NeighbourList *n;
2437
2438   if (peer == NULL)
2439     {
2440       chvc->piter = NULL;
2441       GNUNET_CONTAINER_DLL_remove (chvc_head,
2442                                    chvc_tail,
2443                                    chvc);
2444       if (GNUNET_NO == chvc->hello_known)
2445         {
2446           /* notify PEERINFO about the peer now, so that we at least
2447              have the public key if some other component needs it */
2448           GNUNET_HELLO_get_key (chvc->hello, &pk);
2449           GNUNET_CRYPTO_hash (&pk,
2450                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2451                               &target.hashPubKey);
2452           plain_hello = GNUNET_HELLO_create (&pk,
2453                                              NULL, 
2454                                              NULL);
2455           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2456           GNUNET_free (plain_hello);
2457 #if DEBUG_TRANSPORT
2458           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2460                       "HELLO",
2461                       GNUNET_i2s (&target));
2462 #endif
2463           GNUNET_HELLO_iterate_addresses (chvc->hello,
2464                                           GNUNET_NO, 
2465                                           &run_validation, 
2466                                           chvc);
2467         }
2468       GNUNET_free (chvc);
2469       return;
2470     }
2471   if (h == NULL)
2472     return;
2473   chvc->hello_known = GNUNET_YES;
2474   n = find_neighbour (peer);
2475   if (n != NULL)
2476     {
2477       GNUNET_HELLO_iterate_addresses (h,
2478                                       GNUNET_NO,
2479                                       &add_to_foreign_address_list,
2480                                       n);
2481       try_transmission_to_peer (n);
2482     }
2483   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
2484                                       h,
2485                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
2486                                       &run_validation, 
2487                                       chvc);
2488 }
2489
2490 /**
2491  * Process HELLO-message.
2492  *
2493  * @param plugin transport involved, may be NULL
2494  * @param message the actual message
2495  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
2496  */
2497 static int
2498 process_hello (struct TransportPlugin *plugin,
2499                const struct GNUNET_MessageHeader *message)
2500 {
2501   uint16_t hsize;
2502   struct GNUNET_PeerIdentity target;
2503   const struct GNUNET_HELLO_Message *hello;
2504   struct CheckHelloValidatedContext *chvc;
2505   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
2506
2507   hsize = ntohs (message->size);
2508   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2509       (hsize < sizeof (struct GNUNET_MessageHeader)))
2510     {
2511       GNUNET_break (0);
2512       return GNUNET_SYSERR;
2513     }
2514   /* first, check if load is too high */
2515   if (GNUNET_SCHEDULER_get_load (sched,
2516                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
2517     {
2518       /* TODO: call to stats? */
2519       return GNUNET_OK;
2520     }
2521   hello = (const struct GNUNET_HELLO_Message *) message;
2522   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
2523     {
2524       GNUNET_break_op (0);
2525       return GNUNET_SYSERR;
2526     }
2527   GNUNET_CRYPTO_hash (&publicKey,
2528                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2529                       &target.hashPubKey);
2530 #if DEBUG_TRANSPORT > 1
2531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532               "Processing `%s' message for `%4s' of size %u\n",
2533               "HELLO", 
2534               GNUNET_i2s (&target), 
2535               GNUNET_HELLO_size(hello));
2536 #endif
2537   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
2538   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
2539   memcpy (&chvc[1], hello, hsize);
2540   GNUNET_CONTAINER_DLL_insert (chvc_head,
2541                                chvc_tail,
2542                                chvc);
2543   /* finally, check if HELLO was previously validated
2544      (continuation will then schedule actual validation) */
2545   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
2546                                          sched,
2547                                          &target,
2548                                          0,
2549                                          HELLO_VERIFICATION_TIMEOUT,
2550                                          &check_hello_validated, chvc);
2551   return GNUNET_OK;
2552 }
2553
2554
2555 /**
2556  * The peer specified by the given neighbour has timed-out or a plugin
2557  * has disconnected.  We may either need to do nothing (other plugins
2558  * still up), or trigger a full disconnect and clean up.  This
2559  * function updates our state and does the necessary notifications.
2560  * Also notifies our clients that the neighbour is now officially
2561  * gone.
2562  *
2563  * @param n the neighbour list entry for the peer
2564  * @param check should we just check if all plugins
2565  *        disconnected or must we ask all plugins to
2566  *        disconnect?
2567  */
2568 static void
2569 disconnect_neighbour (struct NeighbourList *n, int check)
2570 {
2571   struct ReadyList *rpos;
2572   struct NeighbourList *npos;
2573   struct NeighbourList *nprev;
2574   struct MessageQueue *mq;
2575   struct ForeignAddressList *peer_addresses;
2576   struct ForeignAddressList *peer_pos;
2577
2578   if (GNUNET_YES == check)
2579     {
2580       rpos = n->plugins;
2581       while (NULL != rpos)
2582         {
2583           peer_addresses = rpos->addresses;
2584           while (peer_addresses != NULL)
2585             {
2586               if (GNUNET_YES == peer_addresses->connected)
2587                 return;             /* still connected */
2588               peer_addresses = peer_addresses->next;
2589             }
2590           rpos = rpos->next;
2591         }
2592     }
2593 #if DEBUG_TRANSPORT
2594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2595               "Disconnecting from `%4s'\n",
2596               GNUNET_i2s (&n->id));
2597 #endif
2598   /* remove n from neighbours list */
2599   nprev = NULL;
2600   npos = neighbours;
2601   while ((npos != NULL) && (npos != n))
2602     {
2603       nprev = npos;
2604       npos = npos->next;
2605     }
2606   GNUNET_assert (npos != NULL);
2607   if (nprev == NULL)
2608     neighbours = n->next;
2609   else
2610     nprev->next = n->next;
2611
2612   /* notify all clients about disconnect */
2613   if (GNUNET_YES == n->received_pong)
2614     notify_clients_disconnect (&n->id);
2615
2616   /* clean up all plugins, cancel connections and pending transmissions */
2617   while (NULL != (rpos = n->plugins))
2618     {
2619       n->plugins = rpos->next;
2620       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
2621
2622       while (rpos->addresses != NULL)
2623         {
2624           peer_pos = rpos->addresses;
2625           rpos->addresses = peer_pos->next;
2626           GNUNET_free(peer_pos);
2627         }
2628       GNUNET_free (rpos);
2629     }
2630
2631   /* free all messages on the queue */
2632   while (NULL != (mq = n->messages_head))
2633     {
2634       GNUNET_CONTAINER_DLL_remove (n->messages_head,
2635                                    n->messages_tail,
2636                                    mq);
2637       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
2638                                  &n->id,
2639                                  sizeof(struct GNUNET_PeerIdentity)));
2640       GNUNET_free (mq);
2641     }
2642   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2643     {
2644       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2645       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2646     }
2647   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
2648     {
2649       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
2650       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
2651     }
2652   /* finally, free n itself */
2653   GNUNET_free (n);
2654 }
2655
2656
2657 /**
2658  * We have received a PING message from someone.  Need to send a PONG message
2659  * in response to the peer by any means necessary. 
2660  *
2661  * FIXME: With something like TCP where a connection exists, we may
2662  * want to send it that way.  But the current API does not seem to
2663  * allow us to do so (can't tell this to the transport!)
2664  */
2665 static int 
2666 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
2667             const struct GNUNET_PeerIdentity *peer,
2668             const char *sender_address,
2669             size_t sender_address_len)
2670 {
2671   struct TransportPlugin *plugin = cls;
2672   struct TransportPingMessage *ping;
2673   struct TransportPongMessage *pong;
2674   struct NeighbourList *n;
2675   struct ReadyList *rl;
2676   struct ForeignAddressList *fal;
2677
2678   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
2679     {
2680       GNUNET_break_op (0);
2681       return GNUNET_SYSERR;
2682     }
2683   ping = (struct TransportPingMessage *) message;
2684   if (0 != memcmp (&ping->target,
2685                    plugin->env.my_identity,
2686                    sizeof (struct GNUNET_PeerIdentity)))
2687     {
2688       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2689                   _("Received `%s' message not destined for me!\n"), 
2690                   "PING");
2691       return GNUNET_SYSERR;
2692     }
2693 #if DEBUG_TRANSPORT
2694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2695               "Processing `%s' from `%s'\n",
2696               "PING", 
2697               GNUNET_a2s ((const struct sockaddr *)sender_address, 
2698                           sender_address_len));
2699 #endif
2700   GNUNET_STATISTICS_update (stats,
2701                             gettext_noop ("# PING messages received"),
2702                             1,
2703                             GNUNET_NO);
2704   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
2705   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
2706   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
2707   pong->purpose.size =
2708     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2709            sizeof (uint32_t) +
2710            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
2711   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
2712   pong->challenge = ping->challenge;
2713   pong->addrlen = htons(sender_address_len);
2714   memcpy(&pong->signer, 
2715          &my_public_key, 
2716          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
2717   memcpy (&pong[1], sender_address, sender_address_len);
2718   GNUNET_assert (GNUNET_OK ==
2719                  GNUNET_CRYPTO_rsa_sign (my_private_key,
2720                                          &pong->purpose, &pong->signature));
2721
2722   n = find_neighbour(peer);
2723   if (n == NULL)
2724     n = setup_new_neighbour(peer);
2725   /* broadcast 'PONG' to all available addresses */
2726   rl = n->plugins;
2727   while (rl != NULL)
2728     {
2729       fal = rl->addresses;
2730       while (fal != NULL)
2731         {
2732           transmit_to_peer(NULL, fal,
2733                            TRANSPORT_PONG_PRIORITY, 
2734                            HELLO_VERIFICATION_TIMEOUT,
2735                            (const char *)pong, 
2736                            ntohs(pong->header.size), 
2737                            GNUNET_YES, 
2738                            n);
2739           fal = fal->next;
2740         }
2741       rl = rl->next;
2742     }
2743   GNUNET_free(pong);
2744   return GNUNET_OK;
2745 }
2746
2747
2748 /**
2749  * Function called by the plugin for each received message.
2750  * Update data volumes, possibly notify plugins about
2751  * reducing the rate at which they read from the socket
2752  * and generally forward to our receive callback.
2753  *
2754  * @param cls the "struct TransportPlugin *" we gave to the plugin
2755  * @param peer (claimed) identity of the other peer
2756  * @param message the message, NULL if we only care about
2757  *                learning about the delay until we should receive again
2758  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
2759  * @param sender_address binary address of the sender (if observed)
2760  * @param sender_address_len number of bytes in sender_address
2761  * @return how long the plugin should wait until receiving more data
2762  *         (plugins that do not support this, can ignore the return value)
2763  */
2764 static struct GNUNET_TIME_Relative
2765 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
2766                     const struct GNUNET_MessageHeader *message,
2767                     unsigned int distance, const char *sender_address,
2768                     size_t sender_address_len)
2769 {
2770   struct ReadyList *service_context;
2771   struct TransportPlugin *plugin = cls;
2772   struct TransportClient *cpos;
2773   struct InboundMessage *im;
2774   struct ForeignAddressList *peer_address;
2775   uint16_t msize;
2776   struct NeighbourList *n;
2777   struct GNUNET_TIME_Relative ret;
2778
2779   n = find_neighbour (peer);
2780   if (n == NULL)
2781     n = setup_new_neighbour (peer);    
2782   service_context = n->plugins;
2783   while ((service_context != NULL) && (plugin != service_context->plugin))
2784     service_context = service_context->next;
2785   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
2786   if (message != NULL)
2787     {
2788       peer_address = add_peer_address(n, 
2789                                       plugin->short_name,
2790                                       sender_address, 
2791                                       sender_address_len);  
2792       if (peer_address != NULL)
2793         {
2794           peer_address->distance = distance;
2795           if (peer_address->connected == GNUNET_NO)
2796             {
2797               peer_address->connected = GNUNET_YES;
2798               peer_address->connect_attempts++;
2799             }
2800           peer_address->timeout
2801             =
2802             GNUNET_TIME_relative_to_absolute
2803             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2804         }
2805       /* update traffic received amount ... */
2806       msize = ntohs (message->size);      
2807       GNUNET_STATISTICS_update (stats,
2808                                 gettext_noop ("# bytes received from other peers"),
2809                                 msize,
2810                                 GNUNET_NO);
2811       n->distance = distance;
2812       n->peer_timeout =
2813         GNUNET_TIME_relative_to_absolute
2814         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2815       GNUNET_SCHEDULER_cancel (sched,
2816                                n->timeout_task);
2817       n->timeout_task =
2818         GNUNET_SCHEDULER_add_delayed (sched,
2819                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2820                                       &neighbour_timeout_task, n);
2821       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2822         {
2823           /* dropping message due to frequent inbound volume violations! */
2824           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2825                       GNUNET_ERROR_TYPE_BULK,
2826                       _
2827                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
2828                       n->in_tracker.available_bytes_per_s__,
2829                       n->quota_violation_count);
2830           GNUNET_STATISTICS_update (stats,
2831                                     gettext_noop ("# bandwidth quota violations by other peers"),
2832                                     1,
2833                                     GNUNET_NO);
2834           return GNUNET_TIME_UNIT_MINUTES; /* minimum penalty, likely ignored (UDP...) */
2835         }
2836       switch (ntohs (message->type))
2837         {
2838         case GNUNET_MESSAGE_TYPE_HELLO:
2839           GNUNET_STATISTICS_update (stats,
2840                                     gettext_noop ("# HELLO messages received from other peers"),
2841                                     1,
2842                                     GNUNET_NO);
2843           process_hello (plugin, message);
2844           break;
2845         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
2846           handle_ping(plugin, message, peer, sender_address, sender_address_len);
2847           break;
2848         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
2849           handle_pong(plugin, message, peer, sender_address, sender_address_len);
2850           break;
2851         default:
2852 #if DEBUG_TRANSPORT
2853           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854                       "Received message of type %u from `%4s', sending to all clients.\n",
2855                       ntohs (message->type), GNUNET_i2s (peer));
2856 #endif
2857           if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
2858                                                               msize))
2859             n->quota_violation_count++;
2860           else 
2861             n->quota_violation_count = 0; /* back within limits */
2862           GNUNET_STATISTICS_update (stats,
2863                                     gettext_noop ("# payload received from other peers"),
2864                                     msize,
2865                                     GNUNET_NO);
2866           /* transmit message to all clients */
2867           im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2868           im->header.size = htons (sizeof (struct InboundMessage) + msize);
2869           im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2870           im->latency = GNUNET_TIME_relative_hton (n->latency);
2871           im->peer = *peer;
2872           memcpy (&im[1], message, msize);
2873           cpos = clients;
2874           while (cpos != NULL)
2875             {
2876               transmit_to_client (cpos, &im->header, GNUNET_YES);
2877               cpos = cpos->next;
2878             }
2879           GNUNET_free (im);
2880         }
2881     }  
2882   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
2883   if (ret.value > 0)
2884     {
2885       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2886                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
2887                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
2888                   (unsigned int) n->in_tracker.available_bytes_per_s__,
2889                   (unsigned long long) ret.value);
2890       GNUNET_STATISTICS_update (stats,
2891                                 gettext_noop ("# ms throttling suggested"),
2892                                 (int64_t) ret.value,
2893                                 GNUNET_NO);      
2894     }
2895   return ret;
2896 }
2897
2898
2899 /**
2900  * Handle START-message.  This is the first message sent to us
2901  * by any client which causes us to add it to our list.
2902  *
2903  * @param cls closure (always NULL)
2904  * @param client identification of the client
2905  * @param message the actual message
2906  */
2907 static void
2908 handle_start (void *cls,
2909               struct GNUNET_SERVER_Client *client,
2910               const struct GNUNET_MessageHeader *message)
2911 {
2912   struct TransportClient *c;
2913   struct ConnectInfoMessage cim;
2914   struct NeighbourList *n;
2915
2916 #if DEBUG_TRANSPORT
2917   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2918               "Received `%s' request from client\n", "START");
2919 #endif
2920   c = clients;
2921   while (c != NULL)
2922     {
2923       if (c->client == client)
2924         {
2925           /* client already on our list! */
2926           GNUNET_break (0);
2927           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2928           return;
2929         }
2930       c = c->next;
2931     }
2932   c = GNUNET_malloc (sizeof (struct TransportClient));
2933   c->next = clients;
2934   clients = c;
2935   c->client = client;
2936   if (our_hello != NULL)
2937     {
2938 #if DEBUG_TRANSPORT
2939       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2940                   "Sending our own `%s' to new client\n", "HELLO");
2941 #endif
2942       transmit_to_client (c,
2943                           (const struct GNUNET_MessageHeader *) our_hello,
2944                           GNUNET_NO);
2945       /* tell new client about all existing connections */
2946       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2947       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2948       n = neighbours; 
2949       while (n != NULL)
2950         {
2951           if (GNUNET_YES == n->received_pong)
2952             {
2953               cim.id = n->id;
2954               cim.latency = GNUNET_TIME_relative_hton (n->latency);
2955               cim.distance = htonl (n->distance);
2956               transmit_to_client (c, &cim.header, GNUNET_NO);
2957             }
2958             n = n->next;
2959         }
2960     }
2961   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2962 }
2963
2964
2965 /**
2966  * Handle HELLO-message.
2967  *
2968  * @param cls closure (always NULL)
2969  * @param client identification of the client
2970  * @param message the actual message
2971  */
2972 static void
2973 handle_hello (void *cls,
2974               struct GNUNET_SERVER_Client *client,
2975               const struct GNUNET_MessageHeader *message)
2976 {
2977   int ret;
2978
2979   ret = process_hello (NULL, message);
2980   GNUNET_SERVER_receive_done (client, ret);
2981 }
2982
2983
2984 /**
2985  * Handle SEND-message.
2986  *
2987  * @param cls closure (always NULL)
2988  * @param client identification of the client
2989  * @param message the actual message
2990  */
2991 static void
2992 handle_send (void *cls,
2993              struct GNUNET_SERVER_Client *client,
2994              const struct GNUNET_MessageHeader *message)
2995 {
2996   struct TransportClient *tc;
2997   struct NeighbourList *n;
2998   const struct OutboundMessage *obm;
2999   const struct GNUNET_MessageHeader *obmm;
3000   uint16_t size;
3001   uint16_t msize;
3002
3003   size = ntohs (message->size);
3004   if (size <
3005       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3006     {
3007       GNUNET_break (0);
3008       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3009       return;
3010     }
3011   GNUNET_STATISTICS_update (stats,
3012                             gettext_noop ("# payload received for other peers"),
3013                             size,
3014                             GNUNET_NO);      
3015   obm = (const struct OutboundMessage *) message;
3016 #if DEBUG_TRANSPORT
3017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3018               "Received `%s' request from client with target `%4s'\n",
3019               "SEND", GNUNET_i2s (&obm->peer));
3020 #endif
3021   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3022   msize = ntohs (obmm->size);
3023   if (size != msize + sizeof (struct OutboundMessage))
3024     {
3025       GNUNET_break (0);
3026       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3027       return;
3028     }
3029   n = find_neighbour (&obm->peer);
3030   if (n == NULL)
3031     n = setup_new_neighbour (&obm->peer);
3032   tc = clients;
3033   while ((tc != NULL) && (tc->client != client))
3034     tc = tc->next;
3035
3036 #if DEBUG_TRANSPORT
3037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3039               ntohs (obmm->size),
3040               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3041 #endif
3042   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
3043                     GNUNET_TIME_relative_ntoh (obm->timeout),
3044                     (char *)obmm, 
3045                     ntohs (obmm->size), GNUNET_NO, n);
3046   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3047 }
3048
3049
3050 /**
3051  * Handle SET_QUOTA-message.
3052  *
3053  * @param cls closure (always NULL)
3054  * @param client identification of the client
3055  * @param message the actual message
3056  */
3057 static void
3058 handle_set_quota (void *cls,
3059                   struct GNUNET_SERVER_Client *client,
3060                   const struct GNUNET_MessageHeader *message)
3061 {
3062   const struct QuotaSetMessage *qsm =
3063     (const struct QuotaSetMessage *) message;
3064   struct NeighbourList *n;
3065   
3066   GNUNET_STATISTICS_update (stats,
3067                             gettext_noop ("# SET QUOTA messages received"),
3068                             1,
3069                             GNUNET_NO);      
3070   n = find_neighbour (&qsm->peer);
3071   if (n == NULL)
3072     {
3073       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3074       GNUNET_STATISTICS_update (stats,
3075                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3076                                 1,
3077                                 GNUNET_NO);      
3078       return;
3079     }
3080 #if DEBUG_TRANSPORT
3081   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3082               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3083               "SET_QUOTA", 
3084               (unsigned int) ntohl (qsm->quota.value__),
3085               (unsigned int) n->in_tracker.available_bytes_per_s__,
3086               GNUNET_i2s (&qsm->peer));
3087 #endif
3088   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3089                                          qsm->quota);
3090   if (0 == ntohl (qsm->quota.value__)) 
3091     disconnect_neighbour (n, GNUNET_NO);    
3092   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3093 }
3094
3095
3096 static void
3097 transmit_address_to_client (void *cls, const char *address)
3098 {
3099   struct GNUNET_SERVER_TransmitContext *tc = cls;
3100   size_t slen;
3101
3102   if (NULL == address)
3103     slen = 0;
3104   else
3105     slen = strlen (address) + 1;
3106   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3107                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3108   if (NULL == address)
3109     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3110 }
3111
3112
3113 /**
3114  * Handle AddressLookup-message.
3115  *
3116  * @param cls closure (always NULL)
3117  * @param client identification of the client
3118  * @param message the actual message
3119  */
3120 static void
3121 handle_address_lookup (void *cls,
3122                        struct GNUNET_SERVER_Client *client,
3123                        const struct GNUNET_MessageHeader *message)
3124 {
3125   const struct AddressLookupMessage *alum;
3126   struct TransportPlugin *lsPlugin;
3127   const char *nameTransport;
3128   const char *address;
3129   uint16_t size;
3130   struct GNUNET_SERVER_TransmitContext *tc;
3131
3132   size = ntohs (message->size);
3133   if (size < sizeof (struct AddressLookupMessage))
3134     {
3135       GNUNET_break_op (0);
3136       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3137       return;
3138     }
3139   alum = (const struct AddressLookupMessage *) message;
3140   uint32_t addressLen = ntohl (alum->addrlen);
3141   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3142     {
3143       GNUNET_break_op (0);
3144       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3145       return;
3146     }
3147   address = (const char *) &alum[1];
3148   nameTransport = (const char *) &address[addressLen];
3149   if (nameTransport
3150       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3151     {
3152       GNUNET_break_op (0);
3153       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3154       return;
3155     }
3156   struct GNUNET_TIME_Absolute timeout =
3157     GNUNET_TIME_absolute_ntoh (alum->timeout);
3158   struct GNUNET_TIME_Relative rtimeout =
3159     GNUNET_TIME_absolute_get_remaining (timeout);
3160   lsPlugin = find_transport (nameTransport);
3161   if (NULL == lsPlugin)
3162     {
3163       tc = GNUNET_SERVER_transmit_context_create (client);
3164       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3165                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3166       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3167       return;
3168     }
3169   tc = GNUNET_SERVER_transmit_context_create (client);
3170   lsPlugin->api->address_pretty_printer (cls, nameTransport,
3171                                          address, addressLen, GNUNET_YES,
3172                                          rtimeout,
3173                                          &transmit_address_to_client, tc);
3174 }
3175
3176 /**
3177  * List of handlers for the messages understood by this
3178  * service.
3179  */
3180 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3181   {&handle_start, NULL,
3182    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3183   {&handle_hello, NULL,
3184    GNUNET_MESSAGE_TYPE_HELLO, 0},
3185   {&handle_send, NULL,
3186    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3187   {&handle_set_quota, NULL,
3188    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3189   {&handle_address_lookup, NULL,
3190    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3191    0},
3192   {NULL, NULL, 0, 0}
3193 };
3194
3195
3196 /**
3197  * Setup the environment for this plugin.
3198  */
3199 static void
3200 create_environment (struct TransportPlugin *plug)
3201 {
3202   plug->env.cfg = cfg;
3203   plug->env.sched = sched;
3204   plug->env.my_identity = &my_identity;
3205   plug->env.cls = plug;
3206   plug->env.receive = &plugin_env_receive;
3207   plug->env.notify_address = &plugin_env_notify_address;
3208   plug->env.max_connections = max_connect_per_transport;
3209   plug->env.stats = stats;
3210 }
3211
3212
3213 /**
3214  * Start the specified transport (load the plugin).
3215  */
3216 static void
3217 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
3218 {
3219   struct TransportPlugin *plug;
3220   char *libname;
3221
3222   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3223               _("Loading `%s' transport plugin\n"), name);
3224   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3225   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3226   create_environment (plug);
3227   plug->short_name = GNUNET_strdup (name);
3228   plug->lib_name = libname;
3229   plug->next = plugins;
3230   plugins = plug;
3231   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3232   if (plug->api == NULL)
3233     {
3234       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3235                   _("Failed to load transport plugin for `%s'\n"), name);
3236       GNUNET_free (plug->short_name);
3237       plugins = plug->next;
3238       GNUNET_free (libname);
3239       GNUNET_free (plug);
3240     }
3241 }
3242
3243
3244 /**
3245  * Called whenever a client is disconnected.  Frees our
3246  * resources associated with that client.
3247  *
3248  * @param cls closure
3249  * @param client identification of the client
3250  */
3251 static void
3252 client_disconnect_notification (void *cls,
3253                                 struct GNUNET_SERVER_Client *client)
3254 {
3255   struct TransportClient *pos;
3256   struct TransportClient *prev;
3257   struct ClientMessageQueueEntry *mqe;
3258
3259   if (client == NULL)
3260     return;
3261 #if DEBUG_TRANSPORT
3262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3263               "Client disconnected, cleaning up.\n");
3264 #endif
3265   prev = NULL;
3266   pos = clients;
3267   while ((pos != NULL) && (pos->client != client))
3268     {
3269       prev = pos;
3270       pos = pos->next;
3271     }
3272   if (pos == NULL)
3273     return;
3274   while (NULL != (mqe = pos->message_queue_head))
3275     {
3276       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3277                                    pos->message_queue_tail,
3278                                    mqe);
3279       pos->message_count--;
3280       GNUNET_free (mqe);
3281     }
3282   if (prev == NULL)
3283     clients = pos->next;
3284   else
3285     prev->next = pos->next;
3286   if (GNUNET_YES == pos->tcs_pending)
3287     {
3288       pos->client = NULL;
3289       return;
3290     }
3291   if (pos->th != NULL)
3292     {
3293       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3294       pos->th = NULL;
3295     }
3296   GNUNET_break (0 == pos->message_count);
3297   GNUNET_free (pos);
3298 }
3299
3300
3301 /**
3302  * Iterator to free entries in the validation_map.
3303  *
3304  * @param cls closure (unused)
3305  * @param key current key code
3306  * @param value value in the hash map (validation to abort)
3307  * @return GNUNET_YES (always)
3308  */
3309 static int 
3310 abort_validation (void *cls,
3311                   const GNUNET_HashCode * key,
3312                   void *value)
3313 {
3314   struct ValidationEntry *va = value;
3315
3316   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3317   GNUNET_free (va->transport_name);
3318   GNUNET_free (va);
3319   return GNUNET_YES;
3320 }
3321
3322
3323 /**
3324  * Function called when the service shuts down.  Unloads our plugins
3325  * and cancels pending validations.
3326  *
3327  * @param cls closure, unused
3328  * @param tc task context (unused)
3329  */
3330 static void
3331 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3332 {
3333   struct TransportPlugin *plug;
3334   struct OwnAddressList *al;
3335   struct CheckHelloValidatedContext *chvc;
3336
3337   while (neighbours != NULL)
3338     disconnect_neighbour (neighbours, GNUNET_NO);
3339 #if DEBUG_TRANSPORT
3340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3341               "Transport service is unloading plugins...\n");
3342 #endif
3343   while (NULL != (plug = plugins))
3344     {
3345       plugins = plug->next;
3346       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3347       GNUNET_free (plug->lib_name);
3348       GNUNET_free (plug->short_name);
3349       while (NULL != (al = plug->addresses))
3350         {
3351           plug->addresses = al->next;
3352           GNUNET_free (al);
3353         }
3354       GNUNET_free (plug);
3355     }
3356   if (my_private_key != NULL)
3357     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3358   GNUNET_free_non_null (our_hello);
3359
3360   /* free 'chvc' data structure */
3361   while (NULL != (chvc = chvc_head))
3362     {
3363       chvc_head = chvc->next;
3364       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3365       GNUNET_free (chvc);
3366     }
3367   chvc_tail = NULL;
3368
3369   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3370                                          &abort_validation,
3371                                          NULL);
3372   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3373   validation_map = NULL;
3374   if (stats != NULL)
3375     {
3376       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3377       stats = NULL;
3378     }
3379 }
3380
3381
3382 /**
3383  * Initiate transport service.
3384  *
3385  * @param cls closure
3386  * @param s scheduler to use
3387  * @param serv the initialized server
3388  * @param c configuration to use
3389  */
3390 static void
3391 run (void *cls,
3392      struct GNUNET_SCHEDULER_Handle *s,
3393      struct GNUNET_SERVER_Handle *serv,
3394      const struct GNUNET_CONFIGURATION_Handle *c)
3395 {
3396   char *plugs;
3397   char *pos;
3398   int no_transports;
3399   unsigned long long tneigh;
3400   char *keyfile;
3401
3402   sched = s;
3403   cfg = c;
3404   stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
3405   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
3406   /* parse configuration */
3407   if ((GNUNET_OK !=
3408        GNUNET_CONFIGURATION_get_value_number (c,
3409                                               "TRANSPORT",
3410                                               "NEIGHBOUR_LIMIT",
3411                                               &tneigh)) ||
3412       (GNUNET_OK !=
3413        GNUNET_CONFIGURATION_get_value_filename (c,
3414                                                 "GNUNETD",
3415                                                 "HOSTKEY", &keyfile)))
3416     {
3417       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3418                   _
3419                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
3420       GNUNET_SCHEDULER_shutdown (s);
3421       if (stats != NULL)
3422         {
3423           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3424           stats = NULL;
3425         }
3426       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3427       validation_map = NULL;
3428       return;
3429     }
3430   max_connect_per_transport = (uint32_t) tneigh;
3431   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3432   GNUNET_free (keyfile);
3433   if (my_private_key == NULL)
3434     {
3435       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3436                   _
3437                   ("Transport service could not access hostkey.  Exiting.\n"));
3438       GNUNET_SCHEDULER_shutdown (s);
3439       if (stats != NULL)
3440         {
3441           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3442           stats = NULL;
3443         }
3444       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3445       validation_map = NULL;
3446       return;
3447     }
3448   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3449   GNUNET_CRYPTO_hash (&my_public_key,
3450                       sizeof (my_public_key), &my_identity.hashPubKey);
3451   /* setup notification */
3452   server = serv;
3453   GNUNET_SERVER_disconnect_notify (server,
3454                                    &client_disconnect_notification, NULL);
3455   /* load plugins... */
3456   no_transports = 1;
3457   if (GNUNET_OK ==
3458       GNUNET_CONFIGURATION_get_value_string (c,
3459                                              "TRANSPORT", "PLUGINS", &plugs))
3460     {
3461       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3462                   _("Starting transport plugins `%s'\n"), plugs);
3463       pos = strtok (plugs, " ");
3464       while (pos != NULL)
3465         {
3466           start_transport (server, pos);
3467           no_transports = 0;
3468           pos = strtok (NULL, " ");
3469         }
3470       GNUNET_free (plugs);
3471     }
3472   GNUNET_SCHEDULER_add_delayed (sched,
3473                                 GNUNET_TIME_UNIT_FOREVER_REL,
3474                                 &shutdown_task, NULL);
3475   if (no_transports)
3476     refresh_hello ();
3477
3478 #if DEBUG_TRANSPORT
3479   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
3480 #endif
3481   /* process client requests */
3482   GNUNET_SERVER_add_handlers (server, handlers);
3483 }
3484
3485
3486 /**
3487  * The main function for the transport service.
3488  *
3489  * @param argc number of arguments from the command line
3490  * @param argv command line arguments
3491  * @return 0 ok, 1 on error
3492  */
3493 int
3494 main (int argc, char *const *argv)
3495 {
3496   return (GNUNET_OK ==
3497           GNUNET_SERVICE_run (argc,
3498                               argv,
3499                               "transport",
3500                               GNUNET_SERVICE_OPTION_NONE,
3501                               &run, NULL)) ? 0 : 1;
3502 }
3503
3504 /* end of gnunet-service-transport.c */