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