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