6b8e0e7dd0e30a0339b112cc3c7aea289c9be025
[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  * TODO:
27  * - if we do not receive an ACK in response to our
28  *   HELLO, retransmit HELLO!
29  */
30 #include "platform.h"
31 #include "gnunet_client_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_getopt_lib.h"
34 #include "gnunet_hello_lib.h"
35 #include "gnunet_os_lib.h"
36 #include "gnunet_peerinfo_service.h"
37 #include "gnunet_plugin_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_service_lib.h"
40 #include "gnunet_signatures.h"
41 #include "plugin_transport.h"
42 #include "transport.h"
43
44 /**
45  * How many messages can we have pending for a given client process
46  * before we start to drop incoming messages?  We typically should
47  * have only one client and so this would be the primary buffer for
48  * messages, so the number should be chosen rather generously.
49  *
50  * The expectation here is that most of the time the queue is large
51  * enough so that a drop is virtually never required.
52  */
53 #define MAX_PENDING 128
54
55 /**
56  * How often should we try to reconnect to a peer using a particular
57  * transport plugin before giving up?  Note that the plugin may be
58  * added back to the list after PLUGIN_RETRY_FREQUENCY expires.
59  */
60 #define MAX_CONNECT_RETRY 3
61
62 /**
63  * How often must a peer violate bandwidth quotas before we start
64  * to simply drop its messages?
65  */
66 #define QUOTA_VIOLATION_DROP_THRESHOLD 100
67
68 /**
69  * How long until a HELLO verification attempt should time out?
70  * Must be rather small, otherwise a partially successful HELLO
71  * validation (some addresses working) might not be available
72  * before a client's request for a connection fails for good.
73  * Besides, if a single request to an address takes a long time,
74  * then the peer is unlikely worthwhile anyway.
75  */
76 #define HELLO_VERIFICATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
77
78 /**
79  * How often do we re-add (cheaper) plugins to our list of plugins
80  * to try for a given connected peer?
81  */
82 #define PLUGIN_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
83
84 /**
85  * After how long do we expire an address in a HELLO
86  * that we just validated?  This value is also used
87  * for our own addresses when we create a HELLO.
88  */
89 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
90
91
92 /**
93  * Entry in linked list of network addresses.
94  */
95 struct AddressList
96 {
97   /**
98    * This is a linked list.
99    */
100   struct AddressList *next;
101
102   /**
103    * The address, actually a pointer to the end
104    * of this struct.  Do not free!
105    */
106   void *addr;
107
108   /**
109    * How long until we auto-expire this address (unless it is
110    * re-confirmed by the transport)?
111    */
112   struct GNUNET_TIME_Absolute expires;
113
114   /**
115    * Length of addr.
116    */
117   size_t addrlen;
118
119 };
120
121
122 /**
123  * Entry in linked list of all of our plugins.
124  */
125 struct TransportPlugin
126 {
127
128   /**
129    * This is a linked list.
130    */
131   struct TransportPlugin *next;
132
133   /**
134    * API of the transport as returned by the plugin's
135    * initialization function.
136    */
137   struct GNUNET_TRANSPORT_PluginFunctions *api;
138
139   /**
140    * Short name for the plugin (i.e. "tcp").
141    */
142   char *short_name;
143
144   /**
145    * Name of the library (i.e. "gnunet_plugin_transport_tcp").
146    */
147   char *lib_name;
148
149   /**
150    * List of our known addresses for this transport.
151    */
152   struct AddressList *addresses;
153
154   /**
155    * Environment this transport service is using
156    * for this plugin.
157    */
158   struct GNUNET_TRANSPORT_PluginEnvironment env;
159
160   /**
161    * ID of task that is used to clean up expired addresses.
162    */
163   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
164
165
166   /**
167    * Set to GNUNET_YES if we need to scrap the existing
168    * list of "addresses" and start fresh when we receive
169    * the next address update from a transport.  Set to
170    * GNUNET_NO if we should just add the new address
171    * to the list and wait for the commit call.
172    */
173   int rebuild;
174 };
175
176 struct NeighbourList;
177
178 /**
179  * For each neighbour we keep a list of messages
180  * that we still want to transmit to the neighbour.
181  */
182 struct MessageQueue
183 {
184
185   /**
186    * This is a linked list.
187    */
188   struct MessageQueue *next;
189
190   /**
191    * The message we want to transmit.
192    */
193   struct GNUNET_MessageHeader *message;
194
195   /**
196    * Client responsible for queueing the message;
197    * used to check that a client has not two messages
198    * pending for the same target.  Can be NULL.
199    */
200   struct TransportClient *client;
201
202   /**
203    * Neighbour this entry belongs to.
204    */
205   struct NeighbourList *neighbour;
206
207   /**
208    * Plugin that we used for the transmission.
209    * NULL until we scheduled a transmission.
210    */
211   struct TransportPlugin *plugin;
212
213   /**
214    * Internal message of the transport system that should not be
215    * included in the usual SEND-SEND_OK transmission confirmation
216    * traffic management scheme.  Typically, "internal_msg" will
217    * be set whenever "client" is NULL (but it is not strictly
218    * required).
219    */
220   int internal_msg;
221
222   /**
223    * How important is the message?
224    */
225   unsigned int priority;
226   
227 };
228
229
230 /**
231  * For a given Neighbour, which plugins are available
232  * to talk to this peer and what are their costs?
233  */
234 struct ReadyList
235 {
236
237   /**
238    * This is a linked list.
239    */
240   struct ReadyList *next;
241
242   /**
243    * Which of our transport plugins does this entry
244    * represent?
245    */
246   struct TransportPlugin *plugin;
247
248   /**
249    * Neighbour this entry belongs to.
250    */
251   struct NeighbourList *neighbour;
252
253   /**
254    * What was the last latency observed for this plugin
255    * and peer?  Invalid if connected is GNUNET_NO.
256    */
257   struct GNUNET_TIME_Relative latency;
258
259   /**
260    * If we did not successfully transmit a message to the
261    * given peer via this connection during the specified
262    * time, we should consider the connection to be dead.
263    * This is used in the case that a TCP transport simply
264    * stalls writing to the stream but does not formerly
265    * get a signal that the other peer died.
266    */
267   struct GNUNET_TIME_Absolute timeout;
268
269   /**
270    * Is this plugin currently connected?  The first time
271    * we transmit or send data to a peer via a particular
272    * plugin, we set this to GNUNET_YES.  If we later get
273    * an error (disconnect notification or transmission
274    * failure), we set it back to GNUNET_NO.  Each time the
275    * value is set to GNUNET_YES, we increment the
276    * "connect_attempts" counter.  If that one reaches a
277    * particular threshold, we consider the plugin to not
278    * be working properly at this time for the given peer
279    * and remove it from the eligible list.
280    */
281   int connected;
282
283   /**
284    * How often have we tried to connect using this plugin?
285    */
286   unsigned int connect_attempts;
287
288   /**
289    * Is this plugin ready to transmit to the specific
290    * target?  GNUNET_NO if not.  Initially, all plugins
291    * are marked ready.  If a transmission is in progress,
292    * "transmit_ready" is set to GNUNET_NO.
293    */
294   int transmit_ready;
295
296 };
297
298
299 /**
300  * Entry in linked list of all of our current neighbours.
301  */
302 struct NeighbourList
303 {
304
305   /**
306    * This is a linked list.
307    */
308   struct NeighbourList *next;
309
310   /**
311    * Which of our transports is connected to this peer
312    * and what is their status?
313    */
314   struct ReadyList *plugins;
315
316   /**
317    * List of messages we would like to send to this peer;
318    * must contain at most one message per client.
319    */
320   struct MessageQueue *messages;
321
322   /**
323    * Identity of this neighbour.
324    */
325   struct GNUNET_PeerIdentity id;
326
327   /**
328    * ID of task scheduled to run when this peer is about to
329    * time out (will free resources associated with the peer).
330    */
331   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
332
333   /**
334    * How long until we should consider this peer dead
335    * (if we don't receive another message in the
336    * meantime)?
337    */
338   struct GNUNET_TIME_Absolute peer_timeout;
339
340   /**
341    * At what time did we reset last_received last?
342    */
343   struct GNUNET_TIME_Absolute last_quota_update;
344
345   /**
346    * At what time should we try to again add plugins to
347    * our ready list?
348    */
349   struct GNUNET_TIME_Absolute retry_plugins_time;
350
351   /**
352    * How many bytes have we received since the "last_quota_update"
353    * timestamp?
354    */
355   uint64_t last_received;
356
357   /**
358    * Global quota for inbound traffic for the neighbour in bytes/ms.
359    */
360   uint32_t quota_in;
361
362   /**
363    * How often has the other peer (recently) violated the
364    * inbound traffic limit?  Incremented by 10 per violation,
365    * decremented by 1 per non-violation (for each
366    * time interval).
367    */
368   unsigned int quota_violation_count;
369
370   /**
371    * Have we seen an ACK from this neighbour in the past?
372    * (used to make up a fake ACK for clients connecting after
373    * the neighbour connected to us).
374    */
375   int saw_ack;
376
377 };
378
379
380 /**
381  * Linked list of messages to be transmitted to
382  * the client.  Each entry is followed by the
383  * actual message.
384  */
385 struct ClientMessageQueueEntry
386 {
387   /**
388    * This is a linked list.
389    */
390   struct ClientMessageQueueEntry *next;
391 };
392
393
394 /**
395  * Client connected to the transport service.
396  */
397 struct TransportClient
398 {
399
400   /**
401    * This is a linked list.
402    */
403   struct TransportClient *next;
404
405   /**
406    * Handle to the client.
407    */
408   struct GNUNET_SERVER_Client *client;
409
410   /**
411    * Linked list of messages yet to be transmitted to
412    * the client.
413    */
414   struct ClientMessageQueueEntry *message_queue_head;
415
416   /**
417    * Tail of linked list of messages yet to be transmitted to the
418    * client.
419    */
420   struct ClientMessageQueueEntry *message_queue_tail;
421
422   /**
423    * Is a call to "transmit_send_continuation" pending?  If so, we
424    * must not free this struct (even if the corresponding client
425    * disconnects) and instead only remove it from the linked list and
426    * set the "client" field to NULL.
427    */
428   int tcs_pending;
429
430   /**
431    * Length of the list of messages pending for this client.
432    */
433   unsigned int message_count;
434
435 };
436
437
438 /**
439  * For each HELLO, we may have to validate multiple addresses;
440  * each address gets its own request entry.
441  */
442 struct ValidationAddress
443 {
444   /**
445    * This is a linked list.
446    */
447   struct ValidationAddress *next;
448
449   /**
450    * Name of the transport.
451    */
452   char *transport_name;
453
454   /**
455    * When should this validated address expire?
456    */
457   struct GNUNET_TIME_Absolute expiration;
458
459   /**
460    * Length of the address we are validating.
461    */
462   size_t addr_len;
463
464   /**
465    * Challenge number we used.
466    */
467   uint32_t challenge;
468
469   /**
470    * Set to GNUNET_YES if the challenge was met,
471    * GNUNET_SYSERR if we know it failed, GNUNET_NO
472    * if we are waiting on a response.
473    */
474   int ok;
475 };
476
477
478 /**
479  * Entry in linked list of all HELLOs awaiting validation.
480  */
481 struct ValidationList
482 {
483
484   /**
485    * This is a linked list.
486    */
487   struct ValidationList *next;
488
489   /**
490    * Linked list with one entry per address from the HELLO
491    * that needs to be validated.
492    */
493   struct ValidationAddress *addresses;
494
495   /**
496    * The public key of the peer.
497    */
498   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
499
500   /**
501    * When does this record time-out? (assuming the
502    * challenge goes unanswered)
503    */
504   struct GNUNET_TIME_Absolute timeout;
505
506 };
507
508
509 /**
510  * HELLOs awaiting validation.
511  */
512 static struct ValidationList *pending_validations;
513
514 /**
515  * Our HELLO message.
516  */
517 static struct GNUNET_HELLO_Message *our_hello;
518
519 /**
520  * "version" of "our_hello".  Used to see if a given
521  * neighbour has already been sent the latest version
522  * of our HELLO message.
523  */
524 static unsigned int our_hello_version;
525
526 /**
527  * Our public key.
528  */
529 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
530
531 /**
532  * Our identity.
533  */
534 static struct GNUNET_PeerIdentity my_identity;
535
536 /**
537  * Our private key.
538  */
539 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
540
541 /**
542  * Our scheduler.
543  */
544 struct GNUNET_SCHEDULER_Handle *sched;
545
546 /**
547  * Our configuration.
548  */
549 const struct GNUNET_CONFIGURATION_Handle *cfg;
550
551 /**
552  * Linked list of all clients to this service.
553  */
554 static struct TransportClient *clients;
555
556 /**
557  * All loaded plugins.
558  */
559 static struct TransportPlugin *plugins;
560
561 /**
562  * Our server.
563  */
564 static struct GNUNET_SERVER_Handle *server;
565
566 /**
567  * All known neighbours and their HELLOs.
568  */
569 static struct NeighbourList *neighbours;
570
571 /**
572  * Number of neighbours we'd like to have.
573  */
574 static uint32_t max_connect_per_transport;
575
576
577 /**
578  * Find an entry in the neighbour list for a particular peer.
579  *
580  * @return NULL if not found.
581  */
582 static struct NeighbourList *
583 find_neighbour (const struct GNUNET_PeerIdentity *key)
584 {
585   struct NeighbourList *head = neighbours;
586   while ((head != NULL) &&
587          (0 != memcmp (key, &head->id, sizeof (struct GNUNET_PeerIdentity))))
588     head = head->next;
589   return head;
590 }
591
592
593 /**
594  * Find an entry in the transport list for a particular transport.
595  *
596  * @return NULL if not found.
597  */
598 static struct TransportPlugin *
599 find_transport (const char *short_name)
600 {
601   struct TransportPlugin *head = plugins;
602   while ((head != NULL) && (0 != strcmp (short_name, head->short_name)))
603     head = head->next;
604   return head;
605 }
606
607
608 /**
609  * Update the quota values for the given neighbour now.
610  */
611 static void
612 update_quota (struct NeighbourList *n)
613 {
614   struct GNUNET_TIME_Relative delta;
615   uint64_t allowed;
616   uint64_t remaining;
617
618   delta = GNUNET_TIME_absolute_get_duration (n->last_quota_update);
619   if (delta.value < MIN_QUOTA_REFRESH_TIME)
620     return;                     /* not enough time passed for doing quota update */
621   allowed = delta.value * n->quota_in;
622   if (n->last_received < allowed)
623     {
624       remaining = allowed - n->last_received;
625       if (n->quota_in > 0)
626         remaining /= n->quota_in;
627       else
628         remaining = 0;
629       if (remaining > MAX_BANDWIDTH_CARRY)
630         remaining = MAX_BANDWIDTH_CARRY;
631       n->last_received = 0;
632       n->last_quota_update = GNUNET_TIME_absolute_get ();
633       n->last_quota_update.value -= remaining;
634       if (n->quota_violation_count > 0)
635         n->quota_violation_count--;
636     }
637   else
638     {
639       n->last_received -= allowed;
640       n->last_quota_update = GNUNET_TIME_absolute_get ();
641       if (n->last_received > allowed)
642         {
643           /* more than twice the allowed rate! */
644           n->quota_violation_count += 10;
645         }
646     }
647 }
648
649
650 /**
651  * Function called to notify a client about the socket
652  * being ready to queue more data.  "buf" will be
653  * NULL and "size" zero if the socket was closed for
654  * writing in the meantime.
655  *
656  * @param cls closure
657  * @param size number of bytes available in buf
658  * @param buf where the callee should write the message
659  * @return number of bytes written to buf
660  */
661 static size_t
662 transmit_to_client_callback (void *cls, size_t size, void *buf)
663 {
664   struct TransportClient *client = cls;
665   struct ClientMessageQueueEntry *q;
666   uint16_t msize;
667   size_t tsize;
668   const struct GNUNET_MessageHeader *msg;
669   struct GNUNET_CONNECTION_TransmitHandle *th;
670   char *cbuf;
671
672   if (buf == NULL)
673     {
674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
675                   "Transmission to client failed, closing connection.\n");
676       /* fatal error with client, free message queue! */
677       while (NULL != (q = client->message_queue_head))
678         {
679           client->message_queue_head = q->next;
680           GNUNET_free (q);
681         }
682       client->message_queue_tail = NULL;
683       client->message_count = 0;
684       return 0;
685     }
686   cbuf = buf;
687   tsize = 0;
688   while (NULL != (q = client->message_queue_head))
689     {
690       msg = (const struct GNUNET_MessageHeader *) &q[1];
691       msize = ntohs (msg->size);
692       if (msize + tsize > size)
693         break;
694 #if DEBUG_TRANSPORT
695       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
696                   "Transmitting message of type %u to client.\n",
697                   ntohs (msg->type));
698 #endif
699       client->message_queue_head = q->next;
700       if (q->next == NULL)
701         client->message_queue_tail = NULL;
702       memcpy (&cbuf[tsize], msg, msize);
703       tsize += msize;
704       GNUNET_free (q);
705       client->message_count--;
706     }
707   if (NULL != q)
708     {
709       GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
710       th = GNUNET_SERVER_notify_transmit_ready (client->client,
711                                                 msize,
712                                                 GNUNET_TIME_UNIT_FOREVER_REL,
713                                                 &transmit_to_client_callback,
714                                                 client);
715       GNUNET_assert (th != NULL);
716     }
717   return tsize;
718 }
719
720
721 /**
722  * Send the specified message to the specified client.  Since multiple
723  * messages may be pending for the same client at a time, this code
724  * makes sure that no message is lost.
725  *
726  * @param client client to transmit the message to
727  * @param msg the message to send
728  * @param may_drop can this message be dropped if the
729  *        message queue for this client is getting far too large?
730  */
731 static void
732 transmit_to_client (struct TransportClient *client,
733                     const struct GNUNET_MessageHeader *msg, int may_drop)
734 {
735   struct ClientMessageQueueEntry *q;
736   uint16_t msize;
737   struct GNUNET_CONNECTION_TransmitHandle *th;
738
739   if ((client->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
740     {
741       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
742                   _
743                   ("Dropping message, have %u messages pending (%u is the soft limit)\n"),
744                   client->message_count, MAX_PENDING);
745       /* TODO: call to statistics... */
746       return;
747     }
748   client->message_count++;
749   msize = ntohs (msg->size);
750   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
751   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
752   memcpy (&q[1], msg, msize);
753   /* append to message queue */
754   if (client->message_queue_tail == NULL)
755     {
756       client->message_queue_tail = q;
757     }
758   else
759     {
760       client->message_queue_tail->next = q;
761       client->message_queue_tail = q;
762     }
763   if (client->message_queue_head == NULL)
764     {
765       client->message_queue_head = q;
766       th = GNUNET_SERVER_notify_transmit_ready (client->client,
767                                                 msize,
768                                                 GNUNET_TIME_UNIT_FOREVER_REL,
769                                                 &transmit_to_client_callback,
770                                                 client);
771       GNUNET_assert (th != NULL);
772     }
773 }
774
775
776 /**
777  * Find alternative plugins for communication.
778  *
779  * @param neighbour for which neighbour should we try to find
780  *        more plugins?
781  */
782 static void
783 try_alternative_plugins (struct NeighbourList *neighbour)
784 {
785   struct ReadyList *rl;
786
787   if ((neighbour->plugins != NULL) &&
788       (neighbour->retry_plugins_time.value >
789        GNUNET_TIME_absolute_get ().value))
790     return;                     /* don't try right now */
791   neighbour->retry_plugins_time
792     = GNUNET_TIME_relative_to_absolute (PLUGIN_RETRY_FREQUENCY);
793
794   rl = neighbour->plugins;
795   while (rl != NULL)
796     {
797       if (rl->connect_attempts > 0)
798         rl->connect_attempts--; /* amnesty */
799       rl = rl->next;
800     }
801
802 }
803
804
805 /**
806  * The peer specified by the given neighbour has timed-out or a plugin
807  * has disconnected.  We may either need to do nothing (other plugins
808  * still up), or trigger a full disconnect and clean up.  This
809  * function updates our state and do the necessary notifications.
810  * Also notifies our clients that the neighbour is now officially
811  * gone.
812  *
813  * @param n the neighbour list entry for the peer
814  * @param check should we just check if all plugins
815  *        disconnected or must we ask all plugins to
816  *        disconnect?
817  */
818 static void
819 disconnect_neighbour (struct NeighbourList *n,
820                       int check);
821
822
823 /**
824  * Check the ready list for the given neighbour and
825  * if a plugin is ready for transmission (and if we
826  * have a message), do so!
827  *
828  * @param neighbour target peer for which to check the plugins
829  */
830 static void 
831 try_transmission_to_peer (struct NeighbourList *neighbour);
832
833
834 /**
835  * Function called by the GNUNET_TRANSPORT_TransmitFunction
836  * upon "completion" of a send request.  This tells the API
837  * that it is now legal to send another message to the given
838  * peer.
839  *
840  * @param cls closure, identifies the entry on the
841  *            message queue that was transmitted and the
842  *            client responsible for queueing the message
843  * @param target the peer receiving the message
844  * @param result GNUNET_OK on success, if the transmission
845  *           failed, we should not tell the client to transmit
846  *           more messages
847  */
848 static void
849 transmit_send_continuation (void *cls,
850                             const struct GNUNET_PeerIdentity *target,
851                             int result)
852 {
853   struct MessageQueue *mq = cls;
854   struct ReadyList *rl;
855   struct SendOkMessage send_ok_msg;
856   struct NeighbourList *n;
857
858   GNUNET_assert (mq != NULL);
859   n = mq->neighbour;
860   GNUNET_assert (n != NULL);
861   GNUNET_assert (0 ==
862                  memcmp (&n->id, target,
863                          sizeof (struct GNUNET_PeerIdentity)));
864   rl = n->plugins;
865   while ((rl != NULL) && (rl->plugin != mq->plugin))
866     rl = rl->next;
867   GNUNET_assert (rl != NULL);
868   if (result == GNUNET_OK)
869     {
870       rl->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
871     }
872   else
873     {
874       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
875                   "Transmission to peer `%s' failed, marking connection as down.\n",
876                   GNUNET_i2s(target));
877       rl->connected = GNUNET_NO;
878     }
879   if (!mq->internal_msg)
880     rl->transmit_ready = GNUNET_YES;
881   if (mq->client != NULL)
882     {
883       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
884                   "Notifying client %p about failed transission to peer `%4s'.\n",
885                   mq->client,
886                   GNUNET_i2s(target));
887       send_ok_msg.header.size = htons (sizeof (send_ok_msg));
888       send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
889       send_ok_msg.success = htonl (result);
890       send_ok_msg.peer = n->id;
891       transmit_to_client (mq->client, &send_ok_msg.header, GNUNET_NO);
892     }
893   GNUNET_free (mq->message);
894   GNUNET_free (mq);
895   /* one plugin just became ready again, try transmitting
896      another message (if available) */
897   if (result == GNUNET_OK)
898     try_transmission_to_peer (n);
899   else    
900     disconnect_neighbour (n, GNUNET_YES); 
901 }
902
903
904 /**
905  * Check the ready list for the given neighbour and
906  * if a plugin is ready for transmission (and if we
907  * have a message), do so!
908  */
909 static void
910 try_transmission_to_peer (struct NeighbourList *neighbour)
911 {
912   struct ReadyList *pos;
913   struct GNUNET_TIME_Relative min_latency;
914   struct ReadyList *rl;
915   struct MessageQueue *mq;
916   struct GNUNET_TIME_Absolute now;
917
918   if (neighbour->messages == NULL)
919     return;                     /* nothing to do */
920   try_alternative_plugins (neighbour);
921   min_latency = GNUNET_TIME_UNIT_FOREVER_REL;
922   rl = NULL;
923   mq = neighbour->messages;
924   now = GNUNET_TIME_absolute_get ();
925   pos = neighbour->plugins;
926   while (pos != NULL)
927     {
928       /* set plugins that are inactive for a long time back to disconnected */
929       if ((pos->timeout.value < now.value) && (pos->connected == GNUNET_YES))
930         {
931 #if DEBUG_TRANSPORT
932           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933                       "Marking long-time inactive connection to `%4s' as down.\n",
934                       GNUNET_i2s (&neighbour->id));
935 #endif
936           pos->connected = GNUNET_NO;
937         }
938       if (((GNUNET_YES == pos->transmit_ready) ||
939            (mq->internal_msg)) &&
940           (pos->connect_attempts < MAX_CONNECT_RETRY) &&
941           ((rl == NULL) || (min_latency.value > pos->latency.value)))
942         {
943           rl = pos;
944           min_latency = pos->latency;
945         }
946       pos = pos->next;
947     }
948   if (rl == NULL)
949     {
950 #if DEBUG_TRANSPORT
951       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
952                   "No plugin ready to transmit message\n");
953 #endif
954       return;                   /* nobody ready */
955     }
956   if (GNUNET_NO == rl->connected)
957     {
958       rl->connect_attempts++;
959       rl->connected = GNUNET_YES;
960 #if DEBUG_TRANSPORT
961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962               "Establishing fresh connection with `%4s' via plugin `%s'\n",
963               GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
964 #endif
965     }
966   neighbour->messages = mq->next;
967   mq->plugin = rl->plugin;
968   if (!mq->internal_msg)
969     rl->transmit_ready = GNUNET_NO;
970 #if DEBUG_TRANSPORT
971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
972               "Giving message of type `%u' for `%4s' to plugin `%s'\n",
973               ntohs (mq->message->type),
974               GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
975 #endif
976   rl->plugin->api->send (rl->plugin->api->cls,
977                          &neighbour->id,
978                          mq->priority,
979                          mq->message,
980                          GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
981                          &transmit_send_continuation, mq);
982 }
983
984
985 /**
986  * Send the specified message to the specified peer.
987  *
988  * @param client source of the transmission request (can be NULL)
989  * @param priority how important is the message
990  * @param msg message to send
991  * @param is_internal is this an internal message
992  * @param neighbour handle to the neighbour for transmission
993  */
994 static void
995 transmit_to_peer (struct TransportClient *client,
996                   unsigned int priority,
997                   const struct GNUNET_MessageHeader *msg,
998                   int is_internal, struct NeighbourList *neighbour)
999 {
1000   struct MessageQueue *mq;
1001   struct MessageQueue *mqe;
1002   struct GNUNET_MessageHeader *m;
1003
1004 #if DEBUG_TRANSPORT
1005   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006               _("Sending message of type %u to peer `%4s'\n"),
1007               ntohs (msg->type), GNUNET_i2s (&neighbour->id));
1008 #endif
1009   if (client != NULL)
1010     {
1011       /* check for duplicate submission */
1012       mq = neighbour->messages;
1013       while (NULL != mq)
1014         {
1015           if (mq->client == client)
1016             {
1017               /* client transmitted to same peer twice
1018                  before getting SendOk! */
1019               GNUNET_break (0);
1020               return;
1021             }
1022           mq = mq->next;
1023         }
1024     }
1025   mq = GNUNET_malloc (sizeof (struct MessageQueue));
1026   mq->client = client;
1027   m = GNUNET_malloc (ntohs (msg->size));
1028   memcpy (m, msg, ntohs (msg->size));
1029   mq->message = m;
1030   mq->neighbour = neighbour;
1031   mq->internal_msg = is_internal;
1032   mq->priority = priority;
1033
1034   /* find tail */
1035   mqe = neighbour->messages;
1036   if (mqe != NULL)
1037     while (mqe->next != NULL)
1038       mqe = mqe->next;
1039   if (mqe == NULL)
1040     {
1041       /* new head */
1042       neighbour->messages = mq;
1043       try_transmission_to_peer (neighbour);
1044     }
1045   else
1046     {
1047       /* append */
1048       mqe->next = mq;
1049     }
1050 }
1051
1052
1053 /**
1054  * FIXME: document.
1055  */
1056 struct GeneratorContext
1057 {
1058   struct TransportPlugin *plug_pos;
1059   struct AddressList *addr_pos;
1060   struct GNUNET_TIME_Absolute expiration;
1061 };
1062
1063
1064 /**
1065  * FIXME: document.
1066  */
1067 static size_t
1068 address_generator (void *cls, size_t max, void *buf)
1069 {
1070   struct GeneratorContext *gc = cls;
1071   size_t ret;
1072
1073   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1074     {
1075       gc->plug_pos = gc->plug_pos->next;
1076       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1077     }
1078   if (NULL == gc->plug_pos)
1079     return 0;
1080   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1081                                   gc->expiration,
1082                                   gc->addr_pos->addr,
1083                                   gc->addr_pos->addrlen, buf, max);
1084   gc->addr_pos = gc->addr_pos->next;
1085   return ret;
1086 }
1087
1088
1089 /**
1090  * Construct our HELLO message from all of the addresses of
1091  * all of the transports.
1092  */
1093 static void
1094 refresh_hello ()
1095 {
1096   struct GNUNET_HELLO_Message *hello;
1097   struct TransportClient *cpos;
1098   struct NeighbourList *npos;
1099   struct GeneratorContext gc;
1100
1101 #if DEBUG_TRANSPORT
1102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1103               "Refreshing my `%s'\n",
1104               "HELLO");
1105 #endif
1106   gc.plug_pos = plugins;
1107   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1108   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1109   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1110   cpos = clients;
1111   while (cpos != NULL)
1112     {
1113       transmit_to_client (cpos,
1114                           (const struct GNUNET_MessageHeader *) hello,
1115                           GNUNET_NO);
1116       cpos = cpos->next;
1117     }
1118
1119   GNUNET_free_non_null (our_hello);
1120   our_hello = hello;
1121   our_hello_version++;
1122   GNUNET_PEERINFO_add_peer (cfg, sched, &my_identity, our_hello);
1123   npos = neighbours;
1124   while (npos != NULL)
1125     {
1126 #if DEBUG_TRANSPORT
1127       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1128                   "Transmitting updated `%s' to neighbour `%4s'\n",
1129                   "HELLO",
1130                   GNUNET_i2s(&npos->id));
1131 #endif
1132       transmit_to_peer (NULL, 0,
1133                         (const struct GNUNET_MessageHeader *) our_hello,
1134                         GNUNET_YES, npos);
1135       npos = npos->next;
1136     }
1137 }
1138
1139
1140 /**
1141  * Task used to clean up expired addresses for a plugin.
1142  *
1143  * @param cls closure
1144  * @param tc context
1145  */
1146 static void
1147 expire_address_task (void *cls,
1148                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1149
1150
1151 /**
1152  * Update the list of addresses for this plugin,
1153  * expiring those that are past their expiration date.
1154  *
1155  * @param plugin addresses of which plugin should be recomputed?
1156  * @param fresh set to GNUNET_YES if a new address was added
1157  *        and we need to regenerate the HELLO even if nobody
1158  *        expired
1159  */
1160 static void
1161 update_addresses (struct TransportPlugin *plugin, int fresh)
1162 {
1163   struct GNUNET_TIME_Relative min_remaining;
1164   struct GNUNET_TIME_Relative remaining;
1165   struct GNUNET_TIME_Absolute now;
1166   struct AddressList *pos;
1167   struct AddressList *prev;
1168   struct AddressList *next;
1169   int expired;
1170
1171   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_TASK)
1172     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1173   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1174   now = GNUNET_TIME_absolute_get ();
1175   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1176   expired = GNUNET_NO;
1177   prev = NULL;
1178   pos = plugin->addresses;
1179   while (pos != NULL)
1180     {
1181       next = pos->next;
1182       if (pos->expires.value < now.value)
1183         {
1184           expired = GNUNET_YES;
1185           if (prev == NULL)
1186             plugin->addresses = pos->next;
1187           else
1188             prev->next = pos->next;
1189           GNUNET_free (pos);
1190         }
1191       else
1192         {
1193           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1194           if (remaining.value < min_remaining.value)
1195             min_remaining = remaining;
1196           prev = pos;
1197         }
1198       pos = next;
1199     }
1200
1201   if (expired || fresh)
1202     refresh_hello ();
1203   if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1204     plugin->address_update_task
1205       = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1206                                       min_remaining,
1207                                       &expire_address_task, plugin);
1208
1209 }
1210
1211
1212 /**
1213  * Task used to clean up expired addresses for a plugin.
1214  *
1215  * @param cls closure
1216  * @param tc context
1217  */
1218 static void
1219 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1220 {
1221   struct TransportPlugin *plugin = cls;
1222   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1223   update_addresses (plugin, GNUNET_NO);
1224 }
1225
1226
1227 /**
1228  * Function that must be called by each plugin to notify the
1229  * transport service about the addresses under which the transport
1230  * provided by the plugin can be reached.
1231  *
1232  * @param cls closure
1233  * @param name name of the transport that generated the address
1234  * @param addr one of the addresses of the host, NULL for the last address
1235  *        the specific address format depends on the transport
1236  * @param addrlen length of the address
1237  * @param expires when should this address automatically expire?
1238  */
1239 static void
1240 plugin_env_notify_address (void *cls,
1241                            const char *name,
1242                            const void *addr,
1243                            size_t addrlen,
1244                            struct GNUNET_TIME_Relative expires)
1245 {
1246   struct TransportPlugin *p = cls;
1247   struct AddressList *al;
1248   struct GNUNET_TIME_Absolute abex;
1249
1250   abex = GNUNET_TIME_relative_to_absolute (expires);
1251   GNUNET_assert (p == find_transport (name));
1252
1253   al = p->addresses;
1254   while (al != NULL)
1255     {
1256       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1257         {
1258           if (al->expires.value < abex.value)
1259             al->expires = abex;
1260           return;
1261         }
1262       al = al->next;
1263     }
1264 #if DEBUG_TRANSPORT
1265   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1266               "Plugin `%s' informs us about a new address `%s'\n", name,
1267               GNUNET_a2s(addr, addrlen));
1268 #endif
1269   al = GNUNET_malloc (sizeof (struct AddressList) + addrlen);
1270   al->addr = &al[1];
1271   al->next = p->addresses;
1272   p->addresses = al;
1273   al->expires = abex;
1274   al->addrlen = addrlen;
1275   memcpy (&al[1], addr, addrlen);
1276   update_addresses (p, GNUNET_YES);
1277 }
1278
1279
1280 /**
1281  * Notify all of our clients about a peer connecting.
1282  */
1283 static void
1284 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1285                         struct GNUNET_TIME_Relative latency)
1286 {
1287   struct ConnectInfoMessage cim;
1288   struct TransportClient *cpos;
1289
1290 #if DEBUG_TRANSPORT
1291   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1292               "Informing clients about peer `%4s' connecting to us\n",
1293               GNUNET_i2s (peer));
1294 #endif
1295   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1296   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1297   cim.quota_out = htonl (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT / (60*1000));
1298   cim.latency = GNUNET_TIME_relative_hton (latency);
1299   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1300   cpos = clients;
1301   while (cpos != NULL)
1302     {
1303       transmit_to_client (cpos, &cim.header, GNUNET_NO);
1304       cpos = cpos->next;
1305     }
1306 }
1307
1308
1309 /**
1310  * Notify all of our clients about a peer disconnecting.
1311  */
1312 static void
1313 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1314 {
1315   struct DisconnectInfoMessage dim;
1316   struct TransportClient *cpos;
1317
1318 #if DEBUG_TRANSPORT
1319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1320               "Informing clients about peer `%4s' disconnecting\n",
1321               GNUNET_i2s (peer));
1322 #endif
1323   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1324   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1325   dim.reserved = htonl (0);
1326   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1327   cpos = clients;
1328   while (cpos != NULL)
1329     {
1330       transmit_to_client (cpos, &dim.header, GNUNET_NO);
1331       cpos = cpos->next;
1332     }
1333 }
1334
1335
1336 /**
1337  * Copy any validated addresses to buf.
1338  *
1339  * @return 0 once all addresses have been
1340  *         returned
1341  */
1342 static size_t
1343 list_validated_addresses (void *cls, size_t max, void *buf)
1344 {
1345   struct ValidationAddress **va = cls;
1346   size_t ret;
1347
1348   while ((NULL != *va) && ((*va)->ok != GNUNET_YES))
1349     *va = (*va)->next;
1350   if (NULL == *va)
1351     return 0;
1352   ret = GNUNET_HELLO_add_address ((*va)->transport_name,
1353                                   (*va)->expiration,
1354                                   &(*va)[1], (*va)->addr_len, buf, max);
1355   *va = (*va)->next;
1356   return ret;
1357 }
1358
1359
1360 /**
1361  * HELLO validation cleanup task.
1362  */
1363 static void
1364 cleanup_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1365 {
1366   struct ValidationAddress *va;
1367   struct ValidationList *pos;
1368   struct ValidationList *prev;
1369   struct GNUNET_TIME_Absolute now;
1370   struct GNUNET_TIME_Absolute first;
1371   struct GNUNET_HELLO_Message *hello;
1372   struct GNUNET_PeerIdentity pid;
1373   struct NeighbourList *n;
1374
1375 #if DEBUG_TRANSPORT
1376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1377               "HELLO validation cleanup background task running...\n");
1378 #endif
1379   now = GNUNET_TIME_absolute_get ();
1380   prev = NULL;
1381   pos = pending_validations;
1382   while (pos != NULL)
1383     {
1384       if (pos->timeout.value < now.value)
1385         {
1386           if (prev == NULL)
1387             pending_validations = pos->next;
1388           else
1389             prev->next = pos->next;
1390           va = pos->addresses;
1391           hello = GNUNET_HELLO_create (&pos->publicKey,
1392                                        &list_validated_addresses, &va);
1393           GNUNET_CRYPTO_hash (&pos->publicKey,
1394                               sizeof (struct
1395                                       GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1396                               &pid.hashPubKey);
1397 #if DEBUG_TRANSPORT
1398           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399                       "Creating persistent `%s' message for peer `%4s' based on confirmed addresses.\n",
1400                       "HELLO", GNUNET_i2s (&pid));
1401 #endif
1402           GNUNET_PEERINFO_add_peer (cfg, sched, &pid, hello);
1403           n = find_neighbour (&pid);
1404           if (NULL != n)
1405             try_transmission_to_peer (n);           
1406           GNUNET_free (hello);
1407           while (NULL != (va = pos->addresses))
1408             {
1409               pos->addresses = va->next;
1410               GNUNET_free (va->transport_name);
1411               GNUNET_free (va);
1412             }
1413           GNUNET_free (pos);
1414           if (prev == NULL)
1415             pos = pending_validations;
1416           else
1417             pos = prev->next;
1418           continue;
1419         }
1420       prev = pos;
1421       pos = pos->next;
1422     }
1423
1424   /* finally, reschedule cleanup if needed; list is
1425      ordered by timeout, so we need the last element... */
1426   if (NULL != pending_validations)
1427     {
1428       first = pending_validations->timeout;
1429       pos = pending_validations;
1430       while (pos != NULL) 
1431         {
1432           first = GNUNET_TIME_absolute_min (first, pos->timeout);
1433           pos = pos->next;
1434         }
1435       GNUNET_SCHEDULER_add_delayed (sched,
1436                                     GNUNET_TIME_absolute_get_remaining (first),
1437                                     &cleanup_validation, NULL);
1438     }
1439 }
1440
1441
1442
1443
1444 /**
1445  * Function that will be called if we receive a validation
1446  * of an address challenge that we transmitted to another
1447  * peer.  Note that the validation should only be considered
1448  * acceptable if the challenge matches AND if the sender
1449  * address is at least a plausible address for this peer
1450  * (otherwise we may be seeing a MiM attack).
1451  *
1452  * @param cls closure
1453  * @param name name of the transport that generated the address
1454  * @param peer who responded to our challenge
1455  * @param challenge the challenge number we presumably used
1456  * @param sender_addr string describing our sender address (as observed
1457  *         by the other peer in human-readable format)
1458  */
1459 static void
1460 plugin_env_notify_validation (void *cls,
1461                               const char *name,
1462                               const struct GNUNET_PeerIdentity *peer,
1463                               uint32_t challenge,
1464                               const char *sender_addr)
1465 {
1466   unsigned int not_done;
1467   int matched;
1468   struct ValidationList *pos;
1469   struct ValidationAddress *va;
1470   struct GNUNET_PeerIdentity id;
1471
1472   pos = pending_validations;
1473   while (pos != NULL)
1474     {
1475       GNUNET_CRYPTO_hash (&pos->publicKey,
1476                           sizeof (struct
1477                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1478                           &id.hashPubKey);
1479       if (0 ==
1480           memcmp (peer, &id, sizeof (struct GNUNET_PeerIdentity)))
1481         break;
1482       pos = pos->next;
1483     }
1484   if (pos == NULL)
1485     {
1486       /* TODO: call statistics (unmatched PONG) */
1487       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1488                   _
1489                   ("Received validation response but have no record of any validation request for `%4s'. Ignoring.\n"),
1490                   GNUNET_i2s(peer));
1491       return;
1492     }
1493   not_done = 0;
1494   matched = GNUNET_NO;
1495   va = pos->addresses;
1496   while (va != NULL)
1497     {
1498       if (va->challenge == challenge)
1499         {
1500 #if DEBUG_TRANSPORT
1501           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1502                       "Confirmed validity of address, peer `%4s' has address `%s'.\n",
1503                       GNUNET_i2s (peer),
1504                       GNUNET_a2s ((const struct sockaddr*) &va[1], 
1505                                   va->addr_len));
1506 #endif
1507           GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1508                       _("Another peer saw us using the address `%s' via `%s'. If this is not plausible, this address should be listed in the configuration as implausible to avoid MiM attacks.\n"),
1509                       sender_addr, 
1510                       name);
1511           va->ok = GNUNET_YES;
1512           va->expiration =
1513             GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1514           matched = GNUNET_YES;
1515         }        
1516       if (va->ok != GNUNET_YES)
1517         not_done++;
1518       va = va->next;
1519     }
1520   if (GNUNET_NO == matched)
1521     {
1522       /* TODO: call statistics (unmatched PONG) */
1523       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1524                   _
1525                   ("Received `%s' message but have no record of a matching `%s' message. Ignoring.\n"),
1526                   "PONG", "PING");
1527     }
1528   if (0 == not_done)
1529     {
1530 #if DEBUG_TRANSPORT
1531       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1532                   "All addresses validated, will now construct `%s' for `%4s'.\n",
1533                   "HELLO",
1534                   GNUNET_i2s (peer));
1535 #endif
1536       pos->timeout.value = 0;
1537       GNUNET_SCHEDULER_add_with_priority (sched,
1538                                           GNUNET_SCHEDULER_PRIORITY_IDLE,
1539                                           &cleanup_validation, NULL);
1540     }
1541   else
1542     {
1543 #if DEBUG_TRANSPORT
1544       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1545                   "Still waiting for %u additional `%s' messages before constructing `%s' for `%4s'.\n",
1546                   not_done,
1547                   "PONG",
1548                   "HELLO",
1549                   GNUNET_i2s (peer));
1550 #endif
1551     }
1552 }
1553
1554
1555 struct CheckHelloValidatedContext
1556 {
1557   /**
1558    * Plugin for which we are validating.
1559    */
1560   struct TransportPlugin *plugin;
1561
1562   /**
1563    * Hello that we are validating.
1564    */
1565   struct GNUNET_HELLO_Message *hello;
1566
1567   /**
1568    * Validation list being build.
1569    */
1570   struct ValidationList *e;
1571
1572   /**
1573    * Context for peerinfo iteration.
1574    * NULL after we are done processing peerinfo's information.
1575    */
1576   struct GNUNET_PEERINFO_IteratorContext *piter;
1577
1578 };
1579
1580
1581 /**
1582  * Append the given address to the list of entries
1583  * that need to be validated.
1584  */
1585 static int
1586 run_validation (void *cls,
1587                 const char *tname,
1588                 struct GNUNET_TIME_Absolute expiration,
1589                 const void *addr, size_t addrlen)
1590 {
1591   struct ValidationList *e = cls;
1592   struct TransportPlugin *tp;
1593   struct ValidationAddress *va;
1594   struct GNUNET_PeerIdentity id;
1595
1596   tp = find_transport (tname);
1597   if (tp == NULL)
1598     {
1599       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1600                   GNUNET_ERROR_TYPE_BULK,
1601                   _
1602                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
1603                   tname);
1604       return GNUNET_OK;
1605     }
1606   GNUNET_CRYPTO_hash (&e->publicKey,
1607                       sizeof (struct
1608                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1609                       &id.hashPubKey);
1610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611               "Scheduling validation of address `%s' via `%s' for `%4s'\n",
1612               GNUNET_a2s(addr, addrlen),
1613               tname,
1614               GNUNET_i2s(&id));
1615
1616   va = GNUNET_malloc (sizeof (struct ValidationAddress) + addrlen);
1617   va->next = e->addresses;
1618   e->addresses = va;
1619   va->transport_name = GNUNET_strdup (tname);
1620   va->addr_len = addrlen;
1621   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1622                                             (unsigned int) -1);
1623   memcpy (&va[1], addr, addrlen);
1624   return GNUNET_OK;
1625 }
1626
1627
1628 /**
1629  * Check if addresses in validated hello "h" overlap with
1630  * those in "chvc->hello" and update "chvc->hello" accordingly,
1631  * removing those addresses that have already been validated.
1632  */
1633 static void
1634 check_hello_validated (void *cls,
1635                        const struct GNUNET_PeerIdentity *peer,
1636                        const struct GNUNET_HELLO_Message *h, 
1637                        uint32_t trust)
1638 {
1639   struct CheckHelloValidatedContext *chvc = cls;
1640   struct ValidationAddress *va;
1641   struct TransportPlugin *tp;
1642   int first_call;
1643   struct GNUNET_PeerIdentity apeer;
1644
1645   first_call = GNUNET_NO;
1646   if (chvc->e == NULL)
1647     {
1648       chvc->piter = NULL;
1649       first_call = GNUNET_YES;
1650       chvc->e = GNUNET_malloc (sizeof (struct ValidationList));
1651       GNUNET_assert (GNUNET_OK ==
1652                      GNUNET_HELLO_get_key (h != NULL ? h : chvc->hello,
1653                                            &chvc->e->publicKey));
1654       chvc->e->timeout =
1655         GNUNET_TIME_relative_to_absolute (HELLO_VERIFICATION_TIMEOUT);
1656       chvc->e->next = pending_validations;
1657       pending_validations = chvc->e;
1658     }
1659   if (h != NULL)
1660     {
1661       GNUNET_HELLO_iterate_new_addresses (chvc->hello,
1662                                           h,
1663                                           GNUNET_TIME_absolute_get (),
1664                                           &run_validation, chvc->e);
1665     }
1666   else if (GNUNET_YES == first_call)
1667     {
1668       /* no existing HELLO, all addresses are new */
1669       GNUNET_HELLO_iterate_addresses (chvc->hello,
1670                                       GNUNET_NO, &run_validation, chvc->e);
1671     }
1672   if (h != NULL)
1673     return;                     /* wait for next call */
1674   /* finally, transmit validation attempts */
1675   GNUNET_assert (GNUNET_OK ==
1676                  GNUNET_HELLO_get_id (chvc->hello,
1677                                       &apeer));
1678 #if DEBUG_TRANSPORT
1679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680               "Ready to validate addresses from `%s' message for peer `%4s'\n",
1681               "HELLO", GNUNET_i2s (&apeer));
1682 #endif
1683   va = chvc->e->addresses;
1684   while (va != NULL)
1685     {
1686 #if DEBUG_TRANSPORT
1687       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1688                   "Establishing `%s' connection to validate `%s' address `%s' of `%4s'\n",
1689                   va->transport_name,
1690                   "HELLO",
1691                   GNUNET_a2s ((const struct sockaddr*) &va[1], 
1692                               va->addr_len),
1693                   GNUNET_i2s (&apeer));
1694 #endif
1695       tp = find_transport (va->transport_name);
1696       GNUNET_assert (tp != NULL);
1697       if (GNUNET_OK !=
1698           tp->api->validate (tp->api->cls,
1699                              &apeer,
1700                              va->challenge,
1701                              HELLO_VERIFICATION_TIMEOUT,
1702                              &va[1],
1703                              va->addr_len))
1704         va->ok = GNUNET_SYSERR;
1705       va = va->next;
1706     }
1707   GNUNET_SCHEDULER_add_delayed (sched,
1708                                 GNUNET_TIME_absolute_get_remaining (chvc->e->timeout), 
1709                                 &cleanup_validation, NULL);
1710   GNUNET_free (chvc);
1711 }
1712
1713
1714 /**
1715  * Process HELLO-message.
1716  *
1717  * @param plugin transport involved, may be NULL
1718  * @param message the actual message
1719  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
1720  */
1721 static int
1722 process_hello (struct TransportPlugin *plugin,
1723                const struct GNUNET_MessageHeader *message)
1724 {
1725   struct ValidationList *e;
1726   uint16_t hsize;
1727   struct GNUNET_PeerIdentity target;
1728   const struct GNUNET_HELLO_Message *hello;
1729   struct CheckHelloValidatedContext *chvc;
1730   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
1731
1732   hsize = ntohs (message->size);
1733   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1734       (hsize < sizeof (struct GNUNET_MessageHeader)))
1735     {
1736       GNUNET_break (0);
1737       return GNUNET_SYSERR;
1738     }
1739   /* first, check if load is too high */
1740   if (GNUNET_OS_load_cpu_get (cfg) > 100)
1741     {
1742       /* TODO: call to stats? */
1743       return GNUNET_OK;
1744     }
1745   hello = (const struct GNUNET_HELLO_Message *) message;
1746   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
1747     {
1748       GNUNET_break_op (0);
1749       return GNUNET_SYSERR;
1750     }
1751   GNUNET_CRYPTO_hash (&publicKey,
1752                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1753                       &target.hashPubKey);
1754 #if DEBUG_TRANSPORT
1755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1756               "Processing `%s' message for `%4s'\n",
1757               "HELLO", GNUNET_i2s (&target));
1758 #endif
1759   /* check if a HELLO for this peer is already on the validation list */
1760   e = pending_validations;
1761   while (e != NULL)
1762     {
1763       if (0 == memcmp (&e->publicKey,
1764                        &publicKey,
1765                        sizeof (struct
1766                                GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
1767         {
1768           /* TODO: call to stats? */
1769 #if DEBUG_TRANSPORT
1770           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1771                       "`%s' message for peer `%4s' is already pending; ignoring new message\n",
1772                       "HELLO", GNUNET_i2s (&target));
1773 #endif    
1774           return GNUNET_OK;
1775         }
1776       e = e->next;
1777     }
1778   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
1779   chvc->plugin = plugin;
1780   chvc->hello = (struct GNUNET_HELLO_Message *) &chvc[1];
1781   memcpy (chvc->hello, hello, hsize);
1782   /* finally, check if HELLO was previously validated
1783      (continuation will then schedule actual validation) */
1784   chvc->piter = GNUNET_PEERINFO_iterate (cfg,
1785                                          sched,
1786                                          &target,
1787                                          0,
1788                                          HELLO_VERIFICATION_TIMEOUT,
1789                                          &check_hello_validated, chvc);
1790   return GNUNET_OK;
1791 }
1792
1793
1794 /**
1795  * The peer specified by the given neighbour has timed-out or a plugin
1796  * has disconnected.  We may either need to do nothing (other plugins
1797  * still up), or trigger a full disconnect and clean up.  This
1798  * function updates our state and do the necessary notifications.
1799  * Also notifies our clients that the neighbour is now officially
1800  * gone.
1801  *
1802  * @param n the neighbour list entry for the peer
1803  * @param check should we just check if all plugins
1804  *        disconnected or must we ask all plugins to
1805  *        disconnect?
1806  */
1807 static void
1808 disconnect_neighbour (struct NeighbourList *n,
1809                       int check)
1810 {
1811   struct ReadyList *rpos;
1812   struct NeighbourList *npos;
1813   struct NeighbourList *nprev;
1814   struct MessageQueue *mq;
1815   
1816   if (GNUNET_YES == check)
1817     {
1818       rpos = n->plugins;
1819       while (NULL != rpos)
1820         {
1821           if (GNUNET_YES == rpos->connected)
1822             return; /* still connected */
1823           rpos = rpos->next;
1824         }
1825     }
1826
1827 #if DEBUG_TRANSPORT
1828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1829               "Disconnecting from `%4s'\n",
1830               GNUNET_i2s(&n->id));
1831 #endif
1832   /* remove n from neighbours list */
1833   nprev = NULL;
1834   npos = neighbours;
1835   while ((npos != NULL) && (npos != n))
1836     {
1837       nprev = npos;
1838       npos = npos->next;
1839     }
1840   GNUNET_assert (npos != NULL);
1841   if (nprev == NULL)
1842     neighbours = n->next;
1843   else
1844     nprev->next = n->next;
1845
1846   /* notify all clients about disconnect */
1847   notify_clients_disconnect (&n->id);
1848
1849   /* clean up all plugins, cancel connections and pending transmissions */
1850   while (NULL != (rpos = n->plugins))
1851     {
1852       n->plugins = rpos->next;
1853       GNUNET_assert (rpos->neighbour == n);
1854       if (GNUNET_YES == rpos->connected)
1855         rpos->plugin->api->disconnect (rpos->plugin->api->cls,
1856                                        &n->id);
1857       GNUNET_free (rpos);
1858     }
1859
1860   /* free all messages on the queue */
1861   while (NULL != (mq = n->messages))
1862     {
1863       n->messages = mq->next;
1864       GNUNET_assert (mq->neighbour == n);
1865       GNUNET_free (mq);
1866     }
1867   if (n->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1868     GNUNET_SCHEDULER_cancel (sched,
1869                              n->timeout_task);
1870   /* finally, free n itself */
1871   GNUNET_free (n);
1872 }
1873
1874
1875 /**
1876  * Add an entry for each of our transport plugins
1877  * (that are able to send) to the list of plugins
1878  * for this neighbour.
1879  *
1880  * @param neighbour to initialize
1881  */
1882 static void
1883 add_plugins (struct NeighbourList *neighbour)
1884 {
1885   struct TransportPlugin *tp;
1886   struct ReadyList *rl;
1887
1888   neighbour->retry_plugins_time
1889     = GNUNET_TIME_relative_to_absolute (PLUGIN_RETRY_FREQUENCY);
1890   tp = plugins;
1891   while (tp != NULL)
1892     {
1893       if (tp->api->send != NULL)
1894         {
1895           rl = GNUNET_malloc (sizeof (struct ReadyList));
1896           rl->next = neighbour->plugins;
1897           neighbour->plugins = rl;
1898           rl->plugin = tp;
1899           rl->neighbour = neighbour;
1900           rl->transmit_ready = GNUNET_YES;
1901         }
1902       tp = tp->next;
1903     }
1904 }
1905
1906
1907 static void
1908 neighbour_timeout_task (void *cls,
1909                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1910 {
1911   struct NeighbourList *n = cls;
1912
1913 #if DEBUG_TRANSPORT
1914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1915               "Neighbour `%4s' has timed out!\n",
1916               GNUNET_i2s(&n->id));
1917 #endif
1918   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1919   disconnect_neighbour (n, GNUNET_NO);
1920 }
1921
1922
1923 /**
1924  * Create a fresh entry in our neighbour list for the given peer.
1925  * Will try to transmit our current HELLO to the new neighbour.  Also
1926  * notifies our clients about the new "connection".
1927  *
1928  * @param peer the peer for which we create the entry
1929  * @return the new neighbour list entry
1930  */
1931 static struct NeighbourList *
1932 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1933 {
1934   struct NeighbourList *n;
1935
1936 #if DEBUG_TRANSPORT
1937   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1938               "Setting up new neighbour `%4s', sending our HELLO to introduce ourselves\n",
1939               GNUNET_i2s (peer));
1940 #endif
1941   GNUNET_assert (our_hello != NULL);
1942   n = GNUNET_malloc (sizeof (struct NeighbourList));
1943   n->next = neighbours;
1944   neighbours = n;
1945   n->id = *peer;
1946   n->last_quota_update = GNUNET_TIME_absolute_get ();
1947   n->peer_timeout =
1948     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1949   n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1950   add_plugins (n);
1951   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1952                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1953                                                   &neighbour_timeout_task, n);
1954   transmit_to_peer (NULL, 0,
1955                     (const struct GNUNET_MessageHeader *) our_hello,
1956                     GNUNET_YES, n);
1957   notify_clients_connect (peer, GNUNET_TIME_UNIT_FOREVER_REL);
1958   return n;
1959 }
1960
1961
1962 /**
1963  * Function called by the plugin for each received message.
1964  * Update data volumes, possibly notify plugins about
1965  * reducing the rate at which they read from the socket
1966  * and generally forward to our receive callback.
1967  *
1968  * @param cls the "struct TransportPlugin *" we gave to the plugin
1969  * @param latency estimated latency for communicating with the
1970  *             given peer
1971  * @param peer (claimed) identity of the other peer
1972  * @param message the message, NULL if peer was disconnected
1973  * @return the new service_context that the plugin should use
1974  *         for future receive calls for messages from this
1975  *         particular peer
1976  */
1977 static void
1978 plugin_env_receive (void *cls,
1979                     struct GNUNET_TIME_Relative latency,
1980                     const struct GNUNET_PeerIdentity *peer,
1981                     const struct GNUNET_MessageHeader *message)
1982 {
1983   const struct GNUNET_MessageHeader ack = {
1984     htons (sizeof (struct GNUNET_MessageHeader)),
1985     htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ACK)
1986   };
1987   struct ReadyList *service_context;
1988   struct TransportPlugin *plugin = cls;
1989   struct TransportClient *cpos;
1990   struct InboundMessage *im;
1991   uint16_t msize;
1992   struct NeighbourList *n;
1993
1994   n = find_neighbour (peer);
1995   if (n == NULL)
1996     {
1997       if (message == NULL)
1998         return;        /* disconnect of peer already marked down */
1999       n = setup_new_neighbour (peer);
2000     }
2001   service_context = n->plugins;
2002   while ( (service_context != NULL) &&
2003           (plugin != service_context->plugin) )
2004     service_context = service_context->next;
2005   GNUNET_assert ((plugin->api->send == NULL) ||
2006                  (service_context != NULL));    
2007   if (message == NULL)
2008     {
2009 #if DEBUG_TRANSPORT
2010       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2011                   "Receive failed from `%4s', triggering disconnect\n",
2012                   GNUNET_i2s(&n->id));
2013 #endif
2014       /* TODO: call stats */
2015       if (service_context != NULL) 
2016         service_context->connected = GNUNET_NO;        
2017       disconnect_neighbour (n, GNUNET_YES);
2018       return;
2019     }
2020 #if DEBUG_TRANSPORT
2021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2022               "Processing message of type `%u' received by plugin...\n",
2023               ntohs (message->type));
2024 #endif
2025   if (service_context != NULL)
2026     {
2027       if (service_context->connected == GNUNET_NO)
2028         {
2029           service_context->connected = GNUNET_YES;
2030           service_context->transmit_ready = GNUNET_YES;
2031           service_context->connect_attempts++;
2032         }
2033       service_context->timeout
2034         = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2035       service_context->latency = latency;
2036     }
2037   /* update traffic received amount ... */
2038   msize = ntohs (message->size);
2039   n->last_received += msize;
2040   GNUNET_SCHEDULER_cancel (sched, n->timeout_task);
2041   n->peer_timeout =
2042     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2043   n->timeout_task =
2044     GNUNET_SCHEDULER_add_delayed (sched, 
2045                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2046                                   &neighbour_timeout_task, n);
2047   update_quota (n);
2048   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2049     {
2050       /* dropping message due to frequent inbound volume violations! */
2051       GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2052                   GNUNET_ERROR_TYPE_BULK,
2053                   _
2054                   ("Dropping incoming message due to repeated bandwidth quota violations.\n"));
2055       /* TODO: call stats */
2056       GNUNET_assert ( (service_context == NULL) ||
2057                       (NULL != service_context->neighbour) );
2058       return;
2059     }
2060   switch (ntohs (message->type))
2061     {
2062     case GNUNET_MESSAGE_TYPE_HELLO:
2063 #if DEBUG_TRANSPORT
2064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2065                   "Receiving `%s' message from `%4s'.\n", "HELLO",
2066                   GNUNET_i2s(peer));
2067 #endif
2068       process_hello (plugin, message);
2069 #if DEBUG_TRANSPORT
2070       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2071                   "Sending `%s' message to connecting peer `%4s'.\n", "ACK",
2072                   GNUNET_i2s(peer));
2073 #endif
2074       transmit_to_peer (NULL, 0, &ack, GNUNET_YES, n);
2075       break;
2076     case GNUNET_MESSAGE_TYPE_TRANSPORT_ACK:
2077       n->saw_ack = GNUNET_YES;
2078       /* intentional fall-through! */
2079     default:
2080 #if DEBUG_TRANSPORT
2081       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082                   "Received message of type %u from `%4s', sending to all clients.\n",
2083                   ntohs (message->type),
2084                   GNUNET_i2s(peer));
2085 #endif
2086       /* transmit message to all clients */
2087       im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2088       im->header.size = htons (sizeof (struct InboundMessage) + msize);
2089       im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2090       im->latency = GNUNET_TIME_relative_hton (latency);
2091       im->peer = *peer;
2092       memcpy (&im[1], message, msize);
2093
2094       cpos = clients;
2095       while (cpos != NULL)
2096         {
2097           transmit_to_client (cpos, &im->header, GNUNET_YES);
2098           cpos = cpos->next;
2099         }
2100       GNUNET_free (im);
2101     }
2102   GNUNET_assert ( (service_context == NULL) ||
2103                   (NULL != service_context->neighbour) );
2104 }
2105
2106
2107 /**
2108  * Handle START-message.  This is the first message sent to us
2109  * by any client which causes us to add it to our list.
2110  *
2111  * @param cls closure (always NULL)
2112  * @param client identification of the client
2113  * @param message the actual message
2114  */
2115 static void
2116 handle_start (void *cls,
2117               struct GNUNET_SERVER_Client *client,
2118               const struct GNUNET_MessageHeader *message)
2119 {
2120   struct TransportClient *c;
2121   struct ConnectInfoMessage cim;
2122   struct NeighbourList *n;
2123   struct InboundMessage *im;
2124   struct GNUNET_MessageHeader *ack;
2125
2126 #if DEBUG_TRANSPORT
2127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128               "Received `%s' request from client\n", "START");
2129 #endif
2130   c = clients;
2131   while (c != NULL)
2132     {
2133       if (c->client == client)
2134         {
2135           /* client already on our list! */
2136           GNUNET_break (0);
2137           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2138           return;
2139         }
2140       c = c->next;
2141     }
2142   c = GNUNET_malloc (sizeof (struct TransportClient));
2143   c->next = clients;
2144   clients = c;
2145   c->client = client;
2146   if (our_hello != NULL)
2147     {
2148 #if DEBUG_TRANSPORT
2149       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150                   "Sending our own `%s' to new client\n",
2151                   "HELLO");
2152 #endif
2153       transmit_to_client (c,
2154                           (const struct GNUNET_MessageHeader *) our_hello,
2155                           GNUNET_NO);
2156       /* tell new client about all existing connections */
2157       cim.header.size = htons (sizeof (struct ConnectInfoMessage));
2158       cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
2159       cim.quota_out = htonl (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT / (60 * 1000));
2160       cim.latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_ZERO);  /* FIXME? */
2161       im = GNUNET_malloc (sizeof (struct InboundMessage) +
2162                           sizeof (struct GNUNET_MessageHeader));
2163       im->header.size = htons (sizeof (struct InboundMessage) +
2164                                sizeof (struct GNUNET_MessageHeader));
2165       im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2166       im->latency = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_ZERO);  /* FIXME? */
2167       ack = (struct GNUNET_MessageHeader *) &im[1];
2168       ack->size = htons (sizeof (struct GNUNET_MessageHeader));
2169       ack->type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ACK);
2170       for (n = neighbours; n != NULL; n = n->next)
2171         {
2172           cim.id = n->id;
2173           transmit_to_client (c, &cim.header, GNUNET_NO);
2174           if (n->saw_ack)
2175             {
2176               im->peer = n->id;
2177               transmit_to_client (c, &im->header, GNUNET_NO);
2178             }
2179         }
2180       GNUNET_free (im);
2181     }
2182   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2183 }
2184
2185
2186 /**
2187  * Handle HELLO-message.
2188  *
2189  * @param cls closure (always NULL)
2190  * @param client identification of the client
2191  * @param message the actual message
2192  */
2193 static void
2194 handle_hello (void *cls,
2195               struct GNUNET_SERVER_Client *client,
2196               const struct GNUNET_MessageHeader *message)
2197 {
2198   int ret;
2199
2200 #if DEBUG_TRANSPORT
2201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2202               "Received `%s' request from client\n", "HELLO");
2203 #endif
2204   ret = process_hello (NULL, message);
2205   GNUNET_SERVER_receive_done (client, ret);
2206 }
2207
2208
2209 /**
2210  * Handle SEND-message.
2211  *
2212  * @param cls closure (always NULL)
2213  * @param client identification of the client
2214  * @param message the actual message
2215  */
2216 static void
2217 handle_send (void *cls,
2218              struct GNUNET_SERVER_Client *client,
2219              const struct GNUNET_MessageHeader *message)
2220 {
2221   struct TransportClient *tc;
2222   struct NeighbourList *n;
2223   const struct OutboundMessage *obm;
2224   const struct GNUNET_MessageHeader *obmm;
2225   uint16_t size;
2226   uint16_t msize;
2227
2228   size = ntohs (message->size);
2229   if (size <
2230       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
2231     {
2232       GNUNET_break (0);
2233       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2234       return;
2235     }
2236   obm = (const struct OutboundMessage *) message;
2237 #if DEBUG_TRANSPORT
2238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2239               "Received `%s' request from client with target `%4s'\n",
2240               "SEND", GNUNET_i2s (&obm->peer));
2241 #endif
2242   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
2243   msize = ntohs (obmm->size);
2244   if (size != msize + sizeof (struct OutboundMessage))
2245     {
2246       GNUNET_break (0);
2247       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2248       return;
2249     }
2250   n = find_neighbour (&obm->peer);
2251   if (n == NULL)
2252     n = setup_new_neighbour (&obm->peer);
2253   tc = clients;
2254   while ((tc != NULL) && (tc->client != client))
2255     tc = tc->next;
2256
2257 #if DEBUG_TRANSPORT
2258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259               "Client asked to transmit %u-byte message of type %u to `%4s'\n",
2260               ntohs (obmm->size),
2261               ntohs (obmm->type), GNUNET_i2s (&obm->peer));
2262 #endif
2263   transmit_to_peer (tc, ntohl(obm->priority), obmm, GNUNET_NO, n);
2264   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2265 }
2266
2267
2268 /**
2269  * Handle SET_QUOTA-message.
2270  *
2271  * @param cls closure (always NULL)
2272  * @param client identification of the client
2273  * @param message the actual message
2274  */
2275 static void
2276 handle_set_quota (void *cls,
2277                   struct GNUNET_SERVER_Client *client,
2278                   const struct GNUNET_MessageHeader *message)
2279 {
2280   const struct QuotaSetMessage *qsm =
2281     (const struct QuotaSetMessage *) message;
2282   struct NeighbourList *n;
2283   struct TransportPlugin *p;
2284   struct ReadyList *rl;
2285
2286 #if DEBUG_TRANSPORT
2287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2288               "Received `%s' request from client for peer `%4s'\n",
2289               "SET_QUOTA", GNUNET_i2s (&qsm->peer));
2290 #endif
2291   n = find_neighbour (&qsm->peer);
2292   if (n == NULL)
2293     {
2294       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2295       return;
2296     }
2297   update_quota (n);
2298   if (n->quota_in < ntohl (qsm->quota_in))
2299     n->last_quota_update = GNUNET_TIME_absolute_get ();
2300   n->quota_in = ntohl (qsm->quota_in);
2301   rl = n->plugins;
2302   while (rl != NULL)
2303     {
2304       p = rl->plugin;
2305       p->api->set_receive_quota (p->api->cls,
2306                                  &qsm->peer, ntohl (qsm->quota_in));
2307       rl = rl->next;
2308     }
2309   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2310 }
2311
2312
2313 /**
2314  * Handle TRY_CONNECT-message.
2315  *
2316  * @param cls closure (always NULL)
2317  * @param client identification of the client
2318  * @param message the actual message
2319  */
2320 static void
2321 handle_try_connect (void *cls,
2322                     struct GNUNET_SERVER_Client *client,
2323                     const struct GNUNET_MessageHeader *message)
2324 {
2325   const struct TryConnectMessage *tcm;
2326
2327   tcm = (const struct TryConnectMessage *) message;
2328 #if DEBUG_TRANSPORT
2329   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330               "Received `%s' request from client %p asking to connect to `%4s'\n",
2331               "TRY_CONNECT",
2332               client,
2333               GNUNET_i2s (&tcm->peer));
2334 #endif
2335   if (NULL == find_neighbour (&tcm->peer))
2336     setup_new_neighbour (&tcm->peer);
2337 #if DEBUG_TRANSPORT
2338   else
2339     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2340                 "Client asked to connect to `%4s', but connection already exists\n",
2341                 "TRY_CONNECT", 
2342                 GNUNET_i2s (&tcm->peer));
2343 #endif    
2344   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2345 }
2346
2347 static void
2348 transmit_address_to_client (void *cls, const char *address)
2349 {
2350         struct GNUNET_SERVER_TransmitContext *tc = cls;
2351         size_t slen;
2352
2353         if (NULL == address)
2354                 slen = 0;
2355         else
2356                 slen = strlen (address) + 1;
2357         GNUNET_SERVER_transmit_context_append (tc, address, slen,
2358                                 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2359         if (NULL == address)
2360                 GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
2361 }
2362
2363 /**
2364  * Handle AddressLookup-message.
2365  *
2366  * @param cls closure (always NULL)
2367  * @param client identification of the client
2368  * @param message the actual message
2369  */
2370 static void
2371 handle_address_lookup (void *cls,
2372                       struct GNUNET_SERVER_Client *client,
2373                       const struct GNUNET_MessageHeader *message)
2374 {
2375         const struct AddressLookupMessage *alum;
2376         struct TransportPlugin *lsPlugin;
2377         const char *nameTransport;
2378         const char *address;
2379         uint16_t size;
2380         struct GNUNET_SERVER_TransmitContext *tc;
2381
2382         size = ntohs (message->size);
2383         if (size < sizeof(struct AddressLookupMessage))
2384         {
2385                 GNUNET_break_op (0);
2386                 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2387                 return;
2388         }
2389         alum = (const struct AddressLookupMessage *) message;
2390         uint32_t addressLen = ntohl(alum->addrlen);
2391         if (size <= sizeof(struct AddressLookupMessage) + addressLen)
2392         {
2393                 GNUNET_break_op (0);
2394                 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2395                 return;
2396         }
2397         address = (const char *)&alum[1];
2398         nameTransport = (const char*)&address[addressLen];
2399         if (nameTransport [size - sizeof (struct AddressLookupMessage) - addressLen -1] != '\0')
2400         {
2401                 GNUNET_break_op (0);
2402                 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2403                 return;
2404         }
2405         struct GNUNET_TIME_Absolute timeout= GNUNET_TIME_absolute_ntoh(alum->timeout);
2406         struct GNUNET_TIME_Relative rtimeout = GNUNET_TIME_absolute_get_remaining(timeout);
2407         lsPlugin = find_transport(nameTransport);
2408         if (NULL == lsPlugin)
2409         {
2410                 tc = GNUNET_SERVER_transmit_context_create (client);
2411                 GNUNET_SERVER_transmit_context_append (tc, NULL, 0, GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2412                 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2413                 return;
2414         }
2415         tc = GNUNET_SERVER_transmit_context_create (client);
2416         lsPlugin->api->address_pretty_printer(cls, nameTransport,
2417                                 address, addressLen, GNUNET_YES, rtimeout, &transmit_address_to_client, tc);
2418 }
2419
2420 /**
2421  * List of handlers for the messages understood by this
2422  * service.
2423  */
2424 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2425   {&handle_start, NULL,
2426    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2427   {&handle_hello, NULL,
2428    GNUNET_MESSAGE_TYPE_HELLO, 0},
2429   {&handle_send, NULL,
2430    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2431   {&handle_set_quota, NULL,
2432    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2433   {&handle_try_connect, NULL,
2434    GNUNET_MESSAGE_TYPE_TRANSPORT_TRY_CONNECT,
2435    sizeof (struct TryConnectMessage)},
2436   {&handle_address_lookup, NULL,
2437    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2438    0 },
2439   {NULL, NULL, 0, 0}
2440 };
2441
2442
2443 /**
2444  * Setup the environment for this plugin.
2445  */
2446 static void
2447 create_environment (struct TransportPlugin *plug)
2448 {
2449   plug->env.cfg = cfg;
2450   plug->env.sched = sched;
2451   plug->env.my_public_key = &my_public_key;
2452   plug->env.my_private_key = my_private_key;
2453   plug->env.my_identity = &my_identity;
2454   plug->env.cls = plug;
2455   plug->env.receive = &plugin_env_receive;
2456   plug->env.notify_address = &plugin_env_notify_address;
2457   plug->env.notify_validation = &plugin_env_notify_validation;
2458   plug->env.default_quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2459   plug->env.max_connections = max_connect_per_transport;
2460 }
2461
2462
2463 /**
2464  * Start the specified transport (load the plugin).
2465  */
2466 static void
2467 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2468 {
2469   struct TransportPlugin *plug;
2470   char *libname;
2471
2472   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2473               _("Loading `%s' transport plugin\n"), name);
2474   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2475   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2476   create_environment (plug);
2477   plug->short_name = GNUNET_strdup (name);
2478   plug->lib_name = libname;
2479   plug->next = plugins;
2480   plugins = plug;
2481   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
2482   if (plug->api == NULL)
2483     {
2484       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2485                   _("Failed to load transport plugin for `%s'\n"), name);
2486       GNUNET_free (plug->short_name);
2487       plugins = plug->next;
2488       GNUNET_free (libname);
2489       GNUNET_free (plug);
2490     }
2491 }
2492
2493
2494 /**
2495  * Called whenever a client is disconnected.  Frees our
2496  * resources associated with that client.
2497  *
2498  * @param cls closure
2499  * @param client identification of the client
2500  */
2501 static void
2502 client_disconnect_notification (void *cls,
2503                                 struct GNUNET_SERVER_Client *client)
2504 {
2505   struct TransportClient *pos;
2506   struct TransportClient *prev;
2507   struct ClientMessageQueueEntry *mqe;
2508
2509 #if DEBUG_TRANSPORT
2510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2511               "Client disconnected, cleaning up.\n");
2512 #endif
2513   prev = NULL;
2514   pos = clients;
2515   while ((pos != NULL) && (pos->client != client))
2516     {
2517       prev = pos;
2518       pos = pos->next;
2519     }
2520   if (pos == NULL)
2521     return;
2522   while (NULL != (mqe = pos->message_queue_head))
2523     {
2524       pos->message_queue_head = mqe->next;
2525       GNUNET_free (mqe);
2526     }
2527   pos->message_queue_head = NULL;
2528   if (prev == NULL)
2529     clients = pos->next;
2530   else
2531     prev->next = pos->next;
2532   if (GNUNET_YES == pos->tcs_pending)
2533     {
2534       pos->client = NULL;
2535       return;
2536     }
2537   GNUNET_free (pos);
2538 }
2539
2540
2541 /**
2542  * Function called when the service shuts down.  Unloads our plugins.
2543  *
2544  * @param cls closure, unused
2545  * @param tc task context (unused)
2546  */
2547 static void
2548 unload_plugins (void *cls, 
2549                 const struct GNUNET_SCHEDULER_TaskContext *tc)
2550 {
2551   struct TransportPlugin *plug;
2552   struct AddressList *al;
2553
2554 #if DEBUG_TRANSPORT
2555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2556               "Transport service is unloading plugins...\n");
2557 #endif
2558   while (NULL != (plug = plugins))
2559     {
2560       plugins = plug->next;
2561       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
2562       GNUNET_free (plug->lib_name);
2563       GNUNET_free (plug->short_name);
2564       while (NULL != (al = plug->addresses))
2565         {
2566           plug->addresses = al->next;
2567           GNUNET_free (al);
2568         }
2569       GNUNET_free (plug);
2570     }
2571   if (my_private_key != NULL)
2572     GNUNET_CRYPTO_rsa_key_free (my_private_key);
2573   GNUNET_free_non_null (our_hello);
2574 }
2575
2576
2577 /**
2578  * Initiate transport service.
2579  *
2580  * @param cls closure
2581  * @param s scheduler to use
2582  * @param serv the initialized server
2583  * @param c configuration to use
2584  */
2585 static void
2586 run (void *cls,
2587      struct GNUNET_SCHEDULER_Handle *s,
2588      struct GNUNET_SERVER_Handle *serv, 
2589      const struct GNUNET_CONFIGURATION_Handle *c)
2590 {
2591   char *plugs;
2592   char *pos;
2593   int no_transports;
2594   unsigned long long tneigh;
2595   char *keyfile;
2596
2597   sched = s;
2598   cfg = c;
2599   /* parse configuration */
2600   if ((GNUNET_OK !=
2601        GNUNET_CONFIGURATION_get_value_number (c,
2602                                               "TRANSPORT",
2603                                               "NEIGHBOUR_LIMIT",
2604                                               &tneigh)) ||
2605       (GNUNET_OK !=
2606        GNUNET_CONFIGURATION_get_value_filename (c,
2607                                                 "GNUNETD",
2608                                                 "HOSTKEY", &keyfile)))
2609     {
2610       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2611                   _
2612                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
2613       GNUNET_SCHEDULER_shutdown (s);
2614       return;
2615     }
2616   max_connect_per_transport = (uint32_t) tneigh;
2617   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2618   GNUNET_free (keyfile);
2619   if (my_private_key == NULL)
2620     {
2621       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2622                   _
2623                   ("Transport service could not access hostkey.  Exiting.\n"));
2624       GNUNET_SCHEDULER_shutdown (s);
2625       return;
2626     }
2627   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
2628   GNUNET_CRYPTO_hash (&my_public_key,
2629                       sizeof (my_public_key), &my_identity.hashPubKey);
2630   /* setup notification */
2631   server = serv;
2632   GNUNET_SERVER_disconnect_notify (server,
2633                                    &client_disconnect_notification, NULL);
2634   /* load plugins... */
2635   no_transports = 1;
2636   if (GNUNET_OK ==
2637       GNUNET_CONFIGURATION_get_value_string (c,
2638                                              "TRANSPORT", "PLUGINS", &plugs))
2639     {
2640       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2641                   _("Starting transport plugins `%s'\n"), plugs);
2642       pos = strtok (plugs, " ");
2643       while (pos != NULL)
2644         {
2645           start_transport (server, pos);
2646           no_transports = 0;
2647           pos = strtok (NULL, " ");
2648         }
2649       GNUNET_free (plugs);
2650     }
2651   GNUNET_SCHEDULER_add_delayed (sched,
2652                                 GNUNET_TIME_UNIT_FOREVER_REL,
2653                                 &unload_plugins, NULL);
2654   if (no_transports)
2655     refresh_hello ();
2656 #if DEBUG_TRANSPORT
2657   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2658               _("Transport service ready.\n"));
2659 #endif
2660   /* process client requests */
2661   GNUNET_SERVER_add_handlers (server, handlers);
2662 }
2663
2664
2665 /**
2666  * The main function for the transport service.
2667  *
2668  * @param argc number of arguments from the command line
2669  * @param argv command line arguments
2670  * @return 0 ok, 1 on error
2671  */
2672 int
2673 main (int argc, char *const *argv)
2674 {
2675   return (GNUNET_OK ==
2676           GNUNET_SERVICE_run (argc,
2677                               argv,
2678                               "transport",
2679                               GNUNET_SERVICE_OPTION_NONE,
2680                               &run, NULL)) ? 0 : 1;
2681 }
2682
2683 /* end of gnunet-service-transport.c */