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