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.session = NULL;
2838   caec.tname = tname;
2839   caec.exists = GNUNET_NO;
2840   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
2841                                          &check_address_exists,
2842                                          &caec);
2843   if (caec.exists == GNUNET_YES)
2844     {
2845       /* During validation attempts we will likely trigger the other
2846          peer trying to validate our address which in turn will cause
2847          it to send us its HELLO, so we expect to hit this case rather
2848          frequently.  Only print something if we are very verbose. */
2849 #if DEBUG_TRANSPORT > 1
2850       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851                   "Validation of address `%s' via `%s' for peer `%4s' already in progress.\n",
2852                   GNUNET_a2s (addr, addrlen),
2853                   tname,
2854                   GNUNET_i2s (&id));
2855 #endif
2856       GNUNET_STATISTICS_update (stats,
2857                                 gettext_noop ("# peer addresses not validated (in progress)"),
2858                                 1,
2859                                 GNUNET_NO);      
2860       return GNUNET_OK;
2861     }
2862   va = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
2863   va->transport_name = GNUNET_strdup (tname);
2864   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2865                                             (unsigned int) -1);
2866   va->send_time = GNUNET_TIME_absolute_get();
2867   va->addr = (const void*) &va[1];
2868   memcpy (&va[1], addr, addrlen);
2869   va->addrlen = addrlen;
2870   GNUNET_HELLO_get_key (chvc->hello,
2871                         &va->publicKey);
2872   va->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
2873                                                    HELLO_VERIFICATION_TIMEOUT,
2874                                                    &timeout_hello_validation,
2875                                                    va);
2876   GNUNET_CONTAINER_multihashmap_put (validation_map,
2877                                      &id.hashPubKey,
2878                                      va,
2879                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2880   neighbour = find_neighbour(&id);
2881   if (neighbour == NULL)
2882     neighbour = setup_new_neighbour(&id);
2883   neighbour->publicKey = va->publicKey;
2884   neighbour->public_key_valid = GNUNET_YES;
2885   peer_address = add_peer_address (neighbour, tname, NULL, addr, addrlen);
2886   GNUNET_assert(peer_address != NULL);
2887   hello_size = GNUNET_HELLO_size(our_hello);
2888   tsize = sizeof(struct TransportPingMessage) + hello_size;
2889   message_buf = GNUNET_malloc(tsize);
2890   ping.challenge = htonl(va->challenge);
2891   ping.header.size = htons(sizeof(struct TransportPingMessage));
2892   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
2893   memcpy(&ping.target, &id, sizeof(struct GNUNET_PeerIdentity));
2894   memcpy(message_buf, our_hello, hello_size);
2895   memcpy(&message_buf[hello_size],
2896          &ping,
2897          sizeof(struct TransportPingMessage));
2898 #if DEBUG_TRANSPORT
2899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2900               "Performing validation of address `%s' via `%s' for peer `%4s' sending `%s' (%u bytes) and `%s' (%u bytes)\n",
2901               GNUNET_a2s (addr, addrlen),
2902               tname,
2903               GNUNET_i2s (&id),
2904               "HELLO", hello_size,
2905               "PING", sizeof (struct TransportPingMessage));
2906 #endif
2907   GNUNET_STATISTICS_update (stats,
2908                             gettext_noop ("# PING messages sent for initial validation"),
2909                             1,
2910                             GNUNET_NO);      
2911   transmit_to_peer (NULL, peer_address,
2912                     GNUNET_SCHEDULER_PRIORITY_DEFAULT,
2913                     HELLO_VERIFICATION_TIMEOUT,
2914                     message_buf, tsize,
2915                     GNUNET_YES, neighbour);
2916   GNUNET_free(message_buf);
2917   return GNUNET_OK;
2918 }
2919
2920
2921 /**
2922  * Check if addresses in validated hello "h" overlap with
2923  * those in "chvc->hello" and validate the rest.
2924  *
2925  * @param cls closure
2926  * @param peer id of the peer, NULL for last call
2927  * @param h hello message for the peer (can be NULL)
2928  * @param trust amount of trust we have in the peer (not used)
2929  */
2930 static void
2931 check_hello_validated (void *cls,
2932                        const struct GNUNET_PeerIdentity *peer,
2933                        const struct GNUNET_HELLO_Message *h, 
2934                        uint32_t trust)
2935 {
2936   struct CheckHelloValidatedContext *chvc = cls;
2937   struct GNUNET_HELLO_Message *plain_hello;
2938   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
2939   struct GNUNET_PeerIdentity target;
2940   struct NeighbourList *n;
2941
2942   if (peer == NULL)
2943     {
2944       chvc->piter = NULL;
2945       GNUNET_CONTAINER_DLL_remove (chvc_head,
2946                                    chvc_tail,
2947                                    chvc);
2948       if (GNUNET_NO == chvc->hello_known)
2949         {
2950           /* notify PEERINFO about the peer now, so that we at least
2951              have the public key if some other component needs it */
2952           GNUNET_HELLO_get_key (chvc->hello, &pk);
2953           GNUNET_CRYPTO_hash (&pk,
2954                               sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2955                               &target.hashPubKey);
2956           plain_hello = GNUNET_HELLO_create (&pk,
2957                                              NULL, 
2958                                              NULL);
2959           GNUNET_PEERINFO_add_peer (cfg, sched, &target, plain_hello);
2960           GNUNET_free (plain_hello);
2961 #if DEBUG_TRANSPORT
2962           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2963                       "Peerinfo had no `%s' message for peer `%4s', full validation needed.\n",
2964                       "HELLO",
2965                       GNUNET_i2s (&target));
2966 #endif
2967           GNUNET_STATISTICS_update (stats,
2968                                     gettext_noop ("# new HELLOs requiring full validation"),
2969                                     1,
2970                                     GNUNET_NO);      
2971           GNUNET_HELLO_iterate_addresses (chvc->hello,
2972                                           GNUNET_NO, 
2973                                           &run_validation, 
2974                                           chvc);
2975         }
2976       else
2977         {
2978           GNUNET_STATISTICS_update (stats,
2979                                     gettext_noop ("# duplicate HELLO (peer known)"),
2980                                     1,
2981                                     GNUNET_NO);      
2982         }
2983       GNUNET_free (chvc);
2984       return;
2985     } 
2986   if (h == NULL)
2987     return;
2988 #if DEBUG_TRANSPORT
2989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2990               "Peerinfo had `%s' message for peer `%4s', validating only new addresses.\n",
2991               "HELLO",
2992               GNUNET_i2s (peer));
2993 #endif
2994   chvc->hello_known = GNUNET_YES;
2995   n = find_neighbour (peer);
2996   if (n != NULL)
2997     {
2998       GNUNET_HELLO_iterate_addresses (h,
2999                                       GNUNET_NO,
3000                                       &add_to_foreign_address_list,
3001                                       n);
3002       try_transmission_to_peer (n);
3003     }
3004   else
3005     {
3006       GNUNET_STATISTICS_update (stats,
3007                                 gettext_noop ("# no existing neighbour record (validating HELLO)"),
3008                                 1,
3009                                 GNUNET_NO);      
3010     }
3011   GNUNET_STATISTICS_update (stats,
3012                             gettext_noop ("# HELLO validations (update case)"),
3013                             1,
3014                             GNUNET_NO);      
3015   GNUNET_HELLO_iterate_new_addresses (chvc->hello,
3016                                       h,
3017                                       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME),
3018                                       &run_validation, 
3019                                       chvc);
3020 }
3021
3022 /**
3023  * Process HELLO-message.
3024  *
3025  * @param plugin transport involved, may be NULL
3026  * @param message the actual message
3027  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
3028  */
3029 static int
3030 process_hello (struct TransportPlugin *plugin,
3031                const struct GNUNET_MessageHeader *message)
3032 {
3033   uint16_t hsize;
3034   struct GNUNET_PeerIdentity target;
3035   const struct GNUNET_HELLO_Message *hello;
3036   struct CheckHelloValidatedContext *chvc;
3037   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
3038
3039   hsize = ntohs (message->size);
3040   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
3041       (hsize < sizeof (struct GNUNET_MessageHeader)))
3042     {
3043       GNUNET_break (0);
3044       return GNUNET_SYSERR;
3045     }
3046   GNUNET_STATISTICS_update (stats,
3047                             gettext_noop ("# HELLOs received for validation"),
3048                             1,
3049                             GNUNET_NO);      
3050   /* first, check if load is too high */
3051   if (GNUNET_SCHEDULER_get_load (sched,
3052                                  GNUNET_SCHEDULER_PRIORITY_BACKGROUND) > MAX_HELLO_LOAD)
3053     {
3054       GNUNET_STATISTICS_update (stats,
3055                                 gettext_noop ("# HELLOs ignored due to high load"),
3056                                 1,
3057                                 GNUNET_NO);      
3058       return GNUNET_OK;
3059     }
3060   hello = (const struct GNUNET_HELLO_Message *) message;
3061   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
3062     {
3063       GNUNET_break_op (0);
3064       return GNUNET_SYSERR;
3065     }
3066   GNUNET_CRYPTO_hash (&publicKey,
3067                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3068                       &target.hashPubKey);
3069   if (0 == memcmp (&my_identity,
3070                    &target,
3071                    sizeof (struct GNUNET_PeerIdentity)))
3072     {
3073       GNUNET_STATISTICS_update (stats,
3074                                 gettext_noop ("# HELLOs ignored for validation (is my own HELLO)"),
3075                                 1,
3076                                 GNUNET_NO);      
3077       return GNUNET_OK;      
3078     }
3079 #if DEBUG_TRANSPORT > 1
3080   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3081               "Processing `%s' message for `%4s' of size %u\n",
3082               "HELLO", 
3083               GNUNET_i2s (&target), 
3084               GNUNET_HELLO_size(hello));
3085 #endif
3086   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
3087   chvc->hello = (const struct GNUNET_HELLO_Message *) &chvc[1];
3088   memcpy (&chvc[1], hello, hsize);
3089   GNUNET_CONTAINER_DLL_insert (chvc_head,
3090                                chvc_tail,
3091                                chvc);
3092   /* finally, check if HELLO was previously validated
3093      (continuation will then schedule actual validation) */
3094   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
3095                                          sched,
3096                                          &target,
3097                                          0,
3098                                          HELLO_VERIFICATION_TIMEOUT,
3099                                          &check_hello_validated, chvc);
3100   return GNUNET_OK;
3101 }
3102
3103
3104 /**
3105  * The peer specified by the given neighbour has timed-out or a plugin
3106  * has disconnected.  We may either need to do nothing (other plugins
3107  * still up), or trigger a full disconnect and clean up.  This
3108  * function updates our state and does the necessary notifications.
3109  * Also notifies our clients that the neighbour is now officially
3110  * gone.
3111  *
3112  * @param n the neighbour list entry for the peer
3113  * @param check should we just check if all plugins
3114  *        disconnected or must we ask all plugins to
3115  *        disconnect?
3116  */
3117 static void
3118 disconnect_neighbour (struct NeighbourList *n, int check)
3119 {
3120   struct ReadyList *rpos;
3121   struct NeighbourList *npos;
3122   struct NeighbourList *nprev;
3123   struct MessageQueue *mq;
3124   struct ForeignAddressList *peer_addresses;
3125   struct ForeignAddressList *peer_pos;
3126
3127   if (GNUNET_YES == check)
3128     {
3129       rpos = n->plugins;
3130       while (NULL != rpos)
3131         {
3132           peer_addresses = rpos->addresses;
3133           while (peer_addresses != NULL)
3134             {
3135               if (GNUNET_YES == peer_addresses->connected)
3136                 return;             /* still connected */
3137               peer_addresses = peer_addresses->next;
3138             }
3139           rpos = rpos->next;
3140         }
3141     }
3142 #if DEBUG_TRANSPORT
3143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3144               "Disconnecting from `%4s'\n",
3145               GNUNET_i2s (&n->id));
3146 #endif
3147   /* remove n from neighbours list */
3148   nprev = NULL;
3149   npos = neighbours;
3150   while ((npos != NULL) && (npos != n))
3151     {
3152       nprev = npos;
3153       npos = npos->next;
3154     }
3155   GNUNET_assert (npos != NULL);
3156   if (nprev == NULL)
3157     neighbours = n->next;
3158   else
3159     nprev->next = n->next;
3160
3161   /* notify all clients about disconnect */
3162   if (GNUNET_YES == n->received_pong)
3163     notify_clients_disconnect (&n->id);
3164
3165   /* clean up all plugins, cancel connections and pending transmissions */
3166   while (NULL != (rpos = n->plugins))
3167     {
3168       n->plugins = rpos->next;
3169       rpos->plugin->api->disconnect (rpos->plugin->api->cls, &n->id);
3170       while (rpos->addresses != NULL)
3171         {
3172           peer_pos = rpos->addresses;
3173           rpos->addresses = peer_pos->next;
3174           if (peer_pos->connected == GNUNET_YES)
3175             GNUNET_STATISTICS_update (stats,
3176                                       gettext_noop ("# connected addresses"),
3177                                       -1,
3178                                       GNUNET_NO); 
3179           if (GNUNET_YES == peer_pos->validated)
3180             GNUNET_STATISTICS_update (stats,
3181                                       gettext_noop ("# peer addresses considered valid"),
3182                                       -1,
3183                                       GNUNET_NO);      
3184           if (GNUNET_SCHEDULER_NO_TASK != peer_pos->revalidate_task)
3185             {
3186               GNUNET_SCHEDULER_cancel (sched,
3187                                        peer_pos->revalidate_task);
3188               peer_pos->revalidate_task = GNUNET_SCHEDULER_NO_TASK;
3189             }
3190           GNUNET_free(peer_pos);
3191         }
3192       GNUNET_free (rpos);
3193     }
3194
3195   /* free all messages on the queue */
3196   while (NULL != (mq = n->messages_head))
3197     {
3198       GNUNET_STATISTICS_update (stats,
3199                                 gettext_noop ("# bytes in message queue for other peers"),
3200                                 - (int64_t) mq->message_buf_size,
3201                                 GNUNET_NO);
3202       GNUNET_STATISTICS_update (stats,
3203                                 gettext_noop ("# bytes discarded due to disconnect"),
3204                                 mq->message_buf_size,
3205                                 GNUNET_NO);
3206       GNUNET_CONTAINER_DLL_remove (n->messages_head,
3207                                    n->messages_tail,
3208                                    mq);
3209       GNUNET_assert (0 == memcmp(&mq->neighbour_id, 
3210                                  &n->id,
3211                                  sizeof(struct GNUNET_PeerIdentity)));
3212       GNUNET_free (mq);
3213     }
3214   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
3215     {
3216       GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
3217       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3218     }
3219   if (n->retry_task != GNUNET_SCHEDULER_NO_TASK)
3220     {
3221       GNUNET_SCHEDULER_cancel (sched, n->retry_task);
3222       n->retry_task = GNUNET_SCHEDULER_NO_TASK;
3223     }
3224   if (n->piter != NULL)
3225     {
3226       GNUNET_PEERINFO_iterate_cancel (n->piter);
3227       n->piter = NULL;
3228     }
3229   /* finally, free n itself */
3230   GNUNET_STATISTICS_update (stats,
3231                             gettext_noop ("# active neighbours"),
3232                             -1,
3233                             GNUNET_NO);
3234   GNUNET_free_non_null (n->pre_connect_message_buffer);
3235   GNUNET_free (n);
3236 }
3237
3238
3239 /**
3240  * We have received a PING message from someone.  Need to send a PONG message
3241  * in response to the peer by any means necessary. 
3242  */
3243 static int 
3244 handle_ping(void *cls, const struct GNUNET_MessageHeader *message,
3245             const struct GNUNET_PeerIdentity *peer,
3246             const char *sender_address,
3247             size_t sender_address_len)
3248 {
3249   struct TransportPlugin *plugin = cls;
3250   struct TransportPingMessage *ping;
3251   struct TransportPongMessage *pong;
3252   struct NeighbourList *n;
3253   struct ReadyList *rl;
3254   struct ForeignAddressList *fal;
3255
3256   if (ntohs (message->size) != sizeof (struct TransportPingMessage))
3257     {
3258       GNUNET_break_op (0);
3259       return GNUNET_SYSERR;
3260     }
3261   ping = (struct TransportPingMessage *) message;
3262   if (0 != memcmp (&ping->target,
3263                    plugin->env.my_identity,
3264                    sizeof (struct GNUNET_PeerIdentity)))
3265     {
3266       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3267                   _("Received `%s' message not destined for me!\n"), 
3268                   "PING");
3269       return GNUNET_SYSERR;
3270     }
3271 #if DEBUG_TRANSPORT
3272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3273               "Processing `%s' from `%s'\n",
3274               "PING", 
3275               (sender_address != NULL) 
3276               ? GNUNET_a2s ((const struct sockaddr *)sender_address, 
3277                             sender_address_len)
3278               : "<inbound>");
3279 #endif
3280   GNUNET_STATISTICS_update (stats,
3281                             gettext_noop ("# PING messages received"),
3282                             1,
3283                             GNUNET_NO);
3284   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + sender_address_len);
3285   pong->header.size = htons (sizeof (struct TransportPongMessage) + sender_address_len);
3286   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
3287   pong->purpose.size =
3288     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3289            sizeof (uint32_t) +
3290            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sender_address_len);
3291   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PING);
3292   pong->challenge = ping->challenge;
3293   pong->addrlen = htons(sender_address_len);
3294   memcpy(&pong->signer, 
3295          &my_public_key, 
3296          sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
3297   if (sender_address != NULL)
3298     memcpy (&pong[1], sender_address, sender_address_len);
3299   GNUNET_assert (GNUNET_OK ==
3300                  GNUNET_CRYPTO_rsa_sign (my_private_key,
3301                                          &pong->purpose, &pong->signature));
3302   n = find_neighbour(peer);
3303   GNUNET_assert (n != NULL);
3304   /* first try reliable response transmission */
3305   rl = n->plugins;
3306   while (rl != NULL)
3307     {
3308       fal = rl->addresses;
3309       while (fal != NULL)
3310         {
3311           if (-1 != rl->plugin->api->send (rl->plugin->api->cls,
3312                                            peer,
3313                                            (const char*) pong,
3314                                            ntohs (pong->header.size),
3315                                            TRANSPORT_PONG_PRIORITY, 
3316                                            HELLO_VERIFICATION_TIMEOUT,
3317                                            fal->session,
3318                                            fal->addr,
3319                                            fal->addrlen,
3320                                            GNUNET_SYSERR,
3321                                            NULL, NULL))
3322             {
3323               /* done! */
3324               GNUNET_STATISTICS_update (stats,
3325                                         gettext_noop ("# PONGs unicast via reliable transport"),
3326                                         1,
3327                                         GNUNET_NO);      
3328               GNUNET_free (pong);
3329               return GNUNET_OK;
3330             }
3331           fal = fal->next;
3332         }
3333       rl = rl->next;
3334     }
3335   /* no reliable method found, do multicast */
3336   GNUNET_STATISTICS_update (stats,
3337                             gettext_noop ("# PONGs multicast to all available addresses"),
3338                             1,
3339                             GNUNET_NO);      
3340   rl = n->plugins;
3341   while (rl != NULL)
3342     {
3343       fal = rl->addresses;
3344       while (fal != NULL)
3345         {
3346           transmit_to_peer(NULL, fal,
3347                            TRANSPORT_PONG_PRIORITY, 
3348                            HELLO_VERIFICATION_TIMEOUT,
3349                            (const char *)pong, 
3350                            ntohs(pong->header.size), 
3351                            GNUNET_YES, 
3352                            n);
3353           fal = fal->next;
3354         }
3355       rl = rl->next;
3356     }
3357   GNUNET_free(pong);
3358   return GNUNET_OK;
3359 }
3360
3361
3362 /**
3363  * Function called by the plugin for each received message.
3364  * Update data volumes, possibly notify plugins about
3365  * reducing the rate at which they read from the socket
3366  * and generally forward to our receive callback.
3367  *
3368  * @param cls the "struct TransportPlugin *" we gave to the plugin
3369  * @param peer (claimed) identity of the other peer
3370  * @param message the message, NULL if we only care about
3371  *                learning about the delay until we should receive again
3372  * @param distance in overlay hops; use 1 unless DV (or 0 if message == NULL)
3373  * @param session identifier used for this session (can be NULL)
3374  * @param sender_address binary address of the sender (if observed)
3375  * @param sender_address_len number of bytes in sender_address
3376  * @return how long the plugin should wait until receiving more data
3377  *         (plugins that do not support this, can ignore the return value)
3378  */
3379 static struct GNUNET_TIME_Relative
3380 plugin_env_receive (void *cls, const struct GNUNET_PeerIdentity *peer,
3381                     const struct GNUNET_MessageHeader *message,
3382                     unsigned int distance,
3383                     struct Session *session,
3384                     const char *sender_address,
3385                     size_t sender_address_len)
3386 {
3387   struct TransportPlugin *plugin = cls;
3388   struct ReadyList *service_context;
3389   struct ForeignAddressList *peer_address;
3390   uint16_t msize;
3391   struct NeighbourList *n;
3392   struct GNUNET_TIME_Relative ret;
3393
3394   n = find_neighbour (peer);
3395   if (n == NULL)
3396     n = setup_new_neighbour (peer);
3397   service_context = n->plugins;
3398   while ((service_context != NULL) && (plugin != service_context->plugin))
3399     service_context = service_context->next;
3400   GNUNET_assert ((plugin->api->send == NULL) || (service_context != NULL));
3401   peer_address = NULL;
3402   if (message != NULL)
3403     {
3404       if ( (session != NULL) ||
3405            (sender_address != NULL) )
3406         peer_address = add_peer_address (n, 
3407                                          plugin->short_name,
3408                                          session,
3409                                          sender_address, 
3410                                          sender_address_len);  
3411       if (peer_address != NULL)
3412         {
3413           peer_address->distance = distance;
3414           if (GNUNET_YES == peer_address->validated)
3415             mark_address_connected (peer_address);
3416           peer_address->timeout
3417             =
3418             GNUNET_TIME_relative_to_absolute
3419             (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3420           schedule_next_ping (peer_address);
3421         }
3422       /* update traffic received amount ... */
3423       msize = ntohs (message->size);      
3424       GNUNET_STATISTICS_update (stats,
3425                                 gettext_noop ("# bytes received from other peers"),
3426                                 msize,
3427                                 GNUNET_NO);
3428       n->distance = distance;
3429       n->peer_timeout =
3430         GNUNET_TIME_relative_to_absolute
3431         (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3432       GNUNET_SCHEDULER_cancel (sched,
3433                                n->timeout_task);
3434       n->timeout_task =
3435         GNUNET_SCHEDULER_add_delayed (sched,
3436                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3437                                       &neighbour_timeout_task, n);
3438       if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
3439         {
3440           /* dropping message due to frequent inbound volume violations! */
3441           GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
3442                       GNUNET_ERROR_TYPE_BULK,
3443                       _
3444                       ("Dropping incoming message due to repeated bandwidth quota (%u b/s) violations (total of %u).\n"), 
3445                       n->in_tracker.available_bytes_per_s__,
3446                       n->quota_violation_count);
3447           GNUNET_STATISTICS_update (stats,
3448                                     gettext_noop ("# bandwidth quota violations by other peers"),
3449                                     1,
3450                                     GNUNET_NO);
3451           return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
3452         }
3453       switch (ntohs (message->type))
3454         {
3455         case GNUNET_MESSAGE_TYPE_HELLO:
3456           GNUNET_STATISTICS_update (stats,
3457                                     gettext_noop ("# HELLO messages received from other peers"),
3458                                     1,
3459                                     GNUNET_NO);
3460           process_hello (plugin, message);
3461           break;
3462         case GNUNET_MESSAGE_TYPE_TRANSPORT_PING:
3463           handle_ping (plugin, message, peer, sender_address, sender_address_len);
3464           break;
3465         case GNUNET_MESSAGE_TYPE_TRANSPORT_PONG:
3466           handle_pong (plugin, message, peer, sender_address, sender_address_len);
3467           break;
3468         default:
3469           handle_payload_message (message, n);
3470           break;
3471         }
3472     }  
3473   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
3474   if (ret.value > 0)
3475     {
3476       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3477                   "Throttling read (%llu bytes excess at %u b/s), waiting %llums before reading more.\n",
3478                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
3479                   (unsigned int) n->in_tracker.available_bytes_per_s__,
3480                   (unsigned long long) ret.value);
3481       GNUNET_STATISTICS_update (stats,
3482                                 gettext_noop ("# ms throttling suggested"),
3483                                 (int64_t) ret.value,
3484                                 GNUNET_NO);      
3485     }
3486   return ret;
3487 }
3488
3489
3490 /**
3491  * Handle START-message.  This is the first message sent to us
3492  * by any client which causes us to add it to our list.
3493  *
3494  * @param cls closure (always NULL)
3495  * @param client identification of the client
3496  * @param message the actual message
3497  */
3498 static void
3499 handle_start (void *cls,
3500               struct GNUNET_SERVER_Client *client,
3501               const struct GNUNET_MessageHeader *message)
3502 {
3503   struct TransportClient *c;
3504   struct ConnectInfoMessage cim;
3505   struct NeighbourList *n;
3506
3507 #if DEBUG_TRANSPORT
3508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3509               "Received `%s' request from client\n", "START");
3510 #endif
3511   c = clients;
3512   while (c != NULL)
3513     {
3514       if (c->client == client)
3515         {
3516           /* client already on our list! */
3517           GNUNET_break (0);
3518           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3519           return;
3520         }
3521       c = c->next;
3522     }
3523   c = GNUNET_malloc (sizeof (struct TransportClient));
3524   c->next = clients;
3525   clients = c;
3526   c->client = client;
3527   if (our_hello != NULL)
3528     {
3529 #if DEBUG_TRANSPORT
3530       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3531                   "Sending our own `%s' to new client\n", "HELLO");
3532 #endif
3533       transmit_to_client (c,
3534                           (const struct GNUNET_MessageHeader *) our_hello,
3535                           GNUNET_NO);
3536       /* tell new client about all existing connections */
3537       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
3538       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
3539       n = neighbours; 
3540       while (n != NULL)
3541         {
3542           if (GNUNET_YES == n->received_pong)
3543             {
3544               cim.id = n->id;
3545               cim.latency = GNUNET_TIME_relative_hton (n->latency);
3546               cim.distance = htonl (n->distance);
3547               transmit_to_client (c, &cim.header, GNUNET_NO);
3548             }
3549             n = n->next;
3550         }
3551     }
3552   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3553 }
3554
3555
3556 /**
3557  * Handle HELLO-message.
3558  *
3559  * @param cls closure (always NULL)
3560  * @param client identification of the client
3561  * @param message the actual message
3562  */
3563 static void
3564 handle_hello (void *cls,
3565               struct GNUNET_SERVER_Client *client,
3566               const struct GNUNET_MessageHeader *message)
3567 {
3568   int ret;
3569
3570   GNUNET_STATISTICS_update (stats,
3571                             gettext_noop ("# HELLOs received from clients"),
3572                             1,
3573                             GNUNET_NO);      
3574   ret = process_hello (NULL, message);
3575   GNUNET_SERVER_receive_done (client, ret);
3576 }
3577
3578
3579 /**
3580  * Handle SEND-message.
3581  *
3582  * @param cls closure (always NULL)
3583  * @param client identification of the client
3584  * @param message the actual message
3585  */
3586 static void
3587 handle_send (void *cls,
3588              struct GNUNET_SERVER_Client *client,
3589              const struct GNUNET_MessageHeader *message)
3590 {
3591   struct TransportClient *tc;
3592   struct NeighbourList *n;
3593   const struct OutboundMessage *obm;
3594   const struct GNUNET_MessageHeader *obmm;
3595   uint16_t size;
3596   uint16_t msize;
3597
3598   size = ntohs (message->size);
3599   if (size <
3600       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
3601     {
3602       GNUNET_break (0);
3603       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3604       return;
3605     }
3606   GNUNET_STATISTICS_update (stats,
3607                             gettext_noop ("# payload received for other peers"),
3608                             size,
3609                             GNUNET_NO);      
3610   obm = (const struct OutboundMessage *) message;
3611 #if DEBUG_TRANSPORT
3612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3613               "Received `%s' request from client with target `%4s'\n",
3614               "SEND", GNUNET_i2s (&obm->peer));
3615 #endif
3616   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
3617   msize = ntohs (obmm->size);
3618   if (size != msize + sizeof (struct OutboundMessage))
3619     {
3620       GNUNET_break (0);
3621       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3622       return;
3623     }
3624   n = find_neighbour (&obm->peer);
3625   if (n == NULL)
3626     n = setup_new_neighbour (&obm->peer);
3627   tc = clients;
3628   while ((tc != NULL) && (tc->client != client))
3629     tc = tc->next;
3630
3631 #if DEBUG_TRANSPORT
3632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3633               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
3634               ntohs (obmm->size),
3635               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
3636 #endif
3637   transmit_to_peer (tc, NULL, ntohl (obm->priority), 
3638                     GNUNET_TIME_relative_ntoh (obm->timeout),
3639                     (char *)obmm, 
3640                     ntohs (obmm->size), GNUNET_NO, n);
3641   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3642 }
3643
3644
3645 /**
3646  * Handle SET_QUOTA-message.
3647  *
3648  * @param cls closure (always NULL)
3649  * @param client identification of the client
3650  * @param message the actual message
3651  */
3652 static void
3653 handle_set_quota (void *cls,
3654                   struct GNUNET_SERVER_Client *client,
3655                   const struct GNUNET_MessageHeader *message)
3656 {
3657   const struct QuotaSetMessage *qsm =
3658     (const struct QuotaSetMessage *) message;
3659   struct NeighbourList *n;
3660   
3661   GNUNET_STATISTICS_update (stats,
3662                             gettext_noop ("# SET QUOTA messages received"),
3663                             1,
3664                             GNUNET_NO);      
3665   n = find_neighbour (&qsm->peer);
3666   if (n == NULL)
3667     {
3668       GNUNET_SERVER_receive_done (client, GNUNET_OK);
3669       GNUNET_STATISTICS_update (stats,
3670                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
3671                                 1,
3672                                 GNUNET_NO);      
3673       return;
3674     }
3675 #if DEBUG_TRANSPORT
3676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3677               "Received `%s' request (new quota %u, old quota %u) from client for peer `%4s'\n",
3678               "SET_QUOTA", 
3679               (unsigned int) ntohl (qsm->quota.value__),
3680               (unsigned int) n->in_tracker.available_bytes_per_s__,
3681               GNUNET_i2s (&qsm->peer));
3682 #endif
3683   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
3684                                          qsm->quota);
3685   if (0 == ntohl (qsm->quota.value__)) 
3686     disconnect_neighbour (n, GNUNET_NO);    
3687   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3688 }
3689
3690
3691 /**
3692  * Take the given address and append it to the set of results send back to
3693  * the client.
3694  * 
3695  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
3696  * @param address the resolved name, NULL to indicate the last response
3697  */
3698 static void
3699 transmit_address_to_client (void *cls, const char *address)
3700 {
3701   struct GNUNET_SERVER_TransmitContext *tc = cls;
3702   size_t slen;
3703
3704   if (NULL == address)
3705     slen = 0;
3706   else
3707     slen = strlen (address) + 1;
3708   GNUNET_SERVER_transmit_context_append_data (tc, address, slen,
3709                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3710   if (NULL == address)
3711     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
3712 }
3713
3714
3715 /**
3716  * Handle AddressLookup-message.
3717  *
3718  * @param cls closure (always NULL)
3719  * @param client identification of the client
3720  * @param message the actual message
3721  */
3722 static void
3723 handle_address_lookup (void *cls,
3724                        struct GNUNET_SERVER_Client *client,
3725                        const struct GNUNET_MessageHeader *message)
3726 {
3727   const struct AddressLookupMessage *alum;
3728   struct TransportPlugin *lsPlugin;
3729   const char *nameTransport;
3730   const char *address;
3731   uint16_t size;
3732   struct GNUNET_SERVER_TransmitContext *tc;
3733   struct GNUNET_TIME_Absolute timeout;
3734   struct GNUNET_TIME_Relative rtimeout;
3735   int32_t numeric;
3736
3737   size = ntohs (message->size);
3738   if (size < sizeof (struct AddressLookupMessage))
3739     {
3740       GNUNET_break_op (0);
3741       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3742       return;
3743     }
3744   alum = (const struct AddressLookupMessage *) message;
3745   uint32_t addressLen = ntohl (alum->addrlen);
3746   if (size <= sizeof (struct AddressLookupMessage) + addressLen)
3747     {
3748       GNUNET_break_op (0);
3749       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3750       return;
3751     }
3752   address = (const char *) &alum[1];
3753   nameTransport = (const char *) &address[addressLen];
3754   if (nameTransport
3755       [size - sizeof (struct AddressLookupMessage) - addressLen - 1] != '\0')
3756     {
3757       GNUNET_break_op (0);
3758       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3759       return;
3760     }
3761   timeout = GNUNET_TIME_absolute_ntoh (alum->timeout);
3762   rtimeout = GNUNET_TIME_absolute_get_remaining (timeout);
3763   numeric = ntohl (alum->numeric_only);
3764   lsPlugin = find_transport (nameTransport);
3765   if (NULL == lsPlugin)
3766     {
3767       tc = GNUNET_SERVER_transmit_context_create (client);
3768       GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
3769                                                   GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
3770       GNUNET_SERVER_transmit_context_run (tc, rtimeout);
3771       return;
3772     }
3773   tc = GNUNET_SERVER_transmit_context_create (client);
3774   lsPlugin->api->address_pretty_printer (lsPlugin->api->cls,
3775                                          nameTransport,
3776                                          address, addressLen, 
3777                                          numeric,
3778                                          rtimeout,
3779                                          &transmit_address_to_client, tc);
3780 }
3781
3782 /**
3783  * List of handlers for the messages understood by this
3784  * service.
3785  */
3786 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3787   {&handle_start, NULL,
3788    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
3789   {&handle_hello, NULL,
3790    GNUNET_MESSAGE_TYPE_HELLO, 0},
3791   {&handle_send, NULL,
3792    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
3793   {&handle_set_quota, NULL,
3794    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
3795   {&handle_address_lookup, NULL,
3796    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
3797    0},
3798   {NULL, NULL, 0, 0}
3799 };
3800
3801
3802 /**
3803  * Setup the environment for this plugin.
3804  */
3805 static void
3806 create_environment (struct TransportPlugin *plug)
3807 {
3808   plug->env.cfg = cfg;
3809   plug->env.sched = sched;
3810   plug->env.my_identity = &my_identity;
3811   plug->env.cls = plug;
3812   plug->env.receive = &plugin_env_receive;
3813   plug->env.notify_address = &plugin_env_notify_address;
3814   plug->env.session_end = &plugin_env_session_end;
3815   plug->env.max_connections = max_connect_per_transport;
3816   plug->env.stats = stats;
3817 }
3818
3819
3820 /**
3821  * Start the specified transport (load the plugin).
3822  */
3823 static void
3824 start_transport (struct GNUNET_SERVER_Handle *server, 
3825                  const char *name)
3826 {
3827   struct TransportPlugin *plug;
3828   char *libname;
3829
3830   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3831               _("Loading `%s' transport plugin\n"), name);
3832   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
3833   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
3834   create_environment (plug);
3835   plug->short_name = GNUNET_strdup (name);
3836   plug->lib_name = libname;
3837   plug->next = plugins;
3838   plugins = plug;
3839   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
3840   if (plug->api == NULL)
3841     {
3842       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3843                   _("Failed to load transport plugin for `%s'\n"), name);
3844       GNUNET_free (plug->short_name);
3845       plugins = plug->next;
3846       GNUNET_free (libname);
3847       GNUNET_free (plug);
3848     }
3849 }
3850
3851
3852 /**
3853  * Called whenever a client is disconnected.  Frees our
3854  * resources associated with that client.
3855  *
3856  * @param cls closure
3857  * @param client identification of the client
3858  */
3859 static void
3860 client_disconnect_notification (void *cls,
3861                                 struct GNUNET_SERVER_Client *client)
3862 {
3863   struct TransportClient *pos;
3864   struct TransportClient *prev;
3865   struct ClientMessageQueueEntry *mqe;
3866
3867   if (client == NULL)
3868     return;
3869 #if DEBUG_TRANSPORT
3870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
3871               "Client disconnected, cleaning up.\n");
3872 #endif
3873   prev = NULL;
3874   pos = clients;
3875   while ((pos != NULL) && (pos->client != client))
3876     {
3877       prev = pos;
3878       pos = pos->next;
3879     }
3880   if (pos == NULL)
3881     return;
3882   while (NULL != (mqe = pos->message_queue_head))
3883     {
3884       GNUNET_CONTAINER_DLL_remove (pos->message_queue_head,
3885                                    pos->message_queue_tail,
3886                                    mqe);
3887       pos->message_count--;
3888       GNUNET_free (mqe);
3889     }
3890   if (prev == NULL)
3891     clients = pos->next;
3892   else
3893     prev->next = pos->next;
3894   if (GNUNET_YES == pos->tcs_pending)
3895     {
3896       pos->client = NULL;
3897       return;
3898     }
3899   if (pos->th != NULL)
3900     {
3901       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
3902       pos->th = NULL;
3903     }
3904   GNUNET_break (0 == pos->message_count);
3905   GNUNET_free (pos);
3906 }
3907
3908
3909 /**
3910  * Iterator to free entries in the validation_map.
3911  *
3912  * @param cls closure (unused)
3913  * @param key current key code
3914  * @param value value in the hash map (validation to abort)
3915  * @return GNUNET_YES (always)
3916  */
3917 static int 
3918 abort_validation (void *cls,
3919                   const GNUNET_HashCode * key,
3920                   void *value)
3921 {
3922   struct ValidationEntry *va = value;
3923
3924   GNUNET_SCHEDULER_cancel (sched, va->timeout_task);
3925   GNUNET_free (va->transport_name);
3926   GNUNET_free (va);
3927   return GNUNET_YES;
3928 }
3929
3930
3931 /**
3932  * Function called when the service shuts down.  Unloads our plugins
3933  * and cancels pending validations.
3934  *
3935  * @param cls closure, unused
3936  * @param tc task context (unused)
3937  */
3938 static void
3939 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3940 {
3941   struct TransportPlugin *plug;
3942   struct OwnAddressList *al;
3943   struct CheckHelloValidatedContext *chvc;
3944
3945   while (neighbours != NULL)
3946     disconnect_neighbour (neighbours, GNUNET_NO);
3947 #if DEBUG_TRANSPORT
3948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3949               "Transport service is unloading plugins...\n");
3950 #endif
3951   while (NULL != (plug = plugins))
3952     {
3953       plugins = plug->next;
3954       if (plug->address_update_task != GNUNET_SCHEDULER_NO_TASK)
3955         {
3956           GNUNET_SCHEDULER_cancel (plug->env.sched, 
3957                                    plug->address_update_task);
3958           plug->address_update_task = GNUNET_SCHEDULER_NO_TASK;
3959         }
3960       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
3961       GNUNET_free (plug->lib_name);
3962       GNUNET_free (plug->short_name);
3963       while (NULL != (al = plug->addresses))
3964         {
3965           plug->addresses = al->next;
3966           GNUNET_free (al);
3967         }
3968       GNUNET_free (plug);
3969     }
3970   if (my_private_key != NULL)
3971     GNUNET_CRYPTO_rsa_key_free (my_private_key);
3972   GNUNET_free_non_null (our_hello);
3973
3974   /* free 'chvc' data structure */
3975   while (NULL != (chvc = chvc_head))
3976     {
3977       chvc_head = chvc->next;
3978       GNUNET_PEERINFO_iterate_cancel (chvc->piter);
3979       GNUNET_free (chvc);
3980     }
3981   chvc_tail = NULL;
3982
3983   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
3984                                          &abort_validation,
3985                                          NULL);
3986   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
3987   validation_map = NULL;
3988   if (stats != NULL)
3989     {
3990       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
3991       stats = NULL;
3992     }
3993 }
3994
3995
3996 /**
3997  * Initiate transport service.
3998  *
3999  * @param cls closure
4000  * @param s scheduler to use
4001  * @param serv the initialized server
4002  * @param c configuration to use
4003  */
4004 static void
4005 run (void *cls,
4006      struct GNUNET_SCHEDULER_Handle *s,
4007      struct GNUNET_SERVER_Handle *serv,
4008      const struct GNUNET_CONFIGURATION_Handle *c)
4009 {
4010   char *plugs;
4011   char *pos;
4012   int no_transports;
4013   unsigned long long tneigh;
4014   char *keyfile;
4015
4016   sched = s;
4017   cfg = c;
4018   stats = GNUNET_STATISTICS_create (sched, "transport", cfg);
4019   validation_map = GNUNET_CONTAINER_multihashmap_create (64);
4020   /* parse configuration */
4021   if ((GNUNET_OK !=
4022        GNUNET_CONFIGURATION_get_value_number (c,
4023                                               "TRANSPORT",
4024                                               "NEIGHBOUR_LIMIT",
4025                                               &tneigh)) ||
4026       (GNUNET_OK !=
4027        GNUNET_CONFIGURATION_get_value_filename (c,
4028                                                 "GNUNETD",
4029                                                 "HOSTKEY", &keyfile)))
4030     {
4031       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4032                   _
4033                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
4034       GNUNET_SCHEDULER_shutdown (s);
4035       if (stats != NULL)
4036         {
4037           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4038           stats = NULL;
4039         }
4040       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4041       validation_map = NULL;
4042       return;
4043     }
4044   max_connect_per_transport = (uint32_t) tneigh;
4045   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4046   GNUNET_free (keyfile);
4047   if (my_private_key == NULL)
4048     {
4049       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4050                   _
4051                   ("Transport service could not access hostkey.  Exiting.\n"));
4052       GNUNET_SCHEDULER_shutdown (s);
4053       if (stats != NULL)
4054         {
4055           GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
4056           stats = NULL;
4057         }
4058       GNUNET_CONTAINER_multihashmap_destroy (validation_map);
4059       validation_map = NULL;
4060       return;
4061     }
4062   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4063   GNUNET_CRYPTO_hash (&my_public_key,
4064                       sizeof (my_public_key), &my_identity.hashPubKey);
4065   /* setup notification */
4066   server = serv;
4067   GNUNET_SERVER_disconnect_notify (server,
4068                                    &client_disconnect_notification, NULL);
4069   /* load plugins... */
4070   no_transports = 1;
4071   if (GNUNET_OK ==
4072       GNUNET_CONFIGURATION_get_value_string (c,
4073                                              "TRANSPORT", "PLUGINS", &plugs))
4074     {
4075       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4076                   _("Starting transport plugins `%s'\n"), plugs);
4077       pos = strtok (plugs, " ");
4078       while (pos != NULL)
4079         {
4080           start_transport (server, pos);
4081           no_transports = 0;
4082           pos = strtok (NULL, " ");
4083         }
4084       GNUNET_free (plugs);
4085     }
4086   GNUNET_SCHEDULER_add_delayed (sched,
4087                                 GNUNET_TIME_UNIT_FOREVER_REL,
4088                                 &shutdown_task, NULL);
4089   if (no_transports)
4090     refresh_hello ();
4091
4092 #if DEBUG_TRANSPORT
4093   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transport service ready.\n"));
4094 #endif
4095   /* process client requests */
4096   GNUNET_SERVER_add_handlers (server, handlers);
4097 }
4098
4099
4100 /**
4101  * The main function for the transport service.
4102  *
4103  * @param argc number of arguments from the command line
4104  * @param argv command line arguments
4105  * @return 0 ok, 1 on error
4106  */
4107 int
4108 main (int argc, char *const *argv)
4109 {
4110   return (GNUNET_OK ==
4111           GNUNET_SERVICE_run (argc,
4112                               argv,
4113                               "transport",
4114                               GNUNET_SERVICE_OPTION_NONE,
4115                               &run, NULL)) ? 0 : 1;
4116 }
4117
4118 /* end of gnunet-service-transport.c */