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