d7bd13317ca13c616109cb1c462b556feb800e23
[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  * Function called by the GNUNET_TRANSPORT_TransmitFunction
812  * upon "completion" of a send request.  This tells the API
813  * that it is now legal to send another message to the given
814  * peer.
815  *
816  * @param cls closure, identifies the entry on the
817  *            message queue that was transmitted and the
818  *            client responsible for queueing the message
819  * @param rl identifies plugin used for the transmission for
820  *           this neighbour; needs to be re-enabled for
821  *           future transmissions
822  * @param target the peer receiving the message
823  * @param result GNUNET_OK on success, if the transmission
824  *           failed, we should not tell the client to transmit
825  *           more messages
826  */
827 static void
828 transmit_send_continuation (void *cls,
829                             struct ReadyList *rl,
830                             const struct GNUNET_PeerIdentity *target,
831                             int result)
832 {
833   struct MessageQueue *mq = cls;
834   struct SendOkMessage send_ok_msg;
835   struct NeighbourList *n;
836
837   GNUNET_assert (mq != NULL);
838   n = mq->neighbour;
839   GNUNET_assert (n != NULL);
840   GNUNET_assert (0 ==
841                  memcmp (&n->id, target,
842                          sizeof (struct GNUNET_PeerIdentity)));
843   if (rl == NULL)
844     {
845       rl = n->plugins;
846       while ((rl != NULL) && (rl->plugin != mq->plugin))
847         rl = rl->next;
848       GNUNET_assert (rl != NULL);
849     }
850   if (result == GNUNET_OK)
851     {
852       rl->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
853     }
854   else
855     {
856       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
857                   "Transmission failed, marking connection as down.\n");
858       rl->connected = GNUNET_NO;
859     }
860   if (!mq->internal_msg)
861     rl->transmit_ready = GNUNET_YES;
862   if (mq->client != NULL)
863     {
864       send_ok_msg.header.size = htons (sizeof (send_ok_msg));
865       send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
866       send_ok_msg.success = htonl (result);
867       send_ok_msg.peer = n->id;
868       transmit_to_client (mq->client, &send_ok_msg.header, GNUNET_NO);
869     }
870   GNUNET_free (mq->message);
871   GNUNET_free (mq);
872   /* one plugin just became ready again, try transmitting
873      another message (if available) */
874   try_transmission_to_peer (n);
875 }
876
877
878 /**
879  * Check the ready list for the given neighbour and
880  * if a plugin is ready for transmission (and if we
881  * have a message), do so!
882  */
883 static void
884 try_transmission_to_peer (struct NeighbourList *neighbour)
885 {
886   struct ReadyList *pos;
887   struct GNUNET_TIME_Relative min_latency;
888   struct ReadyList *rl;
889   struct MessageQueue *mq;
890   struct GNUNET_TIME_Absolute now;
891
892   if (neighbour->messages == NULL)
893     return;                     /* nothing to do */
894   try_alternative_plugins (neighbour);
895   min_latency = GNUNET_TIME_UNIT_FOREVER_REL;
896   rl = NULL;
897   mq = neighbour->messages;
898   now = GNUNET_TIME_absolute_get ();
899   pos = neighbour->plugins;
900   while (pos != NULL)
901     {
902       /* set plugins that are inactive for a long time back to disconnected */
903       if ((pos->timeout.value < now.value) && (pos->connected == GNUNET_YES))
904         {
905 #if DEBUG_TRANSPORT
906           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
907                       "Marking long-time inactive connection to `%4s' as down.\n",
908                       GNUNET_i2s (&neighbour->id));
909 #endif
910           pos->connected = GNUNET_NO;
911         }
912       if (((GNUNET_YES == pos->transmit_ready) ||
913            (mq->internal_msg)) &&
914           (pos->connect_attempts < MAX_CONNECT_RETRY) &&
915           ((rl == NULL) || (min_latency.value > pos->latency.value)))
916         {
917           rl = pos;
918           min_latency = pos->latency;
919         }
920       pos = pos->next;
921     }
922   if (rl == NULL)
923     {
924 #if DEBUG_TRANSPORT
925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
926                   "No plugin ready to transmit message\n");
927 #endif
928       return;                   /* nobody ready */
929     }
930   if (GNUNET_NO == rl->connected)
931     {
932       rl->connect_attempts++;
933       rl->connected = GNUNET_YES;
934 #if DEBUG_TRANSPORT
935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
936               "Establishing fresh connection with `%4s' via plugin `%s'\n",
937               GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
938 #endif
939     }
940   neighbour->messages = mq->next;
941   mq->plugin = rl->plugin;
942   if (!mq->internal_msg)
943     rl->transmit_ready = GNUNET_NO;
944 #if DEBUG_TRANSPORT
945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946               "Giving message of type `%u' for `%4s' to plugin `%s'\n",
947               ntohs (mq->message->type),
948               GNUNET_i2s (&neighbour->id), rl->plugin->short_name);
949 #endif
950   rl->plugin_handle
951     = rl->plugin->api->send (rl->plugin->api->cls,
952                              rl->plugin_handle,
953                              rl,
954                              &neighbour->id,
955                              mq->priority,
956                              mq->message,
957                              GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
958                              &transmit_send_continuation, mq);
959 }
960
961
962 /**
963  * Send the specified message to the specified peer.
964  *
965  * @param client source of the transmission request (can be NULL)
966  * @param priority how important is the message
967  * @param msg message to send
968  * @param is_internal is this an internal message
969  * @param neighbour handle to the neighbour for transmission
970  */
971 static void
972 transmit_to_peer (struct TransportClient *client,
973                   unsigned int priority,
974                   const struct GNUNET_MessageHeader *msg,
975                   int is_internal, struct NeighbourList *neighbour)
976 {
977   struct MessageQueue *mq;
978   struct MessageQueue *mqe;
979   struct GNUNET_MessageHeader *m;
980
981 #if DEBUG_TRANSPORT
982   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
983               _("Sending message of type %u to peer `%4s'\n"),
984               ntohs (msg->type), GNUNET_i2s (&neighbour->id));
985 #endif
986   if (client != NULL)
987     {
988       /* check for duplicate submission */
989       mq = neighbour->messages;
990       while (NULL != mq)
991         {
992           if (mq->client == client)
993             {
994               /* client transmitted to same peer twice
995                  before getting SendOk! */
996               GNUNET_break (0);
997               return;
998             }
999           mq = mq->next;
1000         }
1001     }
1002   mq = GNUNET_malloc (sizeof (struct MessageQueue));
1003   mq->client = client;
1004   m = GNUNET_malloc (ntohs (msg->size));
1005   memcpy (m, msg, ntohs (msg->size));
1006   mq->message = m;
1007   mq->neighbour = neighbour;
1008   mq->internal_msg = is_internal;
1009   mq->priority = priority;
1010
1011   /* find tail */
1012   mqe = neighbour->messages;
1013   if (mqe != NULL)
1014     while (mqe->next != NULL)
1015       mqe = mqe->next;
1016   if (mqe == NULL)
1017     {
1018       /* new head */
1019       neighbour->messages = mq;
1020       try_transmission_to_peer (neighbour);
1021     }
1022   else
1023     {
1024       /* append */
1025       mqe->next = mq;
1026     }
1027 }
1028
1029
1030 struct GeneratorContext
1031 {
1032   struct TransportPlugin *plug_pos;
1033   struct AddressList *addr_pos;
1034   struct GNUNET_TIME_Absolute expiration;
1035 };
1036
1037
1038 static size_t
1039 address_generator (void *cls, size_t max, void *buf)
1040 {
1041   struct GeneratorContext *gc = cls;
1042   size_t ret;
1043
1044   while ((gc->addr_pos == NULL) && (gc->plug_pos != NULL))
1045     {
1046       gc->plug_pos = gc->plug_pos->next;
1047       gc->addr_pos = (gc->plug_pos != NULL) ? gc->plug_pos->addresses : NULL;
1048     }
1049   if (NULL == gc->plug_pos)
1050     return 0;
1051   ret = GNUNET_HELLO_add_address (gc->plug_pos->short_name,
1052                                   gc->expiration,
1053                                   gc->addr_pos->addr,
1054                                   gc->addr_pos->addrlen, buf, max);
1055   gc->addr_pos = gc->addr_pos->next;
1056   return ret;
1057 }
1058
1059
1060 /**
1061  * Construct our HELLO message from all of the addresses of
1062  * all of the transports.
1063  */
1064 static void
1065 refresh_hello ()
1066 {
1067   struct GNUNET_HELLO_Message *hello;
1068   struct TransportClient *cpos;
1069   struct NeighbourList *npos;
1070   struct GeneratorContext gc;
1071
1072 #if DEBUG_TRANSPORT
1073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1074               "Refreshing my `%s'\n",
1075               "HELLO");
1076 #endif
1077   gc.plug_pos = plugins;
1078   gc.addr_pos = plugins != NULL ? plugins->addresses : NULL;
1079   gc.expiration = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1080   hello = GNUNET_HELLO_create (&my_public_key, &address_generator, &gc);
1081   cpos = clients;
1082   while (cpos != NULL)
1083     {
1084       transmit_to_client (cpos,
1085                           (const struct GNUNET_MessageHeader *) hello,
1086                           GNUNET_NO);
1087       cpos = cpos->next;
1088     }
1089
1090   GNUNET_free_non_null (our_hello);
1091   our_hello = hello;
1092   our_hello_version++;
1093   npos = neighbours;
1094   while (npos != NULL)
1095     {
1096 #if DEBUG_TRANSPORT
1097       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1098                   "Transmitting updated `%s' to neighbour `%4s'\n",
1099                   "HELLO",
1100                   GNUNET_i2s(&npos->id));
1101 #endif
1102       transmit_to_peer (NULL, 0,
1103                         (const struct GNUNET_MessageHeader *) our_hello,
1104                         GNUNET_YES, npos);
1105       npos = npos->next;
1106     }
1107 }
1108
1109
1110 /**
1111  * Task used to clean up expired addresses for a plugin.
1112  *
1113  * @param cls closure
1114  * @param tc context
1115  */
1116 static void
1117 expire_address_task (void *cls,
1118                      const struct GNUNET_SCHEDULER_TaskContext *tc);
1119
1120
1121 /**
1122  * Update the list of addresses for this plugin,
1123  * expiring those that are past their expiration date.
1124  *
1125  * @param plugin addresses of which plugin should be recomputed?
1126  * @param fresh set to GNUNET_YES if a new address was added
1127  *        and we need to regenerate the HELLO even if nobody
1128  *        expired
1129  */
1130 static void
1131 update_addresses (struct TransportPlugin *plugin, int fresh)
1132 {
1133   struct GNUNET_TIME_Relative min_remaining;
1134   struct GNUNET_TIME_Relative remaining;
1135   struct GNUNET_TIME_Absolute now;
1136   struct AddressList *pos;
1137   struct AddressList *prev;
1138   struct AddressList *next;
1139   int expired;
1140
1141   if (plugin->address_update_task != GNUNET_SCHEDULER_NO_PREREQUISITE_TASK)
1142     GNUNET_SCHEDULER_cancel (plugin->env.sched, plugin->address_update_task);
1143   plugin->address_update_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1144   now = GNUNET_TIME_absolute_get ();
1145   min_remaining = GNUNET_TIME_UNIT_FOREVER_REL;
1146   expired = GNUNET_NO;
1147   prev = NULL;
1148   pos = plugin->addresses;
1149   while (pos != NULL)
1150     {
1151       next = pos->next;
1152       if (pos->expires.value < now.value)
1153         {
1154           expired = GNUNET_YES;
1155           if (prev == NULL)
1156             plugin->addresses = pos->next;
1157           else
1158             prev->next = pos->next;
1159           GNUNET_free (pos);
1160         }
1161       else
1162         {
1163           remaining = GNUNET_TIME_absolute_get_remaining (pos->expires);
1164           if (remaining.value < min_remaining.value)
1165             min_remaining = remaining;
1166           prev = pos;
1167         }
1168       pos = next;
1169     }
1170
1171   if (expired || fresh)
1172     refresh_hello ();
1173   if (min_remaining.value < GNUNET_TIME_UNIT_FOREVER_REL.value)
1174     plugin->address_update_task
1175       = GNUNET_SCHEDULER_add_delayed (plugin->env.sched,
1176                                       GNUNET_NO,
1177                                       GNUNET_SCHEDULER_PRIORITY_IDLE,
1178                                       GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1179                                       min_remaining,
1180                                       &expire_address_task, plugin);
1181
1182 }
1183
1184
1185 /**
1186  * Task used to clean up expired addresses for a plugin.
1187  *
1188  * @param cls closure
1189  * @param tc context
1190  */
1191 static void
1192 expire_address_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1193 {
1194   struct TransportPlugin *plugin = cls;
1195   plugin->address_update_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1196   update_addresses (plugin, GNUNET_NO);
1197 }
1198
1199
1200 /**
1201  * Function that must be called by each plugin to notify the
1202  * transport service about the addresses under which the transport
1203  * provided by the plugin can be reached.
1204  *
1205  * @param cls closure
1206  * @param name name of the transport that generated the address
1207  * @param addr one of the addresses of the host, NULL for the last address
1208  *        the specific address format depends on the transport
1209  * @param addrlen length of the address
1210  * @param expires when should this address automatically expire?
1211  */
1212 static void
1213 plugin_env_notify_address (void *cls,
1214                            const char *name,
1215                            const void *addr,
1216                            size_t addrlen,
1217                            struct GNUNET_TIME_Relative expires)
1218 {
1219   struct TransportPlugin *p = cls;
1220   struct AddressList *al;
1221   struct GNUNET_TIME_Absolute abex;
1222
1223   abex = GNUNET_TIME_relative_to_absolute (expires);
1224   GNUNET_assert (p == find_transport (name));
1225
1226   al = p->addresses;
1227   while (al != NULL)
1228     {
1229       if ((addrlen == al->addrlen) && (0 == memcmp (addr, &al[1], addrlen)))
1230         {
1231           if (al->expires.value < abex.value)
1232             al->expires = abex;
1233           return;
1234         }
1235       al = al->next;
1236     }
1237 #if DEBUG_TRANSPORT
1238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1239               "Plugin `%s' informs us about a new address `%s'\n", name,
1240               GNUNET_a2s(addr, addrlen));
1241 #endif
1242   al = GNUNET_malloc (sizeof (struct AddressList) + addrlen);
1243   al->addr = &al[1];
1244   al->next = p->addresses;
1245   p->addresses = al;
1246   al->expires = abex;
1247   al->addrlen = addrlen;
1248   memcpy (&al[1], addr, addrlen);
1249   update_addresses (p, GNUNET_YES);
1250 }
1251
1252
1253 struct LookupHelloContext
1254 {
1255   GNUNET_TRANSPORT_AddressCallback iterator;
1256
1257   void *iterator_cls;
1258 };
1259
1260
1261 static int
1262 lookup_address_callback (void *cls,
1263                          const char *tname,
1264                          struct GNUNET_TIME_Absolute expiration,
1265                          const void *addr, size_t addrlen)
1266 {
1267   struct LookupHelloContext *lhc = cls;
1268   lhc->iterator (lhc->iterator_cls, tname, addr, addrlen);
1269   return GNUNET_OK;
1270 }
1271
1272
1273 static void
1274 lookup_hello_callback (void *cls,
1275                        const struct GNUNET_PeerIdentity *peer,
1276                        const struct GNUNET_HELLO_Message *h, uint32_t trust)
1277 {
1278   struct LookupHelloContext *lhc = cls;
1279
1280   if (peer == NULL)
1281     {
1282       lhc->iterator (lhc->iterator_cls, NULL, NULL, 0);
1283       GNUNET_free (lhc);
1284       return;
1285     }
1286   if (h == NULL)
1287     return;
1288   GNUNET_HELLO_iterate_addresses (h,
1289                                   GNUNET_NO, &lookup_address_callback, lhc);
1290 }
1291
1292
1293 /**
1294  * Function that allows a transport to query the known
1295  * network addresses for a given peer.
1296  *
1297  * @param cls closure
1298  * @param timeout after how long should we time out?
1299  * @param target which peer are we looking for?
1300  * @param iter function to call for each known address
1301  * @param iter_cls closure for iter
1302  */
1303 static void
1304 plugin_env_lookup_address (void *cls,
1305                            struct GNUNET_TIME_Relative timeout,
1306                            const struct GNUNET_PeerIdentity *target,
1307                            GNUNET_TRANSPORT_AddressCallback iter,
1308                            void *iter_cls)
1309 {
1310   struct LookupHelloContext *lhc;
1311
1312   lhc = GNUNET_malloc (sizeof (struct LookupHelloContext));
1313   lhc->iterator = iter;
1314   lhc->iterator_cls = iter_cls;
1315   GNUNET_PEERINFO_for_all (cfg,
1316                            sched,
1317                            target, 0, timeout, &lookup_hello_callback, &lhc);
1318 }
1319
1320
1321 /**
1322  * Notify all of our clients about a peer connecting.
1323  */
1324 static void
1325 notify_clients_connect (const struct GNUNET_PeerIdentity *peer,
1326                         struct GNUNET_TIME_Relative latency)
1327 {
1328   struct ConnectInfoMessage cim;
1329   struct TransportClient *cpos;
1330
1331 #if DEBUG_TRANSPORT
1332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333               "Informing clients about peer `%4s' connecting to us\n",
1334               GNUNET_i2s (peer));
1335 #endif
1336   cim.header.size = htons (sizeof (struct ConnectInfoMessage));
1337   cim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1338   cim.quota_out = htonl (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT / (60*1000));
1339   cim.latency = GNUNET_TIME_relative_hton (latency);
1340   memcpy (&cim.id, peer, sizeof (struct GNUNET_PeerIdentity));
1341   cpos = clients;
1342   while (cpos != NULL)
1343     {
1344       transmit_to_client (cpos, &cim.header, GNUNET_NO);
1345       cpos = cpos->next;
1346     }
1347 }
1348
1349
1350 /**
1351  * Notify all of our clients about a peer disconnecting.
1352  */
1353 static void
1354 notify_clients_disconnect (const struct GNUNET_PeerIdentity *peer)
1355 {
1356   struct DisconnectInfoMessage dim;
1357   struct TransportClient *cpos;
1358
1359 #if DEBUG_TRANSPORT
1360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361               "Informing clients about peer `%4s' disconnecting\n",
1362               GNUNET_i2s (peer));
1363 #endif
1364   dim.header.size = htons (sizeof (struct DisconnectInfoMessage));
1365   dim.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1366   dim.reserved = htonl (0);
1367   memcpy (&dim.peer, peer, sizeof (struct GNUNET_PeerIdentity));
1368   cpos = clients;
1369   while (cpos != NULL)
1370     {
1371       transmit_to_client (cpos, &dim.header, GNUNET_NO);
1372       cpos = cpos->next;
1373     }
1374 }
1375
1376
1377 /**
1378  * Copy any validated addresses to buf.
1379  *
1380  * @return 0 once all addresses have been
1381  *         returned
1382  */
1383 static size_t
1384 list_validated_addresses (void *cls, size_t max, void *buf)
1385 {
1386   struct ValidationAddress **va = cls;
1387   size_t ret;
1388
1389   while ((NULL != *va) && ((*va)->ok != GNUNET_YES))
1390     *va = (*va)->next;
1391   if (NULL == *va)
1392     return 0;
1393   ret = GNUNET_HELLO_add_address ((*va)->transport_name,
1394                                   (*va)->expiration,
1395                                   &(*va)[1], (*va)->addr_len, buf, max);
1396   *va = (*va)->next;
1397   return ret;
1398 }
1399
1400
1401 /**
1402  * HELLO validation cleanup task.
1403  */
1404 static void
1405 cleanup_validation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1406 {
1407   struct ValidationAddress *va;
1408   struct ValidationList *pos;
1409   struct ValidationList *prev;
1410   struct GNUNET_TIME_Absolute now;
1411   struct GNUNET_HELLO_Message *hello;
1412   struct GNUNET_PeerIdentity pid;
1413
1414 #if DEBUG_TRANSPORT
1415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1416               "HELLO validation cleanup background task running...\n");
1417 #endif
1418   now = GNUNET_TIME_absolute_get ();
1419   prev = NULL;
1420   pos = pending_validations;
1421   while (pos != NULL)
1422     {
1423       if (pos->timeout.value < now.value)
1424         {
1425           if (prev == NULL)
1426             pending_validations = pos->next;
1427           else
1428             prev->next = pos->next;
1429           va = pos->addresses;
1430           hello = GNUNET_HELLO_create (&pos->publicKey,
1431                                        &list_validated_addresses, &va);
1432           GNUNET_CRYPTO_hash (&pos->publicKey,
1433                               sizeof (struct
1434                                       GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1435                               &pid.hashPubKey);
1436 #if DEBUG_TRANSPORT
1437           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1438                       "Creating persistent `%s' message for peer `%4s' based on confirmed addresses.\n",
1439                       "HELLO", GNUNET_i2s (&pid));
1440 #endif
1441           GNUNET_PEERINFO_add_peer (cfg, sched, &pid, hello);
1442           GNUNET_free (hello);
1443           while (NULL != (va = pos->addresses))
1444             {
1445               pos->addresses = va->next;
1446               GNUNET_free (va->transport_name);
1447               GNUNET_free (va);
1448             }
1449           GNUNET_free (pos);
1450           if (prev == NULL)
1451             pos = pending_validations;
1452           else
1453             pos = prev->next;
1454           continue;
1455         }
1456       prev = pos;
1457       pos = pos->next;
1458     }
1459
1460   /* finally, reschedule cleanup if needed; list is
1461      ordered by timeout, so we need the last element... */
1462   pos = pending_validations;
1463   while ((pos != NULL) && (pos->next != NULL))
1464     pos = pos->next;
1465   if (NULL != pos)
1466     GNUNET_SCHEDULER_add_delayed (sched,
1467                                   GNUNET_NO,
1468                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1469                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1470                                   GNUNET_TIME_absolute_get_remaining
1471                                   (pos->timeout), &cleanup_validation, NULL);
1472 }
1473
1474
1475
1476
1477 /**
1478  * Function that will be called if we receive a validation
1479  * of an address challenge that we transmitted to another
1480  * peer.  Note that the validation should only be considered
1481  * acceptable if the challenge matches AND if the sender
1482  * address is at least a plausible address for this peer
1483  * (otherwise we may be seeing a MiM attack).
1484  *
1485  * @param cls closure
1486  * @param name name of the transport that generated the address
1487  * @param peer who responded to our challenge
1488  * @param challenge the challenge number we presumably used
1489  * @param sender_addr string describing our sender address (as observed
1490  *         by the other peer in human-readable format)
1491  */
1492 static void
1493 plugin_env_notify_validation (void *cls,
1494                               const char *name,
1495                               const struct GNUNET_PeerIdentity *peer,
1496                               uint32_t challenge,
1497                               const char *sender_addr)
1498 {
1499   int all_done;
1500   int matched;
1501   struct ValidationList *pos;
1502   struct ValidationAddress *va;
1503   struct GNUNET_PeerIdentity id;
1504
1505   pos = pending_validations;
1506   while (pos != NULL)
1507     {
1508       GNUNET_CRYPTO_hash (&pos->publicKey,
1509                           sizeof (struct
1510                                   GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1511                           &id.hashPubKey);
1512       if (0 ==
1513           memcmp (peer, &id, sizeof (struct GNUNET_PeerIdentity)))
1514         break;
1515       pos = pos->next;
1516     }
1517   if (pos == NULL)
1518     {
1519       /* TODO: call statistics (unmatched PONG) */
1520       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1521                   _
1522                   ("Received validation response but have no record of a matching validation request. Ignoring.\n"));
1523       return;
1524     }
1525   all_done = GNUNET_YES;
1526   matched = GNUNET_NO;
1527   va = pos->addresses;
1528   while (va != NULL)
1529     {
1530       if (va->challenge == challenge)
1531         {
1532 #if DEBUG_TRANSPORT
1533           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534                       "Confirmed validity of peer address.\n");
1535 #endif
1536           GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1537                       _("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"),
1538                       sender_addr, 
1539                       name);
1540           va->ok = GNUNET_YES;
1541           va->expiration =
1542             GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1543           matched = GNUNET_YES;
1544         }        
1545       if (va->ok != GNUNET_YES)
1546         all_done = GNUNET_NO;
1547       va = va->next;
1548     }
1549   if (GNUNET_NO == matched)
1550     {
1551       /* TODO: call statistics (unmatched PONG) */
1552       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1553                   _
1554                   ("Received `%s' message but have no record of a matching `%s' message. Ignoring.\n"),
1555                   "PONG", "PING");
1556     }
1557   if (GNUNET_YES == all_done)
1558     {
1559       pos->timeout.value = 0;
1560       GNUNET_SCHEDULER_add_delayed (sched,
1561                                     GNUNET_NO,
1562                                     GNUNET_SCHEDULER_PRIORITY_IDLE,
1563                                     GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1564                                     GNUNET_TIME_UNIT_ZERO,
1565                                     &cleanup_validation, NULL);
1566     }
1567 }
1568
1569
1570 struct CheckHelloValidatedContext
1571 {
1572   /**
1573    * Plugin for which we are validating.
1574    */
1575   struct TransportPlugin *plugin;
1576
1577   /**
1578    * Hello that we are validating.
1579    */
1580   struct GNUNET_HELLO_Message *hello;
1581
1582   /**
1583    * Validation list being build.
1584    */
1585   struct ValidationList *e;
1586
1587 };
1588
1589
1590 /**
1591  * Append the given address to the list of entries
1592  * that need to be validated.
1593  */
1594 static int
1595 run_validation (void *cls,
1596                 const char *tname,
1597                 struct GNUNET_TIME_Absolute expiration,
1598                 const void *addr, size_t addrlen)
1599 {
1600   struct ValidationList *e = cls;
1601   struct TransportPlugin *tp;
1602   struct ValidationAddress *va;
1603   struct GNUNET_PeerIdentity id;
1604
1605   tp = find_transport (tname);
1606   if (tp == NULL)
1607     {
1608       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1609                   GNUNET_ERROR_TYPE_BULK,
1610                   _
1611                   ("Transport `%s' not loaded, will not try to validate peer address using this transport.\n"),
1612                   tname);
1613       return GNUNET_OK;
1614     }
1615   GNUNET_CRYPTO_hash (&e->publicKey,
1616                       sizeof (struct
1617                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1618                       &id.hashPubKey);
1619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1620               "Scheduling validation of address `%s' via `%s' for `%4s'\n",
1621               GNUNET_a2s(addr, addrlen),
1622               tname,
1623               GNUNET_i2s(&id));
1624
1625   va = GNUNET_malloc (sizeof (struct ValidationAddress) + addrlen);
1626   va->next = e->addresses;
1627   e->addresses = va;
1628   va->transport_name = GNUNET_strdup (tname);
1629   va->addr_len = addrlen;
1630   va->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1631                                             (unsigned int) -1);
1632   memcpy (&va[1], addr, addrlen);
1633   return GNUNET_OK;
1634 }
1635
1636
1637 /**
1638  * Check if addresses in validated hello "h" overlap with
1639  * those in "chvc->hello" and update "chvc->hello" accordingly,
1640  * removing those addresses that have already been validated.
1641  */
1642 static void
1643 check_hello_validated (void *cls,
1644                        const struct GNUNET_PeerIdentity *peer,
1645                        const struct GNUNET_HELLO_Message *h, 
1646                        uint32_t trust)
1647 {
1648   struct CheckHelloValidatedContext *chvc = cls;
1649   struct ValidationAddress *va;
1650   struct TransportPlugin *tp;
1651   int first_call;
1652   struct GNUNET_PeerIdentity apeer;
1653
1654   first_call = GNUNET_NO;
1655   if (chvc->e == NULL)
1656     {
1657       first_call = GNUNET_YES;
1658       chvc->e = GNUNET_malloc (sizeof (struct ValidationList));
1659       GNUNET_assert (GNUNET_OK ==
1660                      GNUNET_HELLO_get_key (h != NULL ? h : chvc->hello,
1661                                            &chvc->e->publicKey));
1662       chvc->e->timeout =
1663         GNUNET_TIME_relative_to_absolute (HELLO_VERIFICATION_TIMEOUT);
1664       chvc->e->next = pending_validations;
1665       pending_validations = chvc->e;
1666     }
1667   if (h != NULL)
1668     {
1669       GNUNET_HELLO_iterate_new_addresses (chvc->hello,
1670                                           h,
1671                                           GNUNET_TIME_absolute_get (),
1672                                           &run_validation, chvc->e);
1673     }
1674   else if (GNUNET_YES == first_call)
1675     {
1676       /* no existing HELLO, all addresses are new */
1677       GNUNET_HELLO_iterate_addresses (chvc->hello,
1678                                       GNUNET_NO, &run_validation, chvc->e);
1679     }
1680   if (h != NULL)
1681     return;                     /* wait for next call */
1682   /* finally, transmit validation attempts */
1683   GNUNET_assert (GNUNET_OK ==
1684                  GNUNET_HELLO_get_id (chvc->hello,
1685                                       &apeer));
1686   va = chvc->e->addresses;
1687   while (va != NULL)
1688     {
1689 #if DEBUG_TRANSPORT
1690       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691                   "Establishing `%s' connection to validate `%s' of `%4s'\n",
1692                   va->transport_name,
1693                   "HELLO",
1694                   GNUNET_i2s (&apeer));
1695 #endif
1696       tp = find_transport (va->transport_name);
1697       GNUNET_assert (tp != NULL);
1698       if (GNUNET_OK !=
1699           tp->api->validate (tp->api->cls,
1700                              &apeer,
1701                              va->challenge,
1702                              HELLO_VERIFICATION_TIMEOUT,
1703                              &va[1],
1704                              va->addr_len))
1705         va->ok = GNUNET_SYSERR;
1706       va = va->next;
1707     }
1708   if (chvc->e->next == NULL)
1709     GNUNET_SCHEDULER_add_delayed (sched,
1710                                   GNUNET_NO,
1711                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1712                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1713                                   GNUNET_TIME_absolute_get_remaining
1714                                   (chvc->e->timeout), &cleanup_validation,
1715                                   NULL);
1716   GNUNET_free (chvc);
1717 }
1718
1719
1720 /**
1721  * Process HELLO-message.
1722  *
1723  * @param plugin transport involved, may be NULL
1724  * @param message the actual message
1725  * @return GNUNET_OK if the HELLO was well-formed, GNUNET_SYSERR otherwise
1726  */
1727 static int
1728 process_hello (struct TransportPlugin *plugin,
1729                const struct GNUNET_MessageHeader *message)
1730 {
1731   struct ValidationList *e;
1732   uint16_t hsize;
1733   struct GNUNET_PeerIdentity target;
1734   const struct GNUNET_HELLO_Message *hello;
1735   struct CheckHelloValidatedContext *chvc;
1736   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded publicKey;
1737
1738   hsize = ntohs (message->size);
1739   if ((ntohs (message->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1740       (hsize < sizeof (struct GNUNET_MessageHeader)))
1741     {
1742       GNUNET_break (0);
1743       return GNUNET_SYSERR;
1744     }
1745   /* first, check if load is too high */
1746   if (GNUNET_OS_load_cpu_get (cfg) > 100)
1747     {
1748       /* TODO: call to stats? */
1749       return GNUNET_OK;
1750     }
1751   hello = (const struct GNUNET_HELLO_Message *) message;
1752   if (GNUNET_OK != GNUNET_HELLO_get_key (hello, &publicKey))
1753     {
1754       GNUNET_break_op (0);
1755       return GNUNET_SYSERR;
1756     }
1757   GNUNET_CRYPTO_hash (&publicKey,
1758                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1759                       &target.hashPubKey);
1760 #if DEBUG_TRANSPORT
1761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1762               "Processing `%s' message for `%4s'\n",
1763               "HELLO", GNUNET_i2s (&target));
1764 #endif
1765   /* check if a HELLO for this peer is already on the validation list */
1766   e = pending_validations;
1767   while (e != NULL)
1768     {
1769       if (0 == memcmp (&e->publicKey,
1770                        &publicKey,
1771                        sizeof (struct
1772                                GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
1773         {
1774           /* TODO: call to stats? */
1775 #if DEBUG_TRANSPORT
1776           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1777                       "`%s' message for peer `%4s' is already pending; ignoring new message\n",
1778                       "HELLO", GNUNET_i2s (&target));
1779 #endif    
1780           return GNUNET_OK;
1781         }
1782       e = e->next;
1783     }
1784   chvc = GNUNET_malloc (sizeof (struct CheckHelloValidatedContext) + hsize);
1785   chvc->plugin = plugin;
1786   chvc->hello = (struct GNUNET_HELLO_Message *) &chvc[1];
1787   memcpy (chvc->hello, hello, hsize);
1788   /* finally, check if HELLO was previously validated
1789      (continuation will then schedule actual validation) */
1790   GNUNET_PEERINFO_for_all (cfg,
1791                            sched,
1792                            &target,
1793                            0,
1794                            HELLO_VERIFICATION_TIMEOUT,
1795                            &check_hello_validated, chvc);
1796   return GNUNET_OK;
1797 }
1798
1799
1800
1801 /**
1802  * The peer specified by the given neighbour has timed-out.  Update
1803  * our state and do the necessary notifications.  Also notifies
1804  * our clients that the neighbour is now officially gone.
1805  *
1806  * @param n the neighbour list entry for the peer
1807  */
1808 static void
1809 disconnect_neighbour (struct NeighbourList *n)
1810 {
1811   struct ReadyList *rpos;
1812   struct NeighbourList *npos;
1813   struct NeighbourList *nprev;
1814   struct MessageQueue *mq;
1815
1816 #if DEBUG_TRANSPORT
1817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1818               "Disconnecting from neighbour\n");
1819 #endif
1820   /* remove n from neighbours list */
1821   nprev = NULL;
1822   npos = neighbours;
1823   while ((npos != NULL) && (npos != n))
1824     {
1825       nprev = npos;
1826       npos = npos->next;
1827     }
1828   GNUNET_assert (npos != NULL);
1829   if (nprev == NULL)
1830     neighbours = n->next;
1831   else
1832     nprev->next = n->next;
1833
1834   /* notify all clients about disconnect */
1835   notify_clients_disconnect (&n->id);
1836
1837   /* clean up all plugins, cancel connections & pending transmissions */
1838   while (NULL != (rpos = n->plugins))
1839     {
1840       n->plugins = rpos->next;
1841       GNUNET_assert (rpos->neighbour == n);
1842       rpos->plugin->api->cancel (rpos->plugin->api->cls,
1843                                  rpos->plugin_handle, rpos, &n->id);
1844       GNUNET_free (rpos);
1845     }
1846
1847   /* free all messages on the queue */
1848   while (NULL != (mq = n->messages))
1849     {
1850       n->messages = mq->next;
1851       GNUNET_assert (mq->neighbour == n);
1852       GNUNET_free (mq);
1853     }
1854
1855   /* finally, free n itself */
1856   GNUNET_free (n);
1857 }
1858
1859
1860 /**
1861  * Add an entry for each of our transport plugins
1862  * (that are able to send) to the list of plugins
1863  * for this neighbour.
1864  *
1865  * @param neighbour to initialize
1866  */
1867 static void
1868 add_plugins (struct NeighbourList *neighbour)
1869 {
1870   struct TransportPlugin *tp;
1871   struct ReadyList *rl;
1872
1873   neighbour->retry_plugins_time
1874     = GNUNET_TIME_relative_to_absolute (PLUGIN_RETRY_FREQUENCY);
1875   tp = plugins;
1876   while (tp != NULL)
1877     {
1878       if (tp->api->send != NULL)
1879         {
1880           rl = GNUNET_malloc (sizeof (struct ReadyList));
1881           rl->next = neighbour->plugins;
1882           neighbour->plugins = rl;
1883           rl->plugin = tp;
1884           rl->neighbour = neighbour;
1885           rl->transmit_ready = GNUNET_YES;
1886         }
1887       tp = tp->next;
1888     }
1889 }
1890
1891
1892 static void
1893 neighbour_timeout_task (void *cls,
1894                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1895 {
1896   struct NeighbourList *n = cls;
1897
1898 #if DEBUG_TRANSPORT
1899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1900               "Neighbour has timed out!\n");
1901 #endif
1902   n->timeout_task = GNUNET_SCHEDULER_NO_PREREQUISITE_TASK;
1903   disconnect_neighbour (n);
1904 }
1905
1906
1907
1908 /**
1909  * Create a fresh entry in our neighbour list for the given peer.
1910  * Will try to transmit our current HELLO to the new neighbour.  Also
1911  * notifies our clients about the new "connection".
1912  *
1913  * @param peer the peer for which we create the entry
1914  * @return the new neighbour list entry
1915  */
1916 static struct NeighbourList *
1917 setup_new_neighbour (const struct GNUNET_PeerIdentity *peer)
1918 {
1919   struct NeighbourList *n;
1920
1921 #if DEBUG_TRANSPORT
1922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1923               "Setting up new neighbour `%4s', sending our HELLO to introduce ourselves\n",
1924               GNUNET_i2s (peer));
1925 #endif
1926   GNUNET_assert (our_hello != NULL);
1927   n = GNUNET_malloc (sizeof (struct NeighbourList));
1928   n->next = neighbours;
1929   neighbours = n;
1930   n->id = *peer;
1931   n->last_quota_update = GNUNET_TIME_absolute_get ();
1932   n->peer_timeout =
1933     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1934   n->quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
1935   add_plugins (n);
1936   n->timeout_task = GNUNET_SCHEDULER_add_delayed (sched,
1937                                                   GNUNET_NO,
1938                                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
1939                                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1940                                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1941                                                   &neighbour_timeout_task, n);
1942   transmit_to_peer (NULL, 0,
1943                     (const struct GNUNET_MessageHeader *) our_hello,
1944                     GNUNET_YES, n);
1945   notify_clients_connect (peer, GNUNET_TIME_UNIT_FOREVER_REL);
1946   return n;
1947 }
1948
1949
1950 /**
1951  * Function called by the plugin for each received message.
1952  * Update data volumes, possibly notify plugins about
1953  * reducing the rate at which they read from the socket
1954  * and generally forward to our receive callback.
1955  *
1956  * @param plugin_context value to pass to this plugin
1957  *        to respond to the given peer (use is optional,
1958  *        but may speed up processing)
1959  * @param service_context value passed to the transport-service
1960  *        to identify the neighbour; will be NULL on the first
1961  *        call for a given peer
1962  * @param latency estimated latency for communicating with the
1963  *             given peer
1964  * @param peer (claimed) identity of the other peer
1965  * @param message the message, NULL if peer was disconnected
1966  * @return the new service_context that the plugin should use
1967  *         for future receive calls for messages from this
1968  *         particular peer
1969  */
1970 static struct ReadyList *
1971 plugin_env_receive (void *cls,
1972                     void *plugin_context,
1973                     struct ReadyList *service_context,
1974                     struct GNUNET_TIME_Relative latency,
1975                     const struct GNUNET_PeerIdentity *peer,
1976                     const struct GNUNET_MessageHeader *message)
1977 {
1978   const struct GNUNET_MessageHeader ack = {
1979     htons (sizeof (struct GNUNET_MessageHeader)),
1980     htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ACK)
1981   };
1982   struct TransportPlugin *plugin = cls;
1983   struct TransportClient *cpos;
1984   struct InboundMessage *im;
1985   uint16_t msize;
1986   struct NeighbourList *n;
1987
1988   if (service_context != NULL)
1989     {
1990       n = service_context->neighbour;
1991       GNUNET_assert (n != NULL);
1992     }
1993   else
1994     {
1995       n = find_neighbour (peer);
1996       if (n == NULL)
1997         {
1998           if (message == NULL)
1999             return NULL;        /* disconnect of peer already marked down */
2000           n = setup_new_neighbour (peer);
2001         }
2002       service_context = n->plugins;
2003       while ((service_context != NULL) && (plugin != service_context->plugin))
2004         service_context = service_context->next;
2005       GNUNET_assert ((plugin->api->send == NULL) ||
2006                      (service_context != NULL));
2007     }
2008   if (message == NULL)
2009     {
2010       if ((service_context != NULL) &&
2011           (service_context->plugin_handle == plugin_context))
2012         {
2013           service_context->connected = GNUNET_NO;
2014           service_context->plugin_handle = NULL;
2015         }
2016       /* TODO: call stats */
2017       return NULL;
2018     }
2019 #if DEBUG_TRANSPORT
2020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2021               "Processing message of type `%u' received by plugin...\n",
2022               ntohs (message->type));
2023 #endif
2024   if (service_context != NULL)
2025     {
2026       if (service_context->connected == GNUNET_NO)
2027         {
2028           service_context->connected = GNUNET_YES;
2029           service_context->transmit_ready = GNUNET_YES;
2030           service_context->connect_attempts++;
2031         }
2032       service_context->timeout
2033         = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2034       service_context->plugin_handle = plugin_context;
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, GNUNET_NO,
2045                                   GNUNET_SCHEDULER_PRIORITY_IDLE,
2046                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
2047                                   GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2048                                   &neighbour_timeout_task, n);
2049   update_quota (n);
2050   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
2051     {
2052       /* dropping message due to frequent inbound volume violations! */
2053       GNUNET_log (GNUNET_ERROR_TYPE_WARNING |
2054                   GNUNET_ERROR_TYPE_BULK,
2055                   _
2056                   ("Dropping incoming message due to repeated bandwidth quota violations.\n"));
2057       /* TODO: call stats */
2058       GNUNET_assert (NULL != service_context->neighbour);
2059       return service_context;
2060     }
2061   switch (ntohs (message->type))
2062     {
2063     case GNUNET_MESSAGE_TYPE_HELLO:
2064 #if DEBUG_TRANSPORT
2065       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066                   "Receiving `%s' message from `%4s'.\n", "HELLO",
2067                   GNUNET_i2s(peer));
2068 #endif
2069       process_hello (plugin, message);
2070 #if DEBUG_TRANSPORT
2071       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2072                   "Sending `%s' message to connecting peer `%4s'.\n", "ACK",
2073                   GNUNET_i2s(peer));
2074 #endif
2075       transmit_to_peer (NULL, 0, &ack, GNUNET_YES, n);
2076       break;
2077     case GNUNET_MESSAGE_TYPE_TRANSPORT_ACK:
2078       n->saw_ack = GNUNET_YES;
2079       /* intentional fall-through! */
2080     default:
2081 #if DEBUG_TRANSPORT
2082       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2083                   "Received message of type %u from `%4s', sending to all clients.\n",
2084                   ntohs (message->type),
2085                   GNUNET_i2s(peer));
2086 #endif
2087       /* transmit message to all clients */
2088       im = GNUNET_malloc (sizeof (struct InboundMessage) + msize);
2089       im->header.size = htons (sizeof (struct InboundMessage) + msize);
2090       im->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_RECV);
2091       im->latency = GNUNET_TIME_relative_hton (latency);
2092       im->peer = *peer;
2093       memcpy (&im[1], message, msize);
2094
2095       cpos = clients;
2096       while (cpos != NULL)
2097         {
2098           transmit_to_client (cpos, &im->header, GNUNET_YES);
2099           cpos = cpos->next;
2100         }
2101       GNUNET_free (im);
2102     }
2103   GNUNET_assert (NULL != service_context->neighbour);
2104   return service_context;
2105 }
2106
2107
2108 /**
2109  * Handle START-message.  This is the first message sent to us
2110  * by any client which causes us to add it to our list.
2111  *
2112  * @param cls closure (always NULL)
2113  * @param client identification of the client
2114  * @param message the actual message
2115  */
2116 static void
2117 handle_start (void *cls,
2118               struct GNUNET_SERVER_Client *client,
2119               const struct GNUNET_MessageHeader *message)
2120 {
2121   struct TransportClient *c;
2122   struct ConnectInfoMessage cim;
2123   struct NeighbourList *n;
2124   struct InboundMessage *im;
2125   struct GNUNET_MessageHeader *ack;
2126
2127 #if DEBUG_TRANSPORT
2128   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2129               "Received `%s' request from client\n", "START");
2130 #endif
2131   c = clients;
2132   while (c != NULL)
2133     {
2134       if (c->client == client)
2135         {
2136           /* client already on our list! */
2137           GNUNET_break (0);
2138           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2139           return;
2140         }
2141       c = c->next;
2142     }
2143   c = GNUNET_malloc (sizeof (struct TransportClient));
2144   c->next = clients;
2145   clients = c;
2146   c->client = client;
2147   if (our_hello != NULL)
2148     {
2149 #if DEBUG_TRANSPORT
2150       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151                   "Sending our own HELLO to new client\n");
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 asking to connect to `%4s'\n",
2331               "TRY_CONNECT", GNUNET_i2s (&tcm->peer));
2332 #endif
2333   if (NULL == find_neighbour (&tcm->peer))
2334     setup_new_neighbour (&tcm->peer);
2335   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2336 }
2337
2338
2339 /**
2340  * List of handlers for the messages understood by this
2341  * service.
2342  */
2343 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2344   {&handle_start, NULL,
2345    GNUNET_MESSAGE_TYPE_TRANSPORT_START, 0},
2346   {&handle_hello, NULL,
2347    GNUNET_MESSAGE_TYPE_HELLO, 0},
2348   {&handle_send, NULL,
2349    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
2350   {&handle_set_quota, NULL,
2351    GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA, sizeof (struct QuotaSetMessage)},
2352   {&handle_try_connect, NULL,
2353    GNUNET_MESSAGE_TYPE_TRANSPORT_TRY_CONNECT,
2354    sizeof (struct TryConnectMessage)},
2355   {NULL, NULL, 0, 0}
2356 };
2357
2358
2359 /**
2360  * Setup the environment for this plugin.
2361  */
2362 static void
2363 create_environment (struct TransportPlugin *plug)
2364 {
2365   plug->env.cfg = cfg;
2366   plug->env.sched = sched;
2367   plug->env.my_public_key = &my_public_key;
2368   plug->env.my_private_key = my_private_key;
2369   plug->env.my_identity = &my_identity;
2370   plug->env.cls = plug;
2371   plug->env.receive = &plugin_env_receive;
2372   plug->env.lookup = &plugin_env_lookup_address;
2373   plug->env.notify_address = &plugin_env_notify_address;
2374   plug->env.notify_validation = &plugin_env_notify_validation;
2375   plug->env.default_quota_in = (GNUNET_CONSTANTS_DEFAULT_BPM_IN_OUT + 59999) / (60 * 1000);
2376   plug->env.max_connections = max_connect_per_transport;
2377 }
2378
2379
2380 /**
2381  * Start the specified transport (load the plugin).
2382  */
2383 static void
2384 start_transport (struct GNUNET_SERVER_Handle *server, const char *name)
2385 {
2386   struct TransportPlugin *plug;
2387   char *libname;
2388
2389   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2390               _("Loading `%s' transport plugin\n"), name);
2391   GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", name);
2392   plug = GNUNET_malloc (sizeof (struct TransportPlugin));
2393   create_environment (plug);
2394   plug->short_name = GNUNET_strdup (name);
2395   plug->lib_name = libname;
2396   plug->next = plugins;
2397   plugins = plug;
2398   plug->api = GNUNET_PLUGIN_load (libname, &plug->env);
2399   if (plug->api == NULL)
2400     {
2401       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2402                   _("Failed to load transport plugin for `%s'\n"), name);
2403       GNUNET_free (plug->short_name);
2404       plugins = plug->next;
2405       GNUNET_free (libname);
2406       GNUNET_free (plug);
2407     }
2408 }
2409
2410
2411 /**
2412  * Called whenever a client is disconnected.  Frees our
2413  * resources associated with that client.
2414  *
2415  * @param cls closure
2416  * @param client identification of the client
2417  */
2418 static void
2419 client_disconnect_notification (void *cls,
2420                                 struct GNUNET_SERVER_Client *client)
2421 {
2422   struct TransportClient *pos;
2423   struct TransportClient *prev;
2424   struct ClientMessageQueueEntry *mqe;
2425
2426 #if DEBUG_TRANSPORT
2427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2428               "Client disconnected, cleaning up.\n");
2429 #endif
2430   prev = NULL;
2431   pos = clients;
2432   while ((pos != NULL) && (pos->client != client))
2433     {
2434       prev = pos;
2435       pos = pos->next;
2436     }
2437   if (pos == NULL)
2438     return;
2439   while (NULL != (mqe = pos->message_queue_head))
2440     {
2441       pos->message_queue_head = mqe->next;
2442       GNUNET_free (mqe);
2443     }
2444   pos->message_queue_head = NULL;
2445   if (prev == NULL)
2446     clients = pos->next;
2447   else
2448     prev->next = pos->next;
2449   if (GNUNET_YES == pos->tcs_pending)
2450     {
2451       pos->client = NULL;
2452       return;
2453     }
2454   GNUNET_free (pos);
2455 }
2456
2457
2458 /**
2459  * Initiate transport service.
2460  *
2461  * @param cls closure
2462  * @param s scheduler to use
2463  * @param serv the initialized server
2464  * @param c configuration to use
2465  */
2466 static void
2467 run (void *cls,
2468      struct GNUNET_SCHEDULER_Handle *s,
2469      struct GNUNET_SERVER_Handle *serv, struct GNUNET_CONFIGURATION_Handle *c)
2470 {
2471   char *plugs;
2472   char *pos;
2473   int no_transports;
2474   unsigned long long tneigh;
2475   char *keyfile;
2476
2477   sched = s;
2478   cfg = c;
2479   /* parse configuration */
2480   if ((GNUNET_OK !=
2481        GNUNET_CONFIGURATION_get_value_number (c,
2482                                               "TRANSPORT",
2483                                               "NEIGHBOUR_LIMIT",
2484                                               &tneigh)) ||
2485       (GNUNET_OK !=
2486        GNUNET_CONFIGURATION_get_value_filename (c,
2487                                                 "GNUNETD",
2488                                                 "HOSTKEY", &keyfile)))
2489     {
2490       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2491                   _
2492                   ("Transport service is lacking key configuration settings.  Exiting.\n"));
2493       GNUNET_SCHEDULER_shutdown (s);
2494       return;
2495     }
2496   max_connect_per_transport = (uint32_t) tneigh;
2497   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
2498   GNUNET_free (keyfile);
2499   if (my_private_key == NULL)
2500     {
2501       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2502                   _
2503                   ("Transport service could not access hostkey.  Exiting.\n"));
2504       GNUNET_SCHEDULER_shutdown (s);
2505       return;
2506     }
2507   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
2508   GNUNET_CRYPTO_hash (&my_public_key,
2509                       sizeof (my_public_key), &my_identity.hashPubKey);
2510   /* setup notification */
2511   server = serv;
2512   GNUNET_SERVER_disconnect_notify (server,
2513                                    &client_disconnect_notification, NULL);
2514   /* load plugins... */
2515   no_transports = 1;
2516   if (GNUNET_OK ==
2517       GNUNET_CONFIGURATION_get_value_string (c,
2518                                              "TRANSPORT", "PLUGINS", &plugs))
2519     {
2520       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2521                   _("Starting transport plugins `%s'\n"), plugs);
2522       pos = strtok (plugs, " ");
2523       while (pos != NULL)
2524         {
2525           start_transport (server, pos);
2526           no_transports = 0;
2527           pos = strtok (NULL, " ");
2528         }
2529       GNUNET_free (plugs);
2530     }
2531   if (no_transports)
2532     refresh_hello ();
2533 #if DEBUG_TRANSPORT
2534   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2535               _("Transport service ready.\n"));
2536 #endif
2537   /* process client requests */
2538   GNUNET_SERVER_add_handlers (server, handlers);
2539 }
2540
2541
2542 /**
2543  * Function called when the service shuts
2544  * down.  Unloads our plugins.
2545  *
2546  * @param cls closure
2547  * @param cfg configuration to use
2548  */
2549 static void
2550 unload_plugins (void *cls, struct GNUNET_CONFIGURATION_Handle *cfg)
2551 {
2552   struct TransportPlugin *plug;
2553   struct AddressList *al;
2554
2555 #if DEBUG_TRANSPORT
2556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2557               "Transport service is unloading plugins...\n");
2558 #endif
2559   while (NULL != (plug = plugins))
2560     {
2561       plugins = plug->next;
2562       GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
2563       GNUNET_free (plug->lib_name);
2564       GNUNET_free (plug->short_name);
2565       while (NULL != (al = plug->addresses))
2566         {
2567           plug->addresses = al->next;
2568           GNUNET_free (al);
2569         }
2570       GNUNET_free (plug);
2571     }
2572   if (my_private_key != NULL)
2573     GNUNET_CRYPTO_rsa_key_free (my_private_key);
2574 }
2575
2576
2577 /**
2578  * The main function for the transport service.
2579  *
2580  * @param argc number of arguments from the command line
2581  * @param argv command line arguments
2582  * @return 0 ok, 1 on error
2583  */
2584 int
2585 main (int argc, char *const *argv)
2586 {
2587   return (GNUNET_OK ==
2588           GNUNET_SERVICE_run (argc,
2589                               argv,
2590                               "transport",
2591                               &run, NULL, &unload_plugins, NULL)) ? 0 : 1;
2592 }
2593
2594 /* end of gnunet-service-transport.c */