fixes
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 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/plugin_transport_tcp.c
23  * @brief Implementation of the TCP transport service
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_hello_lib.h"
29 #include "gnunet_network_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_peerinfo_service.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_resolver_service.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_service_lib.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_transport_service.h"
39 #include "plugin_transport.h"
40 #include "transport.h"
41
42 #define DEBUG_TCP GNUNET_YES
43
44 /**
45  * After how long do we expire an address that we
46  * learned from another peer if it is not reconfirmed
47  * by anyone?
48  */
49 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
50
51 /**
52  * How long until we give up on transmitting the welcome message?
53  */
54 #define WELCOME_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
55
56 /**
57  * How long until we give up on transmitting the welcome message?
58  */
59 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
60
61 /**
62  * For how many messages back to we keep transmission times?
63  */
64 #define ACK_LOG_SIZE 32
65
66
67
68 /**
69  * Message used to ask a peer to validate receipt (to check an address
70  * from a HELLO).  Followed by the address used.  Note that the
71  * recipients response does not affirm that he has this address,
72  * only that he got the challenge message.
73  */
74 struct ValidationChallengeMessage
75 {
76
77   /**
78    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING
79    */
80   struct GNUNET_MessageHeader header;
81
82   /**
83    * Random challenge number (in network byte order).
84    */
85   uint32_t challenge GNUNET_PACKED;
86
87   /**
88    * Who is the intended recipient?
89    */
90   struct GNUNET_PeerIdentity target;
91
92 };
93
94
95 /**
96  * Message used to validate a HELLO.  The challenge is included in the
97  * confirmation to make matching of replies to requests possible.  The
98  * signature signs the original challenge number, our public key, the
99  * sender's address (so that the sender can check that the address we
100  * saw is plausible for him and possibly detect a MiM attack) and a
101  * timestamp (to limit replay).<p>
102  *
103  * This message is followed by the address of the
104  * client that we are observing (which is part of what
105  * is being signed).
106  */
107 struct ValidationChallengeResponse
108 {
109
110   /**
111    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG
112    */
113   struct GNUNET_MessageHeader header;
114
115   /**
116    * For padding, always zero.
117    */
118   uint32_t reserved GNUNET_PACKED;
119
120   /**
121    * Signature.
122    */
123   struct GNUNET_CRYPTO_RsaSignature signature;
124
125   /**
126    * What are we signing and why?
127    */
128   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
129
130   /**
131    * Random challenge number (in network byte order).
132    */
133   uint32_t challenge GNUNET_PACKED;
134
135   /**
136    * Who signed this message?
137    */
138   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
139
140 };
141
142
143
144 /**
145  * Initial handshake message for a session.  This header
146  * is followed by the address that the other peer used to
147  * connect to us (so that we may learn it) or the address
148  * that the other peer got from the accept call.
149  */
150 struct WelcomeMessage
151 {
152   struct GNUNET_MessageHeader header;
153
154   /**
155    * Identity of the node connecting (TCP client)
156    */
157   struct GNUNET_PeerIdentity clientIdentity;
158
159 };
160
161
162 /**
163  * Encapsulation for normal TCP traffic.
164  */
165 struct DataMessage
166 {
167   struct GNUNET_MessageHeader header;
168
169   /**
170    * For alignment.
171    */
172   uint32_t reserved GNUNET_PACKED;
173
174   /**
175    * Number of the last message that was received from the other peer.
176    */
177   uint64_t ack_in GNUNET_PACKED;
178
179   /**
180    * Number of this outgoing message.
181    */
182   uint64_t ack_out GNUNET_PACKED;
183
184   /**
185    * How long was sending this ack delayed by the other peer
186    * (estimate).  The receiver of this message can use the delay
187    * between sending his message number 'ack' and receiving this ack
188    * minus the delay as an estimate of the round-trip time.
189    */
190   struct GNUNET_TIME_RelativeNBO delay;
191
192 };
193
194
195 /**
196  * Encapsulation of all of the state of the plugin.
197  */
198 struct Plugin;
199
200
201 /**
202  * Information kept for each message that is yet to
203  * be transmitted.
204  */
205 struct PendingMessage
206 {
207
208   /**
209    * This is a linked list.
210    */
211   struct PendingMessage *next;
212
213   /**
214    * The pending message, pointer to the end
215    * of this struct, do not free!
216    */
217   struct GNUNET_MessageHeader *msg;
218
219
220   /**
221    * Continuation function to call once the message
222    * has been sent.  Can be  NULL if there is no
223    * continuation to call.
224    */
225   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
226
227   /**
228    * Closure for transmit_cont.
229    */
230   void *transmit_cont_cls;
231
232   /**
233    * Timeout value for the pending message.
234    */
235   struct GNUNET_TIME_Absolute timeout;
236
237   /**
238    * GNUNET_YES if this is a welcome message;
239    * otherwise this should be a DATA message.
240    */
241   int is_welcome;
242
243 };
244
245
246 /**
247  * Session handle for TCP connections.
248  */
249 struct Session
250 {
251
252   /**
253    * Stored in a linked list.
254    */
255   struct Session *next;
256
257   /**
258    * Pointer to the global plugin struct.
259    */
260   struct Plugin *plugin;
261
262   /**
263    * The client (used to identify this connection)
264    */
265   struct GNUNET_SERVER_Client *client;
266
267   /**
268    * gnunet-service-transport context for this connection.
269    */
270   struct ReadyList *service_context;
271
272   /**
273    * Messages currently pending for transmission
274    * to this peer, if any.
275    */
276   struct PendingMessage *pending_messages;
277
278   /**
279    * Handle for pending transmission request.
280    */
281   struct GNUNET_NETWORK_TransmitHandle *transmit_handle;
282
283   /**
284    * To whom are we talking to (set to our identity
285    * if we are still waiting for the welcome message)
286    */
287   struct GNUNET_PeerIdentity target;
288
289   /**
290    * At what time did we reset last_received last?
291    */
292   struct GNUNET_TIME_Absolute last_quota_update;
293
294   /**
295    * Address of the other peer if WE initiated the connection
296    * (and hence can be sure what it is), otherwise NULL.
297    */
298   void *connect_addr;
299
300   /**
301    * How many bytes have we received since the "last_quota_update"
302    * timestamp?
303    */
304   uint64_t last_received;
305
306   /**
307    * Our current latency estimate (in ms).
308    */
309   double latency_estimate;
310
311   /**
312    * Time when we generated the last ACK_LOG_SIZE acks.
313    * (the "last" refers to the "out_msg_counter" here)
314    */
315   struct GNUNET_TIME_Absolute gen_time[ACK_LOG_SIZE];
316
317   /**
318    * Our current sequence number.
319    */
320   uint64_t out_msg_counter;
321
322   /**
323    * Highest received incoming sequence number.
324    */
325   uint64_t max_in_msg_counter;
326
327   /**
328    * Number of bytes per ms that this peer is allowed
329    * to send to us.
330    */
331   uint32_t quota_in;
332
333   /**
334    * Length of connect_addr, can be 0.
335    */
336   size_t connect_alen;
337
338   /**
339    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
340    * GNUNET_SYSERR is used to mark non-welcoming connections (HELLO
341    * validation only).
342    */
343   int expecting_welcome;
344
345   /**
346    * Are we still trying to connect?
347    */
348   int still_connecting;
349
350 };
351
352
353 /**
354  * Encapsulation of all of the state of the plugin.
355  */
356 struct Plugin
357 {
358   /**
359    * Our environment.
360    */
361   struct GNUNET_TRANSPORT_PluginEnvironment *env;
362
363   /**
364    * The listen socket.
365    */
366   struct GNUNET_NETWORK_SocketHandle *lsock;
367
368   /**
369    * List of open TCP sessions.
370    */
371   struct Session *sessions;
372
373   /**
374    * Handle for the statistics service.
375    */
376   struct GNUNET_STATISTICS_Handle *statistics;
377
378   /**
379    * Handle to the network service.
380    */
381   struct GNUNET_SERVICE_Context *service;
382
383   /**
384    * Handle to the server for this service.
385    */
386   struct GNUNET_SERVER_Handle *server;
387
388   /**
389    * Copy of the handler array where the closures are
390    * set to this struct's instance.
391    */
392   struct GNUNET_SERVER_MessageHandler *handlers;
393
394   /**
395    * ID of task used to update our addresses when one expires.
396    */
397   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
398
399   /**
400    * Port that we are actually listening on.
401    */
402   uint16_t open_port;
403
404   /**
405    * Port that the user said we would have visible to the
406    * rest of the world.
407    */
408   uint16_t adv_port;
409
410 };
411
412
413 /**
414  * Find the session handle for the given peer.
415  */
416 static struct Session *
417 find_session_by_target (struct Plugin *plugin,
418                         const struct GNUNET_PeerIdentity *target)
419 {
420   struct Session *ret;
421
422   ret = plugin->sessions;
423   while ((ret != NULL) &&
424          (0 != memcmp (target,
425                        &ret->target, sizeof (struct GNUNET_PeerIdentity))))
426     ret = ret->next;
427   return ret;
428 }
429
430
431 /**
432  * Find the session handle for the given peer.
433  */
434 static struct Session *
435 find_session_by_client (struct Plugin *plugin,
436                         const struct GNUNET_SERVER_Client *client)
437 {
438   struct Session *ret;
439
440   ret = plugin->sessions;
441   while ((ret != NULL) && (client != ret->client))
442     ret = ret->next;
443   return ret;
444 }
445
446
447 /**
448  * Create a welcome message.
449  */
450 static struct PendingMessage *
451 create_welcome (size_t addrlen, const void *addr, struct Plugin *plugin)
452 {
453   struct PendingMessage *pm;
454   struct WelcomeMessage *welcome;
455
456   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
457                       sizeof (struct WelcomeMessage) + addrlen);
458   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
459   welcome = (struct WelcomeMessage *) &pm[1];
460   welcome->header.size = htons (sizeof (struct WelcomeMessage) + addrlen);
461   welcome->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
462   GNUNET_CRYPTO_hash (plugin->env->my_public_key,
463                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
464                       &welcome->clientIdentity.hashPubKey);
465   memcpy (&welcome[1], addr, addrlen);
466   pm->timeout = GNUNET_TIME_relative_to_absolute (WELCOME_TIMEOUT);
467   pm->is_welcome = GNUNET_YES;
468   return pm;
469 }
470
471
472 /**
473  * Create a new session using the specified address
474  * for the welcome message.
475  *
476  * @param plugin us
477  * @param target peer to connect to
478  * @param client client to use
479  * @param addrlen IPv4 or IPv6
480  * @param addr either struct sockaddr_in or struct sockaddr_in6
481  * @return NULL connection failed / invalid address
482  */
483 static struct Session *
484 create_session (struct Plugin *plugin,
485                 const struct GNUNET_PeerIdentity *target,
486                 struct GNUNET_SERVER_Client *client,
487                 const void *addr, size_t addrlen)
488 {
489   struct Session *ret;
490
491   ret = GNUNET_malloc (sizeof (struct Session));
492   ret->plugin = plugin;
493   ret->next = plugin->sessions;
494   plugin->sessions = ret;
495   ret->client = client;
496   ret->target = *target;
497   ret->last_quota_update = GNUNET_TIME_absolute_get ();
498   ret->quota_in = plugin->env->default_quota_in;
499   ret->expecting_welcome = GNUNET_YES;
500   ret->pending_messages = create_welcome (addrlen, addr, plugin);
501   return ret;
502 }
503
504
505 /**
506  * If we have pending messages, ask the server to
507  * transmit them (schedule the respective tasks, etc.)
508  *
509  * @param session for which session should we do this
510  */
511 static void process_pending_messages (struct Session *session);
512
513
514 /**
515  * Function called to notify a client about the socket
516  * begin ready to queue more data.  "buf" will be
517  * NULL and "size" zero if the socket was closed for
518  * writing in the meantime.
519  *
520  * @param cls closure
521  * @param size number of bytes available in buf
522  * @param buf where the callee should write the message
523  * @return number of bytes written to buf
524  */
525 static size_t
526 do_transmit (void *cls, size_t size, void *buf)
527 {
528   struct Session *session = cls;
529   struct PendingMessage *pm;
530   char *cbuf;
531   uint16_t msize;
532   size_t ret;
533   struct DataMessage *dm;
534
535   session->transmit_handle = NULL;
536   if (buf == NULL)
537     {
538 #if DEBUG_TCP
539       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
540                        "tcp", 
541                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
542                        GNUNET_i2s(&session->target));
543 #endif
544       /* timeout */
545       while (NULL != (pm = session->pending_messages))
546         {
547           session->pending_messages = pm->next;
548           if (pm->transmit_cont != NULL)
549             pm->transmit_cont (pm->transmit_cont_cls,
550                                session->service_context,
551                                &session->target, GNUNET_SYSERR);
552           GNUNET_free (pm);
553         }
554       return 0;
555     }
556   ret = 0;
557   cbuf = buf;
558   while (NULL != (pm = session->pending_messages))
559     {
560       if (pm->is_welcome)
561         {
562           if (size < (msize = htons (pm->msg->size)))
563             break;
564           memcpy (cbuf, pm->msg, msize);
565           cbuf += msize;
566           ret += msize;
567           size -= msize;
568         }
569       else
570         {
571           if (size <
572               sizeof (struct DataMessage) + (msize = htons (pm->msg->size)))
573             break;
574           dm = (struct DataMessage *) cbuf;
575           dm->header.size = htons (sizeof (struct DataMessage) + msize);
576           dm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA);
577           dm->ack_out = GNUNET_htonll (++session->out_msg_counter);
578           dm->ack_in = GNUNET_htonll (session->max_in_msg_counter);
579           cbuf += sizeof (struct DataMessage);
580           ret += sizeof (struct DataMessage);
581           size -= sizeof (struct DataMessage);
582           memcpy (cbuf, pm->msg, msize);
583           cbuf += msize;
584           ret += msize;
585           size -= msize;
586         }
587       session->pending_messages = pm->next;
588       if (pm->transmit_cont != NULL)
589         pm->transmit_cont (pm->transmit_cont_cls,
590                            session->service_context,
591                            &session->target, GNUNET_OK);
592       GNUNET_free (pm);
593       session->gen_time[session->out_msg_counter % ACK_LOG_SIZE]
594         = GNUNET_TIME_absolute_get ();
595     }
596   process_pending_messages (session);
597 #if DEBUG_TCP
598   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
599                    "tcp", "Transmitting %u bytes\n", ret);
600 #endif
601   return ret;
602 }
603
604
605 /**
606  * If we have pending messages, ask the server to
607  * transmit them (schedule the respective tasks, etc.)
608  *
609  * @param session for which session should we do this
610  */
611 static void
612 process_pending_messages (struct Session *session)
613 {
614   GNUNET_assert (session->client != NULL);
615   if (session->pending_messages == NULL)
616     return;
617   if (session->transmit_handle != NULL)
618     return;
619   session->transmit_handle
620     = GNUNET_SERVER_notify_transmit_ready (session->client,
621                                            htons (session->
622                                                   pending_messages->msg->
623                                                   size) +
624                                            (session->
625                                             pending_messages->is_welcome ? 0 :
626                                             sizeof (struct DataMessage)),
627                                            GNUNET_TIME_absolute_get_remaining
628                                            (session->
629                                             pending_messages[0].timeout),
630                                            &do_transmit, session);
631 }
632
633
634
635 /**
636  * Create a new session connecting to the specified
637  * target at the specified address.  The session will
638  * be used to verify an address in a HELLO and should
639  * not expect to receive a WELCOME.
640  *
641  * @param plugin us
642  * @param target peer to connect to
643  * @param addrlen IPv4 or IPv6
644  * @param addr either struct sockaddr_in or struct sockaddr_in6
645  * @return NULL connection failed / invalid address
646  */
647 static struct Session *
648 connect_and_create_validation_session (struct Plugin *plugin,
649                                        const struct GNUNET_PeerIdentity *target,
650                                        const void *addr, size_t addrlen)
651 {
652   struct GNUNET_SERVER_Client *client;
653   struct GNUNET_NETWORK_SocketHandle *conn;
654   struct Session *session;
655   int af;
656
657   if (addrlen == sizeof (struct sockaddr_in))
658     af = AF_INET;
659   else if (addrlen == sizeof (struct sockaddr_in6))
660     af = AF_INET6;    
661   else
662     {
663       GNUNET_break_op (0);
664       return NULL;              /* invalid address */
665     }
666   conn = GNUNET_NETWORK_socket_create_from_sockaddr (plugin->env->sched,
667                                                      af,
668                                                      addr,
669                                                      addrlen,
670                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
671   if (conn == NULL)
672     {
673 #if DEBUG_TCP
674       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
675                        "tcp",
676                        "Failed to create connection to peer at `%s'.\n",
677                        GNUNET_a2s(addr, addrlen));
678 #endif
679       return NULL;
680     }
681   client = GNUNET_SERVER_connect_socket (plugin->server, conn);
682   GNUNET_assert (client != NULL);
683   session = create_session (plugin, target, client, addr, addrlen);
684   /* kill welcome */
685   GNUNET_free (session->pending_messages);
686   session->pending_messages = NULL;
687   session->connect_alen = addrlen;
688   session->connect_addr = GNUNET_malloc (addrlen);
689   session->expecting_welcome = GNUNET_SYSERR;  
690   memcpy (session->connect_addr, addr, addrlen);
691 #if DEBUG_TCP
692   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
693                    "tcp",
694                    "Creating new session %p with `%s' based on `%s' request.\n",
695                    session, 
696                    GNUNET_a2s(addr, addrlen),
697                    "validate");
698 #endif
699   return session;
700 }
701
702
703 /**
704  * Function that can be used by the transport service to validate that
705  * another peer is reachable at a particular address (even if we
706  * already have a connection to this peer, this function is required
707  * to establish a new one).
708  *
709  * @param cls closure
710  * @param target who should receive this message
711  * @param challenge challenge code to use
712  * @param addrlen length of the address
713  * @param addr the address
714  * @param timeout how long should we try to transmit these?
715  * @return GNUNET_OK if the transmission has been scheduled
716  */
717 static int
718 tcp_plugin_validate (void *cls,
719                      const struct GNUNET_PeerIdentity *target,
720                      uint32_t challenge,
721                      struct GNUNET_TIME_Relative timeout,
722                      const void *addr, size_t addrlen)
723 {
724   struct Plugin *plugin = cls;
725   struct Session *session;
726   struct PendingMessage *pm;
727   struct ValidationChallengeMessage *vcm;
728
729   session = connect_and_create_validation_session (plugin, target, addr, addrlen);
730   if (session == NULL)
731     {
732 #if DEBUG_TCP
733       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
734                        "tcp", "Failed to create fresh session.\n");
735 #endif
736       return GNUNET_SYSERR;
737     }
738   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
739                       sizeof (struct ValidationChallengeMessage) + addrlen);
740   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
741   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
742   pm->is_welcome = GNUNET_YES;
743   vcm = (struct ValidationChallengeMessage*) &pm[1];
744   vcm->header.size =
745     htons (sizeof (struct ValidationChallengeMessage) + addrlen);
746   vcm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING);
747   vcm->challenge = htonl(challenge);
748   vcm->target = *target;
749   memcpy (&vcm[1], addr, addrlen);
750   GNUNET_assert (session->pending_messages == NULL);
751   session->pending_messages = pm;
752   process_pending_messages (session);
753   return GNUNET_OK;
754 }
755
756
757 /**
758  * Functions with this signature are called whenever we need
759  * to close a session due to a disconnect or failure to
760  * establish a connection.
761  *
762  * @param session session to close down
763  */
764 static void
765 disconnect_session (struct Session *session)
766 {
767   struct Session *prev;
768   struct Session *pos;
769   struct PendingMessage *pm;
770
771 #if DEBUG_TCP
772   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
773                    "tcp",
774                    "Disconnecting from other peer (session %p).\n", session);
775 #endif
776   /* remove from session list */
777   prev = NULL;
778   pos = session->plugin->sessions;
779   while (pos != session)
780     {
781       prev = pos;
782       pos = pos->next;
783     }
784   if (prev == NULL)
785     session->plugin->sessions = session->next;
786   else
787     prev->next = session->next;
788   /* clean up state */
789   if (session->client != NULL)
790     {
791 #if DEBUG_TCP
792       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
793                   "Disconnecting from client address %p\n", session->client);
794 #endif
795       GNUNET_SERVER_client_drop (session->client);
796       session->client = NULL;
797     }
798   if (session->transmit_handle != NULL)
799     {
800       GNUNET_NETWORK_notify_transmit_ready_cancel (session->transmit_handle);
801       session->transmit_handle = NULL;
802     }
803   while (NULL != (pm = session->pending_messages))
804     {
805       session->pending_messages = pm->next;
806       if (NULL != pm->transmit_cont)
807         pm->transmit_cont (pm->transmit_cont_cls,
808                            session->service_context,
809                            &session->target, GNUNET_SYSERR);
810       GNUNET_free (pm);
811     }
812   /* notify transport service about disconnect */
813   session->plugin->env->receive (session->plugin->env->cls,
814                                  session,
815                                  session->service_context,
816                                  GNUNET_TIME_UNIT_ZERO,
817                                  &session->target, NULL);
818   GNUNET_free_non_null (session->connect_addr);
819   GNUNET_free (session);
820 }
821
822
823 /**
824  * Iterator callback to go over all addresses.  If we get
825  * a TCP address, increment the counter
826  *
827  * @param cls closure, points to the counter
828  * @param tname name of the transport
829  * @param expiration expiration time
830  * @param addr the address
831  * @param addrlen length of the address
832  * @return GNUNET_OK to keep the address,
833  *         GNUNET_NO to delete it from the HELLO
834  *         GNUNET_SYSERR to stop iterating (but keep current address)
835  */
836 static int
837 count_tcp_addresses (void *cls,
838                      const char *tname,
839                      struct GNUNET_TIME_Absolute expiration,
840                      const void *addr, size_t addrlen)
841 {
842   unsigned int *counter = cls;
843
844   if (0 != strcmp (tname, "tcp"))
845     return GNUNET_OK;           /* not one of ours */
846   (*counter)++;
847   return GNUNET_OK;             /* failed to connect */
848 }
849
850
851 struct ConnectContext
852 {
853   struct Plugin *plugin;
854
855   struct GNUNET_NETWORK_SocketHandle *sa;
856
857   struct PendingMessage *welcome;
858
859   unsigned int pos;
860 };
861
862
863 /**
864  * Iterator callback to go over all addresses.  If we get
865  * the "pos" TCP address, try to connect to it.
866  *
867  * @param cls closure
868  * @param tname name of the transport
869  * @param expiration expiration time
870  * @param addrlen length of the address
871  * @param addr the address
872  * @return GNUNET_OK to keep the address,
873  *         GNUNET_NO to delete it from the HELLO
874  *         GNUNET_SYSERR to stop iterating (but keep current address)
875  */
876 static int
877 try_connect_to_address (void *cls,
878                         const char *tname,
879                         struct GNUNET_TIME_Absolute expiration,
880                         const void *addr, size_t addrlen)
881 {
882   struct ConnectContext *cc = cls;
883   int af;
884
885   if (0 != strcmp (tname, "tcp"))
886     return GNUNET_OK;           /* not one of ours */
887   if (sizeof (struct sockaddr_in) == addrlen)
888     af = AF_INET;
889   else if (sizeof (struct sockaddr_in6) == addrlen)
890     af = AF_INET6;
891   else
892     {
893       /* not a valid address */
894       GNUNET_break (0);
895       return GNUNET_NO;
896     }
897   if (0 == cc->pos--)
898     {
899       cc->welcome = create_welcome (addrlen, addr, cc->plugin);
900       cc->sa =
901         GNUNET_NETWORK_socket_create_from_sockaddr (cc->plugin->env->sched,
902                                                     af, addr, addrlen,
903                                                     GNUNET_SERVER_MAX_MESSAGE_SIZE);
904 #if DEBUG_TCP
905       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
906                        "tcp", "Connected to other peer.\n");
907 #endif
908       return GNUNET_SYSERR;
909     }
910   return GNUNET_OK;             /* failed to connect */
911 }
912
913
914 /**
915  * Type of an iterator over the hosts.  Note that each
916  * host will be called with each available protocol.
917  *
918  * @param cls closure
919  * @param peer id of the peer, NULL for last call
920  * @param hello hello message for the peer (can be NULL)
921  * @param trust amount of trust we have in the peer
922  */
923 static void
924 session_try_connect (void *cls,
925                      const struct GNUNET_PeerIdentity *peer,
926                      const struct GNUNET_HELLO_Message *hello, uint32_t trust)
927 {
928   struct Session *session = cls;
929   unsigned int count;
930   struct ConnectContext cctx;
931   struct PendingMessage *pm;
932
933   if (peer == NULL)
934     {
935       /* last call, destroy session if we are still not
936          connected */
937       if (session->still_connecting == GNUNET_NO)
938         {
939 #if DEBUG_TCP
940           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
941                            "tcp",
942                            "Connected to other peer, now processing messages.\n");
943 #endif
944           process_pending_messages (session);
945         }
946       else
947         {
948 #if DEBUG_TCP
949           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
950                            "tcp",
951                            "Failed to connect to other peer, now closing session.\n");
952 #endif
953           disconnect_session (session);
954         }
955       return;
956     }
957   if ((hello == NULL) || (session->client != NULL))
958     {
959       GNUNET_break (0);         /* should this ever happen!? */
960       return;
961     }
962   count = 0;
963   GNUNET_HELLO_iterate_addresses (hello,
964                                   GNUNET_NO, &count_tcp_addresses, &count);
965   if (count == 0)
966     {
967 #if DEBUG_TCP
968       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
969                        "tcp",
970                        "Asked to connect, but have no addresses to try.\n");
971 #endif
972       return;
973     }
974   cctx.plugin = session->plugin;
975   cctx.sa = NULL;
976   cctx.welcome = NULL;
977   cctx.pos = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
978   GNUNET_HELLO_iterate_addresses (hello,
979                                   GNUNET_NO, &try_connect_to_address, &cctx);
980   if (cctx.sa == NULL)
981     {
982 #if DEBUG_TCP
983       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
984                        "tcp",
985                        "Asked to connect, but all addresses failed.\n");
986 #endif
987       GNUNET_free_non_null (cctx.welcome);
988       return;
989     }
990   session->client = GNUNET_SERVER_connect_socket (session->plugin->server,
991                                                   cctx.sa);
992 #if DEBUG_TCP
993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994               "Connected getting client address %p\n", session->client);
995 #endif
996   if (session->client == NULL)
997     {
998       GNUNET_break (0);         /* how could this happen? */
999       GNUNET_free_non_null (cctx.welcome);
1000       return;
1001     }
1002   pm = cctx.welcome;
1003   /* prepend (!) */
1004   pm->next = session->pending_messages;
1005   session->pending_messages = pm;
1006   session->still_connecting = GNUNET_NO;
1007 #if DEBUG_TCP
1008   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1009                    "tcp",
1010                    "Connected to other peer, now sending `%s' message.\n",
1011                    "WELCOME");
1012 #endif
1013 }
1014
1015
1016 /**
1017  * Function that can be used by the transport service to transmit
1018  * a message using the plugin.
1019  *
1020  * @param cls closure
1021  * @param plugin_context value we were asked to pass to this plugin
1022  *        to respond to the given peer (use is optional,
1023  *        but may speed up processing), can be NULL
1024  * @param service_context value passed to the transport-service
1025  *        to identify the neighbour
1026  * @param target who should receive this message
1027  * @param priority how important is the message
1028  * @param msg the message to transmit
1029  * @param cont continuation to call once the message has
1030  *        been transmitted (or if the transport is ready
1031  *        for the next transmission call; or if the
1032  *        peer disconnected...)
1033  * @param cont_cls closure for cont
1034  * @return plugin_context that should be used next time for
1035  *         sending messages to the specified peer
1036  */
1037 static void *
1038 tcp_plugin_send (void *cls,
1039                  void *plugin_context,
1040                  struct ReadyList *service_context,
1041                  const struct GNUNET_PeerIdentity *target,   
1042                  unsigned int priority,
1043                  const struct GNUNET_MessageHeader *msg,
1044                  struct GNUNET_TIME_Relative timeout,
1045                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1046 {
1047   struct Plugin *plugin = cls;
1048   struct Session *session = plugin_context;
1049   struct PendingMessage *pm;
1050   struct PendingMessage *pme;
1051
1052   if (session == NULL)
1053     session = find_session_by_target (plugin, target);  
1054   pm = GNUNET_malloc (sizeof (struct PendingMessage) + ntohs (msg->size));
1055   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1056   memcpy (pm->msg, msg, ntohs (msg->size));
1057   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1058   pm->transmit_cont = cont;
1059   pm->transmit_cont_cls = cont_cls;
1060   if (session == NULL)
1061     {
1062       session = GNUNET_malloc (sizeof (struct Session));
1063 #if DEBUG_TCP
1064       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1065                        "tcp",
1066                        "Asked to transmit, creating fresh session %p.\n",
1067                        session);
1068 #endif
1069       session->next = plugin->sessions;
1070       plugin->sessions = session;
1071       session->plugin = plugin;
1072       session->target = *target;
1073       session->last_quota_update = GNUNET_TIME_absolute_get ();
1074       session->quota_in = plugin->env->default_quota_in;
1075       session->expecting_welcome = GNUNET_YES;
1076       session->still_connecting = GNUNET_YES;
1077       session->pending_messages = pm;
1078       session->service_context = service_context;
1079       GNUNET_PEERINFO_for_all (plugin->env->cfg,
1080                                plugin->env->sched,
1081                                target,
1082                                0, timeout, &session_try_connect, session);
1083       return session;
1084     }
1085   GNUNET_assert (session != NULL);
1086   GNUNET_assert (session->still_connecting == GNUNET_NO);
1087   session->service_context = service_context;
1088   /* append pm to pending_messages list */
1089   pme = session->pending_messages;
1090   if (pme == NULL)
1091     {
1092       session->pending_messages = pm;
1093     }
1094   else
1095     {
1096       while (NULL != pme->next)
1097         pme = pme->next;
1098       pme->next = pm;
1099     }
1100 #if DEBUG_TCP
1101   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1102                    "tcp", "Asked to transmit, added message to list.\n");
1103 #endif
1104   process_pending_messages (session);
1105   return session;
1106 }
1107
1108
1109
1110 /**
1111  * Function that can be called to force a disconnect from the
1112  * specified neighbour.  This should also cancel all previously
1113  * scheduled transmissions.  Obviously the transmission may have been
1114  * partially completed already, which is OK.  The plugin is supposed
1115  * to close the connection (if applicable) and no longer call the
1116  * transmit continuation(s).
1117  *
1118  * Finally, plugin MUST NOT call the services's receive function to
1119  * notify the service that the connection to the specified target was
1120  * closed after a getting this call.
1121  *
1122  * @param cls closure
1123  * @param plugin_context value we were asked to pass to this plugin
1124  *        to respond to the given peer (use is optional,
1125  *        but may speed up processing), can be NULL (if
1126  *        NULL was returned from the transmit function)
1127  * @param service_context must correspond to the service context
1128  *        of the corresponding Transmit call; the plugin should
1129  *        not cancel a send call made with a different service
1130  *        context pointer!  Never NULL.
1131  * @param target peer for which the last transmission is
1132  *        to be cancelled
1133  */
1134 static void
1135 tcp_plugin_cancel (void *cls,
1136                    void *plugin_context,
1137                    struct ReadyList *service_context,
1138                    const struct GNUNET_PeerIdentity *target)
1139 {
1140   struct Plugin *plugin = cls;
1141   struct PendingMessage *pm;
1142   struct Session *session;
1143   struct Session *next;
1144   
1145   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1146                    "tcp",
1147                    "Asked to close session with `%4s'\n",
1148                    GNUNET_i2s(target));
1149   session = plugin->sessions;
1150   while (session != NULL)
1151     {
1152       next = session->next;
1153       if (0 == memcmp (target,
1154                        &session->target, sizeof (struct GNUNET_PeerIdentity)))
1155         {
1156           pm = session->pending_messages;
1157           while (pm != NULL)
1158             {
1159               pm->transmit_cont = NULL;
1160               pm->transmit_cont_cls = NULL;
1161               pm = pm->next;
1162             }
1163           session->service_context = NULL;
1164           GNUNET_SERVER_client_disconnect (session->client);
1165           /* rest of the clean-up of the session will be done as part of
1166              disconnect_notify which should be triggered any time now */
1167         }
1168       session = next;
1169     }
1170 }
1171
1172
1173 struct PrettyPrinterContext
1174 {
1175   GNUNET_TRANSPORT_AddressStringCallback asc;
1176   void *asc_cls;
1177   uint16_t port;
1178 };
1179
1180
1181 /**
1182  * Append our port and forward the result.
1183  */
1184 static void
1185 append_port (void *cls, const char *hostname)
1186 {
1187   struct PrettyPrinterContext *ppc = cls;
1188   char *ret;
1189
1190   if (hostname == NULL)
1191     {
1192       ppc->asc (ppc->asc_cls, NULL);
1193       GNUNET_free (ppc);
1194       return;
1195     }
1196   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1197   ppc->asc (ppc->asc_cls, ret);
1198   GNUNET_free (ret);
1199 }
1200
1201
1202 /**
1203  * Convert the transports address to a nice, human-readable
1204  * format.
1205  *
1206  * @param cls closure
1207  * @param name name of the transport that generated the address
1208  * @param addr one of the addresses of the host, NULL for the last address
1209  *        the specific address format depends on the transport
1210  * @param addrlen length of the address
1211  * @param numeric should (IP) addresses be displayed in numeric form?
1212  * @param timeout after how long should we give up?
1213  * @param asc function to call on each string
1214  * @param asc_cls closure for asc
1215  */
1216 static void
1217 tcp_plugin_address_pretty_printer (void *cls,
1218                                    const char *type,
1219                                    const void *addr,
1220                                    size_t addrlen,
1221                                    int numeric,
1222                                    struct GNUNET_TIME_Relative timeout,
1223                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1224                                    void *asc_cls)
1225 {
1226   struct Plugin *plugin = cls;
1227   const struct sockaddr_in *v4;
1228   const struct sockaddr_in6 *v6;
1229   struct PrettyPrinterContext *ppc;
1230
1231   if ((addrlen != sizeof (struct sockaddr_in)) &&
1232       (addrlen != sizeof (struct sockaddr_in6)))
1233     {
1234       /* invalid address */
1235       GNUNET_break_op (0);
1236       asc (asc_cls, NULL);
1237       return;
1238     }
1239   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1240   ppc->asc = asc;
1241   ppc->asc_cls = asc_cls;
1242   if (addrlen == sizeof (struct sockaddr_in))
1243     {
1244       v4 = (const struct sockaddr_in *) addr;
1245       ppc->port = ntohs (v4->sin_port);
1246     }
1247   else
1248     {
1249       v6 = (const struct sockaddr_in6 *) addr;
1250       ppc->port = ntohs (v6->sin6_port);
1251
1252     }
1253   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1254                                 plugin->env->cfg,
1255                                 addr,
1256                                 addrlen,
1257                                 !numeric, timeout, &append_port, ppc);
1258 }
1259
1260
1261 /**
1262  * Update the last-received and bandwidth quota values
1263  * for this session.
1264  *
1265  * @param session session to update
1266  * @param force set to GNUNET_YES if we should update even
1267  *        though the minimum refresh time has not yet expired
1268  */
1269 static void
1270 update_quota (struct Session *session, int force)
1271 {
1272   struct GNUNET_TIME_Absolute now;
1273   unsigned long long delta;
1274   unsigned long long total_allowed;
1275   unsigned long long total_remaining;
1276
1277   now = GNUNET_TIME_absolute_get ();
1278   delta = now.value - session->last_quota_update.value;
1279   if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
1280     return;                     /* too early, not enough data */
1281
1282   total_allowed = session->quota_in * delta;
1283   if (total_allowed > session->last_received)
1284     {
1285       /* got less than acceptable */
1286       total_remaining = total_allowed - session->last_received;
1287       session->last_received = 0;
1288       delta = total_remaining / session->quota_in;      /* bonus seconds */
1289       if (delta > MAX_BANDWIDTH_CARRY)
1290         delta = MAX_BANDWIDTH_CARRY;    /* limit amount of carry-over */
1291     }
1292   else
1293     {
1294       /* got more than acceptable */
1295       total_remaining = 0;
1296       session->last_received -= total_allowed;
1297       delta = 0;
1298     }
1299   session->last_quota_update.value = now.value - delta;
1300 }
1301
1302
1303 /**
1304  * Set a quota for receiving data from the given peer; this is a
1305  * per-transport limit.  The transport should limit its read/select
1306  * calls to stay below the quota (in terms of incoming data).
1307  *
1308  * @param cls closure
1309  * @param peer the peer for whom the quota is given
1310  * @param quota_in quota for receiving/sending data in bytes per ms
1311  */
1312 static void
1313 tcp_plugin_set_receive_quota (void *cls,
1314                               const struct GNUNET_PeerIdentity *target,
1315                               uint32_t quota_in)
1316 {
1317   struct Plugin *plugin = cls;
1318   struct Session *session;
1319
1320   session = find_session_by_target (plugin, target);
1321   if (session->quota_in != quota_in)
1322     {
1323       update_quota (session, GNUNET_YES);
1324       if (session->quota_in > quota_in)
1325         session->last_quota_update = GNUNET_TIME_absolute_get ();
1326       session->quota_in = quota_in;
1327     }
1328 }
1329
1330
1331 /**
1332  * Check if the given port is plausible (must be either
1333  * our listen port or our advertised port).  If it is
1334  * neither, we return one of these two ports at random.
1335  *
1336  * @return either in_port or a more plausible port
1337  */
1338 static uint16_t
1339 check_port (struct Plugin *plugin, uint16_t in_port)
1340 {
1341   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1342     return in_port;
1343   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1344                                     2) == 0)
1345     ? plugin->open_port : plugin->adv_port;
1346 }
1347
1348
1349 /**
1350  * Another peer has suggested an address for this
1351  * peer and transport plugin.  Check that this could be a valid
1352  * address.  If so, consider adding it to the list
1353  * of addresses.
1354  *
1355  * @param cls closure
1356  * @param addr pointer to the address
1357  * @param addrlen length of addr
1358  * @return GNUNET_OK if this is a plausible address for this peer
1359  *         and transport
1360  */
1361 static int
1362 tcp_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1363 {
1364   struct Plugin *plugin = cls;
1365   char buf[sizeof (struct sockaddr_in6)];
1366   struct sockaddr_in *v4;
1367   struct sockaddr_in6 *v6;
1368
1369   if ((addrlen != sizeof (struct sockaddr_in)) &&
1370       (addrlen != sizeof (struct sockaddr_in6)))
1371     {
1372       GNUNET_break_op (0);
1373       return GNUNET_SYSERR;
1374     }
1375   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1376   if (addrlen == sizeof (struct sockaddr_in))
1377     {
1378       v4 = (struct sockaddr_in *) buf;
1379       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1380     }
1381   else
1382     {
1383       v6 = (struct sockaddr_in6 *) buf;
1384       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1385     }
1386 #if DEBUG_TCP
1387   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1388                    "tcp",
1389                    "Informing transport service about my address `%s'.\n",
1390                    GNUNET_a2s(addr, addrlen));
1391 #endif
1392   plugin->env->notify_address (plugin->env->cls,
1393                                "tcp",
1394                                buf, addrlen, LEARNED_ADDRESS_EXPIRATION);
1395   return GNUNET_OK;
1396 }
1397
1398
1399 /**
1400  * Send a validation challenge response.
1401  */
1402 static size_t
1403 send_vcr (void *cls,
1404           size_t size,
1405           void *buf)
1406 {
1407   struct ValidationChallengeResponse *vcr = cls;
1408   uint16_t msize;
1409
1410   if (NULL == buf)
1411     {
1412       GNUNET_free (vcr);
1413       return 0;
1414     }
1415   msize = ntohs(vcr->header.size);
1416   GNUNET_assert (size >= msize);
1417   memcpy (buf, vcr, msize);
1418   GNUNET_free (vcr);
1419   return msize;
1420 }
1421
1422
1423 /**
1424  * We've received a PING from this peer via TCP.
1425  * Send back our PONG.
1426  *
1427  * @param cls closure
1428  * @param client identification of the client
1429  * @param message the actual message
1430  */
1431 static void
1432 handle_tcp_ping (void *cls,
1433                  struct GNUNET_SERVER_Client *client,
1434                  const struct GNUNET_MessageHeader *message)
1435 {
1436   struct Plugin *plugin = cls;
1437   const struct ValidationChallengeMessage *vcm;
1438   struct ValidationChallengeResponse *vcr;
1439   uint16_t msize;
1440   size_t addrlen;
1441   void *addr;
1442
1443 #if DEBUG_TRANSPORT
1444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1445               "Processing PING\n");
1446 #endif
1447   msize = ntohs (message->size);
1448   if (msize < sizeof (struct ValidationChallengeMessage))
1449     {
1450       GNUNET_break_op (0);
1451       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1452       return;
1453     }
1454   vcm = (const struct ValidationChallengeMessage *) message;
1455   if (0 != memcmp (&vcm->target,
1456                    plugin->env->my_identity, sizeof (struct GNUNET_PeerIdentity)))
1457     {
1458       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1459                   _("Received `%s' message not destined for me!\n"), "PING");
1460       /* TODO: call statistics */
1461       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1462       return;
1463     }
1464   msize -= sizeof (struct ValidationChallengeMessage);
1465   if (GNUNET_OK !=
1466       tcp_plugin_address_suggested (plugin, &vcm[1], msize))
1467     {
1468       GNUNET_break_op (0);
1469       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1470       return;
1471     }
1472   if (GNUNET_OK !=
1473       GNUNET_SERVER_client_get_address (client,
1474                                         &addr,
1475                                         &addrlen))
1476     {
1477       GNUNET_break (0);
1478       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1479       return;
1480     }
1481   vcr = GNUNET_malloc (sizeof (struct ValidationChallengeResponse) + addrlen);
1482   vcr->header.size = htons (sizeof (struct ValidationChallengeResponse) + addrlen);
1483   vcr->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG);
1484   vcr->purpose.size =
1485     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1486            sizeof (uint32_t) +
1487            sizeof ( struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1488            addrlen);
1489   vcr->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
1490   vcr->challenge = vcm->challenge;
1491   vcr->signer = *plugin->env->my_public_key;
1492   memcpy (&vcr[1],
1493           addr,
1494           addrlen);
1495   GNUNET_assert (GNUNET_OK ==
1496                  GNUNET_CRYPTO_rsa_sign (plugin->env->my_private_key,
1497                                          &vcr->purpose,
1498                                          &vcr->signature));
1499 #if EXTRA_CHECKS
1500   GNUNET_assert (GNUNET_OK ==
1501                  GNUNET_CRYPTO_rsa_verify
1502                  (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING,
1503                   &vcr->purpose,
1504                   &vcr->signature,
1505                   plugin->env->my_public_key));
1506 #endif
1507   GNUNET_free (addr);
1508   if (NULL ==
1509       GNUNET_SERVER_notify_transmit_ready (client,
1510                                            sizeof (struct ValidationChallengeResponse) + addrlen,
1511                                            GNUNET_TIME_UNIT_SECONDS,
1512                                            &send_vcr,
1513                                            vcr))
1514     {
1515       GNUNET_break (0);
1516       GNUNET_free (vcr);
1517     }
1518   /* after a PING, we always close the connection */
1519   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1520 }
1521
1522
1523 /**
1524  * Handle PING-message.  If the plugin that gave us the message is
1525  * able to queue the PONG immediately, we only queue one PONG.
1526  * Otherwise we send at most TWO PONG messages, one via an unconfirmed
1527  * transport and one via a confirmed transport.  Both addresses are
1528  * selected randomly among those available.
1529  *
1530  * @param plugin plugin that gave us the message
1531  * @param sender claimed sender of the PING
1532  * @param plugin_context context that might be used to send response
1533  * @param message the actual message
1534  */
1535 /**
1536  * We've received a PING from this peer via TCP.
1537  * Send back our PONG.
1538  *
1539  * @param cls closure
1540  * @param client identification of the client
1541  * @param message the actual message
1542  */
1543 static void
1544 handle_tcp_pong (void *cls,
1545                  struct GNUNET_SERVER_Client *client,
1546                  const struct GNUNET_MessageHeader *message)
1547 {
1548   struct Plugin *plugin = cls;
1549   const struct ValidationChallengeResponse *vcr;
1550   struct GNUNET_PeerIdentity peer;
1551   char *sender_addr;
1552   size_t addrlen;
1553
1554 #if DEBUG_TRANSPORT
1555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1556               "Processing PONG\n");
1557 #endif
1558   if (ntohs(message->size) < sizeof(struct ValidationChallengeResponse))
1559     {
1560       GNUNET_break_op (0);
1561       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1562       return;
1563     }
1564   addrlen = ntohs(message->size) - sizeof(struct ValidationChallengeResponse);
1565   vcr = (const struct ValidationChallengeResponse *) message;
1566   if ( (ntohl(vcr->purpose.size) !=
1567         sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1568         sizeof (uint32_t) +
1569         sizeof ( struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1570         addrlen))
1571     {
1572       GNUNET_break_op (0);
1573       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1574       return;
1575     }
1576   if (GNUNET_OK !=
1577       GNUNET_CRYPTO_rsa_verify
1578       (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING, 
1579        &vcr->purpose,
1580        &vcr->signature, 
1581        &vcr->signer))
1582     {
1583       GNUNET_break_op (0);
1584       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1585       return;
1586     }
1587   GNUNET_CRYPTO_hash (&vcr->signer,
1588                       sizeof(  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1589                       &peer.hashPubKey);
1590   sender_addr = GNUNET_strdup (GNUNET_a2s((const struct sockaddr*) &vcr[1],
1591                                           addrlen));
1592   plugin->env->notify_validation (plugin->env->cls,
1593                                   "tcp",
1594                                   &peer,
1595                                   ntohl(vcr->challenge),
1596                                   sender_addr);
1597   GNUNET_free (sender_addr);
1598   /* after a PONG, we always close the connection */
1599   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1600 }
1601
1602
1603 /**
1604  * We've received a welcome from this peer via TCP.
1605  * Possibly create a fresh client record and send back
1606  * our welcome.
1607  *
1608  * @param cls closure
1609  * @param client identification of the client
1610  * @param message the actual message
1611  */
1612 static void
1613 handle_tcp_welcome (void *cls,
1614                     struct GNUNET_SERVER_Client *client,
1615                     const struct GNUNET_MessageHeader *message)
1616 {
1617   struct Plugin *plugin = cls;
1618   struct Session *session_c;
1619   const struct WelcomeMessage *wm;
1620   uint16_t msize;
1621   uint32_t addrlen;
1622   size_t alen;
1623   void *vaddr;
1624   const struct sockaddr *addr;
1625
1626   msize = ntohs (message->size);
1627   if (msize < sizeof (struct WelcomeMessage))
1628     {
1629       GNUNET_break_op (0);
1630       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1631       return;
1632     }
1633   wm = (const struct WelcomeMessage *) message;
1634 #if DEBUG_TCP
1635   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1636                    "tcp",
1637                    "Received `%s' message from `%4s/%p'.\n", "WELCOME",
1638                    GNUNET_i2s(&wm->clientIdentity),
1639                    client);
1640 #endif
1641   session_c = find_session_by_client (plugin, client);
1642   if (session_c == NULL)
1643     {
1644       vaddr = NULL;
1645       GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1646       GNUNET_SERVER_client_keep (client);
1647       session_c = create_session (plugin,
1648                                   &wm->clientIdentity, client, vaddr, alen);
1649 #if DEBUG_TCP
1650       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1651                        "tcp",
1652                        "Creating new session %p for incoming `%s' message.\n",
1653                        session_c, "WELCOME");
1654 #endif
1655       GNUNET_free_non_null (vaddr);
1656       process_pending_messages (session_c);
1657     }
1658   if (session_c->expecting_welcome != GNUNET_YES)
1659     {
1660       GNUNET_break_op (0);
1661       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1662       return;
1663     }
1664   session_c->expecting_welcome = GNUNET_NO;
1665   if (0 < (addrlen = msize - sizeof (struct WelcomeMessage)))
1666     {
1667       addr = (const struct sockaddr *) &wm[1];
1668       tcp_plugin_address_suggested (plugin, addr, addrlen);
1669     }
1670   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1671 }
1672
1673
1674 /**
1675  * Calculate how long we should delay reading from the TCP socket to
1676  * ensure that we stay within our bandwidth limits (push back).
1677  *
1678  * @param session for which client should this be calculated
1679  */
1680 static struct GNUNET_TIME_Relative
1681 calculate_throttle_delay (struct Session *session)
1682 {
1683   struct GNUNET_TIME_Relative ret;
1684   struct GNUNET_TIME_Absolute now;
1685   uint64_t del;
1686   uint64_t avail;
1687   uint64_t excess;
1688
1689   now = GNUNET_TIME_absolute_get ();
1690   del = now.value - session->last_quota_update.value;
1691   if (del > MAX_BANDWIDTH_CARRY)
1692     {
1693       update_quota (session, GNUNET_YES);
1694       del = now.value - session->last_quota_update.value;
1695       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1696     }
1697   if (session->quota_in == 0)
1698     session->quota_in = 1;      /* avoid divison by zero */
1699   avail = del * session->quota_in;
1700   if (avail > session->last_received)
1701     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1702   excess = session->last_received - avail;
1703   ret.value = excess / session->quota_in;
1704   return ret;
1705 }
1706
1707
1708 /**
1709  * Task to signal the server that we can continue
1710  * receiving from the TCP client now.
1711  */
1712 static void
1713 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1714 {
1715   struct Session *session = cls;
1716   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1717 }
1718
1719
1720 /**
1721  * We've received data for this peer via TCP.  Unbox,
1722  * compute latency and forward.
1723  *
1724  * @param cls closure
1725  * @param client identification of the client
1726  * @param message the actual message
1727  */
1728 static void
1729 handle_tcp_data (void *cls,
1730                  struct GNUNET_SERVER_Client *client,
1731                  const struct GNUNET_MessageHeader *message)
1732 {
1733   struct Plugin *plugin = cls;
1734   struct Session *session;
1735   const struct DataMessage *dm;
1736   uint16_t msize;
1737   const struct GNUNET_MessageHeader *msg;
1738   struct GNUNET_TIME_Relative latency;
1739   struct GNUNET_TIME_Absolute ttime;
1740   struct GNUNET_TIME_Absolute now;
1741   struct GNUNET_TIME_Relative delay;
1742   uint64_t ack_in;
1743
1744   msize = ntohs (message->size);
1745   if ((msize <
1746        sizeof (struct DataMessage) + sizeof (struct GNUNET_MessageHeader)))
1747     {
1748       GNUNET_break_op (0);
1749       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1750       return;
1751     }
1752   session = find_session_by_client (plugin, client);
1753   if ((NULL == session) || (GNUNET_NO != session->expecting_welcome))
1754     {
1755       GNUNET_break_op (0);
1756       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1757       return;
1758     }
1759 #if DEBUG_TCP
1760   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1761                    "tcp", "Receiving %u bytes from `%4s'.\n",
1762                    msize,
1763                    GNUNET_i2s(&session->target));
1764 #endif
1765   dm = (const struct DataMessage *) message;
1766   session->max_in_msg_counter = GNUNET_MAX (session->max_in_msg_counter,
1767                                             GNUNET_ntohll (dm->ack_out));
1768   msg = (const struct GNUNET_MessageHeader *) &dm[1];
1769   if (msize != sizeof (struct DataMessage) + ntohs (msg->size))
1770     {
1771       GNUNET_break_op (0);
1772       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1773       return;
1774     }
1775   /* estimate latency */
1776   ack_in = GNUNET_ntohll (dm->ack_in);
1777   if ((ack_in <= session->out_msg_counter) &&
1778       (session->out_msg_counter - ack_in < ACK_LOG_SIZE))
1779     {
1780       delay = GNUNET_TIME_relative_ntoh (dm->delay);
1781       ttime = session->gen_time[ack_in % ACK_LOG_SIZE];
1782       now = GNUNET_TIME_absolute_get ();
1783       if (delay.value > now.value - ttime.value)
1784         delay.value = 0;        /* not plausible */
1785       /* update (round-trip) latency using ageing; we
1786          use 7:1 so that we can reasonably quickly react
1787          to changes, but not so fast that latency is largely
1788          jitter... */
1789       session->latency_estimate
1790         = ((7 * session->latency_estimate) +
1791            (now.value - ttime.value - delay.value)) / 8;
1792     }
1793   latency.value = (uint64_t) session->latency_estimate;
1794   /* deliver on */
1795 #if DEBUG_TCP
1796   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1797                    "tcp",
1798                    "Forwarding data of type %u to transport service.\n",
1799                    ntohs (msg->type));
1800 #endif
1801   session->service_context
1802     = plugin->env->receive (plugin->env->cls,
1803                             session,
1804                             session->service_context,
1805                             latency, &session->target, msg);
1806   /* update bandwidth used */
1807   session->last_received += msize;
1808   update_quota (session, GNUNET_NO);
1809
1810   delay = calculate_throttle_delay (session);
1811   if (delay.value == 0)
1812     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1813   else
1814     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1815                                   GNUNET_NO,
1816                                   GNUNET_SCHEDULER_PRIORITY_HIGH,
1817                                   GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
1818                                   delay, &delayed_done, session);
1819 }
1820
1821
1822 /**
1823  * Handlers for the various TCP messages.
1824  */
1825 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1826   {&handle_tcp_ping, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING, 0},
1827   {&handle_tcp_pong, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG, 0},
1828   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 0},
1829   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1830   {NULL, NULL, 0, 0}
1831 };
1832
1833
1834 static void
1835 create_tcp_handlers (struct Plugin *plugin)
1836 {
1837   unsigned int i;
1838   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1839   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1840   for (i = 0;
1841        i <
1842        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1843        i++)
1844     plugin->handlers[i].callback_cls = plugin;
1845   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1846 }
1847
1848
1849 /**
1850  * Functions with this signature are called whenever a peer
1851  * is disconnected on the network level.
1852  *
1853  * @param cls closure
1854  * @param client identification of the client
1855  */
1856 static void
1857 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1858 {
1859   struct Plugin *plugin = cls;
1860   struct Session *session;
1861
1862 #if DEBUG_TCP
1863   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1864                    "tcp",
1865                    "Notified about network-level disconnect of client %p.\n",
1866                    client);
1867 #endif
1868   session = find_session_by_client (plugin, client);
1869   if (session == NULL)
1870     return;                     /* unknown, nothing to do */
1871 #if DEBUG_TCP
1872   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1873                    "tcp", "Will now destroy session %p.\n", session);
1874 #endif
1875   disconnect_session (session);
1876 }
1877
1878
1879 /**
1880  * Add the IP of our network interface to the list of
1881  * our external IP addresses.
1882  */
1883 static int
1884 process_interfaces (void *cls,
1885                     const char *name,
1886                     int isDefault,
1887                     const struct sockaddr *addr, socklen_t addrlen)
1888 {
1889   struct Plugin *plugin = cls;
1890   int af;
1891   struct sockaddr_in *v4;
1892   struct sockaddr_in6 *v6;
1893
1894   af = addr->sa_family;
1895   if (af == AF_INET)
1896     {
1897       v4 = (struct sockaddr_in *) addr;
1898       v4->sin_port = htons (plugin->adv_port);
1899     }
1900   else
1901     {
1902       GNUNET_assert (af == AF_INET6);
1903       v6 = (struct sockaddr_in6 *) addr;
1904       v6->sin6_port = htons (plugin->adv_port);
1905     }
1906   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1907                    GNUNET_ERROR_TYPE_BULK,
1908                    "tcp", _("Found address `%s' (%s)\n"), 
1909                    GNUNET_a2s(addr, addrlen), name);
1910   plugin->env->notify_address (plugin->env->cls,
1911                                "tcp",
1912                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1913   return GNUNET_OK;
1914 }
1915
1916
1917 /**
1918  * Function called by the resolver for each address obtained from DNS
1919  * for our own hostname.  Add the addresses to the list of our
1920  * external IP addresses.
1921  *
1922  * @param cls closure
1923  * @param addr one of the addresses of the host, NULL for the last address
1924  * @param addrlen length of the address
1925  */
1926 static void
1927 process_hostname_ips (void *cls,
1928                       const struct sockaddr *addr, socklen_t addrlen)
1929 {
1930   struct Plugin *plugin = cls;
1931
1932   if (addr == NULL)
1933     return;
1934   plugin->env->notify_address (plugin->env->cls,
1935                                "tcp",
1936                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1937 }
1938
1939
1940 /**
1941  * Entry point for the plugin.
1942  */
1943 void *
1944 libgnunet_plugin_transport_tcp_init (void *cls)
1945 {
1946   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1947   struct GNUNET_TRANSPORT_PluginFunctions *api;
1948   struct Plugin *plugin;
1949   struct GNUNET_SERVICE_Context *service;
1950   unsigned long long aport;
1951   unsigned long long bport;
1952
1953   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1954   if (service == NULL)
1955     {
1956       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1957                        "tcp",
1958                        _
1959                        ("Failed to start service for `%s' transport plugin.\n"),
1960                        "tcp");
1961       return NULL;
1962     }
1963   aport = 0;
1964   if ((GNUNET_OK !=
1965        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1966                                               "transport-tcp",
1967                                               "PORT",
1968                                               &bport)) ||
1969       (bport > 65535) ||
1970       ((GNUNET_OK ==
1971         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1972                                                "transport-tcp",
1973                                                "ADVERTISED-PORT",
1974                                                &aport)) && (aport > 65535)))
1975     {
1976       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1977                        "tcp",
1978                        _
1979                        ("Require valid port number for service `%s' in configuration!\n"),
1980                        "transport-tcp");
1981       GNUNET_SERVICE_stop (service);
1982       return NULL;
1983     }
1984   if (aport == 0)
1985     aport = bport;
1986   plugin = GNUNET_malloc (sizeof (struct Plugin));
1987   plugin->open_port = bport;
1988   plugin->adv_port = aport;
1989   plugin->env = env;
1990   plugin->lsock = NULL;
1991   plugin->statistics = NULL;
1992   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1993   api->cls = plugin;
1994   api->validate = &tcp_plugin_validate;
1995   api->send = &tcp_plugin_send;
1996   api->cancel = &tcp_plugin_cancel;
1997   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1998   api->set_receive_quota = &tcp_plugin_set_receive_quota;
1999   api->address_suggested = &tcp_plugin_address_suggested;
2000   api->cost_estimate = 42;      /* TODO: ATS */
2001   plugin->service = service;
2002   plugin->server = GNUNET_SERVICE_get_server (service);
2003   create_tcp_handlers (plugin);
2004   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2005                    "tcp", _("TCP transport listening on port %u\n"), bport);
2006   if (aport != bport)
2007     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2008                      "tcp",
2009                      _
2010                      ("TCP transport advertises itself as being on port %u\n"),
2011                      aport);
2012   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
2013                                    plugin);
2014   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2015   GNUNET_RESOLVER_hostname_resolve (env->sched,
2016                                     env->cfg,
2017                                     AF_UNSPEC,
2018                                     HOSTNAME_RESOLVE_TIMEOUT,
2019                                     &process_hostname_ips, plugin);
2020   return api;
2021 }
2022
2023
2024 /**
2025  * Exit point from the plugin.
2026  */
2027 void *
2028 libgnunet_plugin_transport_tcp_done (void *cls)
2029 {
2030   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2031   struct Plugin *plugin = api->cls;
2032
2033   GNUNET_SERVICE_stop (plugin->service);
2034   GNUNET_free (plugin->handlers);
2035   GNUNET_free (plugin);
2036   GNUNET_free (api);
2037   return NULL;
2038 }
2039
2040 /* end of plugin_transport_tcp.c */