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