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