remove send on connect
[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, 2010 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 3, 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  * @file transport/plugin_transport_tcp.c
22  * @brief Implementation of the TCP transport service
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_connection_lib.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_nat_lib.h"
31 #include "gnunet_os_lib.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 "gnunet_transport_plugin.h"
40 #include "transport.h"
41
42 #define DEBUG_TCP GNUNET_NO
43
44 #define DEBUG_TCP_NAT GNUNET_NO
45
46 /**
47  * Initial handshake message for a session.
48  */
49 struct WelcomeMessage
50 {
51   /**
52    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
53    */
54   struct GNUNET_MessageHeader header;
55
56   /**
57    * Identity of the node connecting (TCP client)
58    */
59   struct GNUNET_PeerIdentity clientIdentity;
60
61 };
62
63
64 /**
65  * Basically a WELCOME message, but with the purpose
66  * of giving the waiting peer a client handle to use
67  */
68 struct TCP_NAT_ProbeMessage
69 {
70   /**
71    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
72    */
73   struct GNUNET_MessageHeader header;
74
75   /**
76    * Identity of the sender of the message.
77    */
78   struct GNUNET_PeerIdentity clientIdentity;
79
80 };
81
82
83 /**
84  * Context for sending a NAT probe via TCP.
85  */
86 struct TCPProbeContext
87 {
88
89   /**
90    * Active probes are kept in a DLL.
91    */
92   struct TCPProbeContext *next;
93
94   /**
95    * Active probes are kept in a DLL.
96    */
97   struct TCPProbeContext *prev;
98
99   /**
100    * Probe connection.
101    */
102   struct GNUNET_CONNECTION_Handle *sock;
103
104   /**
105    * Message to be sent.
106    */
107   struct TCP_NAT_ProbeMessage message;
108
109   /**
110    * Handle to the transmission.
111    */
112   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
113
114   /**
115    * Transport plugin handle.
116    */
117   struct Plugin *plugin;
118 };
119
120
121 /**
122  * Network format for IPv4 addresses.
123  */
124 struct IPv4TcpAddress
125 {
126   /**
127    * IPv4 address, in network byte order.
128    */
129   uint32_t ipv4_addr GNUNET_PACKED;
130
131   /**
132    * Port number, in network byte order.
133    */
134   uint16_t t4_port GNUNET_PACKED;
135
136 };
137
138
139 /**
140  * Network format for IPv6 addresses.
141  */
142 struct IPv6TcpAddress
143 {
144   /**
145    * IPv6 address.
146    */
147   struct in6_addr ipv6_addr GNUNET_PACKED;
148
149   /**
150    * Port number, in network byte order.
151    */
152   uint16_t t6_port GNUNET_PACKED;
153
154 };
155
156
157 /**
158  * Encapsulation of all of the state of the plugin.
159  */
160 struct Plugin;
161
162
163 /**
164  * Information kept for each message that is yet to
165  * be transmitted.
166  */
167 struct PendingMessage
168 {
169
170   /**
171    * This is a doubly-linked list.
172    */
173   struct PendingMessage *next;
174
175   /**
176    * This is a doubly-linked list.
177    */
178   struct PendingMessage *prev;
179
180   /**
181    * The pending message
182    */
183   const char *msg;
184
185   /**
186    * Continuation function to call once the message
187    * has been sent.  Can be NULL if there is no
188    * continuation to call.
189    */
190   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
191
192   /**
193    * Closure for transmit_cont.
194    */
195   void *transmit_cont_cls;
196
197   /**
198    * Timeout value for the pending message.
199    */
200   struct GNUNET_TIME_Absolute timeout;
201
202   /**
203    * So that the gnunet-service-transport can group messages together,
204    * these pending messages need to accept a message buffer and size
205    * instead of just a GNUNET_MessageHeader.
206    */
207   size_t message_size;
208
209 };
210
211
212 /**
213  * Session handle for TCP connections.
214  */
215 struct Session
216 {
217
218   /**
219    * API requirement.
220    */
221   struct SessionHeader header;
222
223   /**
224    * Stored in a linked list.
225    */
226   struct Session *next;
227
228   /**
229    * Pointer to the global plugin struct.
230    */
231   struct Plugin *plugin;
232
233   /**
234    * The client (used to identify this connection)
235    */
236   struct GNUNET_SERVER_Client *client;
237
238   /**
239    * Messages currently pending for transmission
240    * to this peer, if any.
241    */
242   struct PendingMessage *pending_messages_head;
243
244   /**
245    * Messages currently pending for transmission
246    * to this peer, if any.
247    */
248   struct PendingMessage *pending_messages_tail;
249
250   /**
251    * Handle for pending transmission request.
252    */
253   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
254
255   /**
256    * To whom are we talking to (set to our identity
257    * if we are still waiting for the welcome message)
258    */
259   struct GNUNET_PeerIdentity target;
260
261   /**
262    * ID of task used to delay receiving more to throttle sender.
263    */
264   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
265
266   /**
267    * Address of the other peer (either based on our 'connect'
268    * call or on our 'accept' call).
269    */
270   void *connect_addr;
271
272   /**
273    * Last activity on this connection.  Used to select preferred
274    * connection.
275    */
276   struct GNUNET_TIME_Absolute last_activity;
277
278   /**
279    * Length of connect_addr.
280    */
281   size_t connect_alen;
282
283   /**
284    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
285    */
286   int expecting_welcome;
287
288   /**
289    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
290    */
291   int inbound;
292
293   /**
294    * Was this session created using NAT traversal?
295    */
296   int is_nat;
297
298 };
299
300
301 /**
302  * Encapsulation of all of the state of the plugin.
303  */
304 struct Plugin
305 {
306   /**
307    * Our environment.
308    */
309   struct GNUNET_TRANSPORT_PluginEnvironment *env;
310
311   /**
312    * The listen socket.
313    */
314   struct GNUNET_CONNECTION_Handle *lsock;
315
316   /**
317    * Our handle to the NAT module.
318    */
319   struct GNUNET_NAT_Handle *nat;
320
321   /**
322    * List of open TCP sessions.
323    */
324   struct Session *sessions;
325
326   /**
327    * Handle to the network service.
328    */
329   struct GNUNET_SERVICE_Context *service;
330
331   /**
332    * Handle to the server for this service.
333    */
334   struct GNUNET_SERVER_Handle *server;
335
336   /**
337    * Copy of the handler array where the closures are
338    * set to this struct's instance.
339    */
340   struct GNUNET_SERVER_MessageHandler *handlers;
341
342   /**
343    * Map of peers we have tried to contact behind a NAT
344    */
345   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
346   
347   /**
348    * List of active TCP probes.
349    */
350   struct TCPProbeContext *probe_head;
351
352   /**
353    * List of active TCP probes.
354    */
355   struct TCPProbeContext *probe_tail;
356
357   /**
358    * Handle for (DYN)DNS lookup of our external IP.
359    */
360   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
361   
362   /**
363    * How many more TCP sessions are we allowed to open right now?
364    */
365   unsigned long long max_connections;
366
367   /**
368    * ID of task used to update our addresses when one expires.
369    */
370   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
371
372   /**
373    * Port that we are actually listening on.
374    */
375   uint16_t open_port;
376
377   /**
378    * Port that the user said we would have visible to the
379    * rest of the world.
380    */
381   uint16_t adv_port;
382
383 };
384
385
386 /**
387  * Function to check if an inbound connection is acceptable.
388  * Mostly used to limit the total number of open connections 
389  * we can have.
390  *
391  * @param cls the 'struct Plugin'
392  * @param ucred credentials, if available, otherwise NULL
393  * @param addr address
394  * @param addrlen length of address
395  * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
396  *   for unknown address family (will be denied).
397  */
398 static int
399 plugin_tcp_access_check (void *cls,
400                          const struct GNUNET_CONNECTION_Credentials *ucred,
401                          const struct sockaddr *addr,
402                          socklen_t addrlen)
403 {
404   struct Plugin *plugin = cls;
405
406   if (0 == plugin->max_connections)
407     return GNUNET_NO;
408   plugin->max_connections--;
409   return GNUNET_YES;
410 }
411
412
413 /**
414  * Our external IP address/port mapping has changed.
415  *
416  * @param cls closure, the 'struct LocalAddrList'
417  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
418  *     the previous (now invalid) one
419  * @param addr either the previous or the new public IP address
420  * @param addrlen actual lenght of the address
421  */
422 static void
423 tcp_nat_port_map_callback (void *cls,
424                            int add_remove,
425                            const struct sockaddr *addr,
426                            socklen_t addrlen)
427 {
428   struct Plugin *plugin = cls;
429   struct IPv4TcpAddress t4;
430   struct IPv6TcpAddress t6;
431   void *arg;
432   size_t args;
433
434   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
435                    "tcp",
436                    "NPMC called with %d for address `%s'\n",
437                    add_remove,
438                    GNUNET_a2s (addr, addrlen));
439   /* convert 'addr' to our internal format */
440   switch (addr->sa_family)
441     {
442     case AF_INET:
443       GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
444       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
445       t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
446       arg = &t4;
447       args = sizeof (t4);
448       break;
449     case AF_INET6:
450       GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
451       memcpy (&t6.ipv6_addr,
452               &((struct sockaddr_in6 *) addr)->sin6_addr,
453               sizeof (struct in6_addr));
454       t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
455       arg = &t6;
456       args = sizeof (t6);    
457       break;
458     default:
459       GNUNET_break (0);
460       return;
461     }
462   /* modify our published address list */
463   plugin->env->notify_address (plugin->env->cls,
464                                add_remove,
465                                arg, args);
466 }
467
468
469 /**
470  * Function called for a quick conversion of the binary address to
471  * a numeric address.  Note that the caller must not free the
472  * address and that the next call to this function is allowed
473  * to override the address again.
474  *
475  * @param cls closure ('struct Plugin*')
476  * @param addr binary address
477  * @param addrlen length of the address
478  * @return string representing the same address
479  */
480 static const char*
481 tcp_address_to_string (void *cls,
482                        const void *addr,
483                        size_t addrlen)
484 {
485   static char rbuf[INET6_ADDRSTRLEN + 12];
486   char buf[INET6_ADDRSTRLEN];
487   const void *sb;
488   struct in_addr a4;
489   struct in6_addr a6;
490   const struct IPv4TcpAddress *t4;
491   const struct IPv6TcpAddress *t6;
492   int af;
493   uint16_t port;
494
495   if (addrlen == sizeof (struct IPv6TcpAddress))
496     {
497       t6 = addr;
498       af = AF_INET6;
499       port = ntohs (t6->t6_port);
500       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
501       sb = &a6;
502     }
503   else if (addrlen == sizeof (struct IPv4TcpAddress))
504     {
505       t4 = addr;
506       af = AF_INET;
507       port = ntohs (t4->t4_port);
508       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
509       sb = &a4;
510     }
511   else
512     {
513       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
514                        "tcp",
515                        _("Unexpected address length: %u bytes\n"),
516                        (unsigned int) addrlen);
517       GNUNET_break (0);
518       return NULL;
519     }
520   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
521     {
522       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
523       return NULL;
524     }
525   GNUNET_snprintf (rbuf,
526                    sizeof (rbuf),
527                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
528                    buf,
529                    port);
530   return rbuf;
531 }
532
533
534 /**
535  * Find the session handle for the given client.
536  *
537  * @param plugin the plugin
538  * @param client which client to find the session handle for
539  * @return NULL if no matching session exists
540  */
541 static struct Session *
542 find_session_by_client (struct Plugin *plugin,
543                         const struct GNUNET_SERVER_Client *client)
544 {
545   struct Session *ret;
546
547   ret = plugin->sessions;
548   while ((ret != NULL) && (client != ret->client))
549     ret = ret->next;
550   return ret;
551 }
552
553
554 /**
555  * Create a new session.  Also queues a welcome message.
556  *
557  * @param plugin the plugin
558  * @param target peer to connect to
559  * @param client client to use
560  * @param is_nat this a NAT session, we should wait for a client to
561  *               connect to us from an address, then assign that to
562  *               the session
563  * @return new session object
564  */
565 static struct Session *
566 create_session (struct Plugin *plugin,
567                 const struct GNUNET_PeerIdentity *target,
568                 struct GNUNET_SERVER_Client *client, 
569                 int is_nat)
570 {
571   struct Session *ret;
572   struct PendingMessage *pm;
573   struct WelcomeMessage welcome;
574
575   if (is_nat != GNUNET_YES)
576     GNUNET_assert (client != NULL);
577   else
578     GNUNET_assert (client == NULL);
579 #if DEBUG_TCP
580   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
581                    "tcp",
582                    "Creating new session for peer `%4s'\n",
583                    GNUNET_i2s (target));
584 #endif
585   ret = GNUNET_malloc (sizeof (struct Session));
586   ret->last_activity = GNUNET_TIME_absolute_get ();
587   ret->plugin = plugin;
588   ret->is_nat = is_nat;
589   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
590     {
591       ret->next = plugin->sessions;
592       plugin->sessions = ret;
593     }
594   ret->client = client;
595   ret->target = *target;
596   ret->expecting_welcome = GNUNET_YES;
597   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
598   pm->msg = (const char*) &pm[1];
599   pm->message_size = sizeof (struct WelcomeMessage);
600   welcome.header.size = htons (sizeof (struct WelcomeMessage));
601   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
602   welcome.clientIdentity = *plugin->env->my_identity;
603   memcpy (&pm[1], &welcome, sizeof (welcome));
604   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
605   GNUNET_STATISTICS_update (plugin->env->stats,
606                             gettext_noop ("# bytes currently in TCP buffers"),
607                             pm->message_size,
608                             GNUNET_NO);
609   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
610                                ret->pending_messages_tail,
611                                pm);
612   if (is_nat != GNUNET_YES)
613     GNUNET_STATISTICS_update (plugin->env->stats,
614                               gettext_noop ("# TCP sessions active"),
615                               1,
616                               GNUNET_NO);
617   return ret;
618 }
619
620
621 /**
622  * If we have pending messages, ask the server to
623  * transmit them (schedule the respective tasks, etc.)
624  *
625  * @param session for which session should we do this
626  */
627 static void process_pending_messages (struct Session *session);
628
629
630 /**
631  * Function called to notify a client about the socket
632  * being ready to queue more data.  "buf" will be
633  * NULL and "size" zero if the socket was closed for
634  * writing in the meantime.
635  *
636  * @param cls closure
637  * @param size number of bytes available in buf
638  * @param buf where the callee should write the message
639  * @return number of bytes written to buf
640  */
641 static size_t
642 do_transmit (void *cls, size_t size, void *buf)
643 {
644   struct Session *session = cls;
645   struct GNUNET_PeerIdentity pid;
646   struct Plugin *plugin;
647   struct PendingMessage *pos;
648   struct PendingMessage *hd;
649   struct PendingMessage *tl;
650   struct GNUNET_TIME_Absolute now;
651   char *cbuf;
652   size_t ret;
653
654   GNUNET_assert (session != NULL);
655   session->transmit_handle = NULL;
656   plugin = session->plugin;
657   if (buf == NULL)
658     {
659 #if DEBUG_TCP
660       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
661                        "tcp",
662                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
663                        GNUNET_i2s (&session->target));
664 #endif
665       /* timeout; cancel all messages that have already expired */
666       hd = NULL;
667       tl = NULL;
668       ret = 0;
669       now = GNUNET_TIME_absolute_get ();
670       while ( (NULL != (pos = session->pending_messages_head)) &&
671               (pos->timeout.abs_value <= now.abs_value) )
672         {
673           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
674                                        session->pending_messages_tail,
675                                        pos);
676 #if DEBUG_TCP
677           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
678                            "tcp",
679                            "Failed to transmit %u byte message to `%4s'.\n",
680                            pos->message_size,
681                            GNUNET_i2s (&session->target));
682 #endif
683           ret += pos->message_size;
684           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
685         }
686       /* do this call before callbacks (so that if callbacks destroy
687          session, they have a chance to cancel actions done by this
688          call) */
689       process_pending_messages (session);
690       pid = session->target;
691       /* no do callbacks and do not use session again since
692          the callbacks may abort the session */
693       while (NULL != (pos = hd))
694         {
695           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
696           if (pos->transmit_cont != NULL)
697             pos->transmit_cont (pos->transmit_cont_cls,
698                                 &pid, GNUNET_SYSERR);
699           GNUNET_free (pos);
700         }
701       GNUNET_STATISTICS_update (plugin->env->stats,
702                                 gettext_noop ("# bytes currently in TCP buffers"),
703                                 - (int64_t) ret,
704                                 GNUNET_NO);
705       GNUNET_STATISTICS_update (plugin->env->stats,
706                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
707                                 ret,
708                                 GNUNET_NO);
709       return 0;
710     }
711   /* copy all pending messages that would fit */
712   ret = 0;
713   cbuf = buf;
714   hd = NULL;
715   tl = NULL;
716   while (NULL != (pos = session->pending_messages_head))
717     {
718       if (ret + pos->message_size > size)
719         break;
720       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
721                                    session->pending_messages_tail,
722                                    pos);
723       GNUNET_assert (size >= pos->message_size);
724       /* FIXME: this memcpy can be up to 7% of our total runtime */
725       memcpy (cbuf, pos->msg, pos->message_size);
726       cbuf += pos->message_size;
727       ret += pos->message_size;
728       size -= pos->message_size;
729       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
730     }
731   /* schedule 'continuation' before callbacks so that callbacks that
732      cancel everything don't cause us to use a session that no longer
733      exists... */
734   process_pending_messages (session);
735   session->last_activity = GNUNET_TIME_absolute_get ();
736   pid = session->target;
737   /* we'll now call callbacks that may cancel the session; hence
738      we should not use 'session' after this point */
739   while (NULL != (pos = hd))
740     {
741       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
742       if (pos->transmit_cont != NULL)
743         pos->transmit_cont (pos->transmit_cont_cls,
744                             &pid, GNUNET_OK);
745       GNUNET_free (pos);
746     }
747   GNUNET_assert (hd == NULL);
748   GNUNET_assert (tl == NULL);
749 #if DEBUG_TCP > 1
750   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
751                    "tcp",
752                    "Transmitting %u bytes\n", 
753                    ret);
754 #endif
755   GNUNET_STATISTICS_update (plugin->env->stats,
756                             gettext_noop ("# bytes currently in TCP buffers"),
757                             - (int64_t) ret,
758                             GNUNET_NO);
759   GNUNET_STATISTICS_update (plugin->env->stats,
760                             gettext_noop ("# bytes transmitted via TCP"),
761                             ret,
762                             GNUNET_NO);
763   return ret;
764 }
765
766
767 /**
768  * If we have pending messages, ask the server to
769  * transmit them (schedule the respective tasks, etc.)
770  *
771  * @param session for which session should we do this
772  */
773 static void
774 process_pending_messages (struct Session *session)
775 {
776   struct PendingMessage *pm;
777
778   GNUNET_assert (session->client != NULL);
779   if (session->transmit_handle != NULL)
780     return;
781   if (NULL == (pm = session->pending_messages_head))
782     return;
783
784   session->transmit_handle
785     = GNUNET_SERVER_notify_transmit_ready (session->client,
786                                            pm->message_size,
787                                            GNUNET_TIME_absolute_get_remaining
788                                            (pm->timeout),
789                                            &do_transmit, session);
790 }
791
792
793 /**
794  * Functions with this signature are called whenever we need
795  * to close a session due to a disconnect or failure to
796  * establish a connection.
797  *
798  * @param session session to close down
799  */
800 static void
801 disconnect_session (struct Session *session)
802 {
803   struct Session *prev;
804   struct Session *pos;
805   struct PendingMessage *pm;
806
807 #if DEBUG_TCP
808   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
809                    "tcp",
810                    "Disconnecting from `%4s' at %s.\n",
811                    GNUNET_i2s (&session->target),
812                    (session->connect_addr != NULL) ?
813                    tcp_address_to_string (session->plugin,
814                                           session->connect_addr,
815                                           session->connect_alen) : "*");
816 #endif
817   /* remove from session list */
818   prev = NULL;
819   pos = session->plugin->sessions;
820   while (pos != session)
821     {
822       prev = pos;
823       pos = pos->next;
824     }
825   if (prev == NULL)
826     session->plugin->sessions = session->next;
827   else
828     prev->next = session->next;
829
830   /* clean up state */
831   if (session->transmit_handle != NULL)
832     {
833       GNUNET_CONNECTION_notify_transmit_ready_cancel
834         (session->transmit_handle);
835       session->transmit_handle = NULL;
836     }
837   while (NULL != (pm = session->pending_messages_head))
838     {
839 #if DEBUG_TCP
840       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
841                        "tcp",
842                        pm->transmit_cont != NULL
843                        ? "Could not deliver message to `%4s'.\n"
844                        : "Could not deliver message to `%4s', notifying.\n",
845                        GNUNET_i2s (&session->target));
846 #endif
847       GNUNET_STATISTICS_update (session->plugin->env->stats,
848                                 gettext_noop ("# bytes currently in TCP buffers"),
849                                 - (int64_t) pm->message_size,
850                                 GNUNET_NO);
851       GNUNET_STATISTICS_update (session->plugin->env->stats,
852                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
853                                 pm->message_size,
854                                 GNUNET_NO);
855       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
856                                    session->pending_messages_tail,
857                                    pm);
858       if (NULL != pm->transmit_cont)
859         pm->transmit_cont (pm->transmit_cont_cls,
860                            &session->target, GNUNET_SYSERR);
861       GNUNET_free (pm);
862     }
863   GNUNET_break (session->client != NULL);
864   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
865     {
866       GNUNET_SCHEDULER_cancel (session->receive_delay_task);
867       if (session->client != NULL)
868         GNUNET_SERVER_receive_done (session->client,
869                                     GNUNET_SYSERR);     
870     }
871   if (session->client != NULL)
872     {
873       GNUNET_SERVER_client_drop (session->client);
874       session->client = NULL;
875     }
876   GNUNET_STATISTICS_update (session->plugin->env->stats,
877                             gettext_noop ("# TCP sessions active"),
878                             -1,
879                             GNUNET_NO);
880   GNUNET_free_non_null (session->connect_addr);
881   session->plugin->env->session_end (session->plugin->env->cls,
882                                      &session->target,
883                                      session);
884   GNUNET_assert (NULL == session->transmit_handle);
885   GNUNET_free (session);
886 }
887
888
889 /**
890  * Given two otherwise equivalent sessions, pick the better one.
891  *
892  * @param s1 one session (also default)
893  * @param s2 other session
894  * @return "better" session (more active)
895  */
896 static struct Session *
897 select_better_session (struct Session *s1,
898                        struct Session *s2)
899 {
900   if (s1 == NULL)
901     return s2;
902   if (s2 == NULL)
903     return s1;
904   if ( (s1->expecting_welcome == GNUNET_NO) &&
905        (s2->expecting_welcome == GNUNET_YES) )
906     return s1;
907   if ( (s1->expecting_welcome == GNUNET_YES) &&
908        (s2->expecting_welcome == GNUNET_NO) )
909     return s2;
910   if (s1->last_activity.abs_value < s2->last_activity.abs_value)
911     return s2;
912   if (s1->last_activity.abs_value > s2->last_activity.abs_value)
913     return s1;
914   if ( (GNUNET_YES == s1->inbound) &&
915        (GNUNET_NO  == s2->inbound) )
916     return s1;
917   if ( (GNUNET_NO  == s1->inbound) &&
918        (GNUNET_YES == s2->inbound) )
919     return s2;
920   return s1;
921 }
922
923
924
925 /**
926  * Function that can be used by the transport service to transmit
927  * a message using the plugin.   Note that in the case of a
928  * peer disconnecting, the continuation MUST be called
929  * prior to the disconnect notification itself.  This function
930  * will be called with this peer's HELLO message to initiate
931  * a fresh connection to another peer.
932  *
933  * @param cls closure
934  * @param target who should receive this message
935  * @param msg the message to transmit
936  * @param msgbuf_size number of bytes in 'msg'
937  * @param priority how important is the message (most plugins will
938  *                 ignore message priority and just FIFO)
939  * @param timeout how long to wait at most for the transmission (does not
940  *                require plugins to discard the message after the timeout,
941  *                just advisory for the desired delay; most plugins will ignore
942  *                this as well)
943  * @param session which session must be used (or NULL for "any")
944  * @param addr the address to use (can be NULL if the plugin
945  *                is "on its own" (i.e. re-use existing TCP connection))
946  * @param addrlen length of the address in bytes
947  * @param force_address GNUNET_YES if the plugin MUST use the given address,
948  *                GNUNET_NO means the plugin may use any other address and
949  *                GNUNET_SYSERR means that only reliable existing
950  *                bi-directional connections should be used (regardless
951  *                of address)
952  * @param cont continuation to call once the message has
953  *        been transmitted (or if the transport is ready
954  *        for the next transmission call; or if the
955  *        peer disconnected...); can be NULL
956  * @param cont_cls closure for cont
957  * @return number of bytes used (on the physical network, with overheads);
958  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
959  *         and does NOT mean that the message was not transmitted (DV and NAT)
960  */
961 static ssize_t
962 tcp_plugin_send (void *cls,
963                  const struct GNUNET_PeerIdentity *target,
964                  const char *msg,
965                  size_t msgbuf_size,
966                  uint32_t priority,
967                  struct GNUNET_TIME_Relative timeout,
968                  struct Session *session,
969                  const void *addr,
970                  size_t addrlen,
971                  int force_address,
972                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
973 {
974   struct Plugin *plugin = cls;
975   struct Session *cand_session;
976   struct Session *next;
977   struct PendingMessage *pm;
978   struct GNUNET_CONNECTION_Handle *sa;
979   int af;
980   const void *sb;
981   size_t sbs;
982   struct sockaddr_in a4;
983   struct sockaddr_in6 a6;
984   const struct IPv4TcpAddress *t4;
985   const struct IPv6TcpAddress *t6;
986   unsigned int is_natd;
987
988   GNUNET_STATISTICS_update (plugin->env->stats,
989                             gettext_noop ("# bytes TCP was asked to transmit"),
990                             msgbuf_size,
991                             GNUNET_NO);
992   /* FIXME: we could do this cheaper with a hash table
993      where we could restrict the iteration to entries that match
994      the target peer... */
995   is_natd = GNUNET_NO;
996   if (session == NULL)
997     {
998       cand_session = NULL;
999       next = plugin->sessions;
1000       while (NULL != (session = next))
1001         {
1002           next = session->next;
1003           GNUNET_assert (session->client != NULL);
1004           if (0 != memcmp (target,
1005                            &session->target,
1006                            sizeof (struct GNUNET_PeerIdentity)))
1007             continue;
1008           if ( ( (GNUNET_SYSERR == force_address) &&
1009                  (session->expecting_welcome == GNUNET_NO) ) ||
1010                (GNUNET_NO == force_address) )
1011             {
1012               cand_session = select_better_session (cand_session,
1013                                                     session);
1014               continue;
1015             }
1016           if (GNUNET_SYSERR == force_address)
1017             continue;
1018           GNUNET_break (GNUNET_YES == force_address);
1019           if (addr == NULL)
1020             {
1021               GNUNET_break (0);
1022               break;
1023             }
1024           if ( (addrlen != session->connect_alen) && 
1025                (session->is_nat == GNUNET_NO) )
1026             continue;
1027           if ((0 != memcmp (session->connect_addr,
1028                            addr,
1029                            addrlen)) && (session->is_nat == GNUNET_NO))
1030             continue;
1031           cand_session = select_better_session (cand_session,
1032                                                 session);       
1033         }
1034       session = cand_session;
1035     }
1036   if ( (session == NULL) &&
1037        (addr == NULL) )
1038     {
1039 #if DEBUG_TCP
1040       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1041                        "tcp",
1042                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1043                        GNUNET_i2s (target));
1044 #endif
1045       GNUNET_STATISTICS_update (plugin->env->stats,
1046                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1047                                 msgbuf_size,
1048                                 GNUNET_NO);
1049       return -1;
1050     }
1051   if (session == NULL)
1052     {
1053       if (addrlen == sizeof (struct IPv6TcpAddress))
1054         {
1055           t6 = addr;
1056           af = AF_INET6;
1057           memset (&a6, 0, sizeof (a6));
1058 #if HAVE_SOCKADDR_IN_SIN_LEN
1059           a6.sin6_len = sizeof (a6);
1060 #endif
1061           a6.sin6_family = AF_INET6;
1062           a6.sin6_port = t6->t6_port;
1063           if (t6->t6_port == 0)
1064             is_natd = GNUNET_YES;
1065           memcpy (&a6.sin6_addr,
1066                   &t6->ipv6_addr,
1067                   sizeof (struct in6_addr));
1068           sb = &a6;
1069           sbs = sizeof (a6);
1070         }
1071       else if (addrlen == sizeof (struct IPv4TcpAddress))
1072         {
1073           t4 = addr;
1074           af = AF_INET;
1075           memset (&a4, 0, sizeof (a4));
1076 #if HAVE_SOCKADDR_IN_SIN_LEN
1077           a4.sin_len = sizeof (a4);
1078 #endif
1079           a4.sin_family = AF_INET;
1080           a4.sin_port = t4->t4_port;
1081           if (t4->t4_port == 0)
1082             is_natd = GNUNET_YES;
1083           a4.sin_addr.s_addr = t4->ipv4_addr;
1084           sb = &a4;
1085           sbs = sizeof (a4);
1086         }
1087       else
1088         {
1089           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1090                            "tcp",
1091                            _("Address of unexpected length: %u\n"),
1092                            addrlen);
1093           GNUNET_break (0);
1094           return -1;
1095         }
1096
1097       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1098         return -1; /* NAT client only works with IPv4 addresses */
1099       if (0 == plugin->max_connections)
1100         return -1; /* saturated */
1101
1102       if ( (is_natd == GNUNET_YES) &&
1103            (NULL != plugin->nat) &&
1104            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns,
1105                                                                 &target->hashPubKey)) )
1106         {
1107 #if DEBUG_TCP_NAT
1108           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1109                            "tcp",
1110                            _("Found valid IPv4 NAT address (creating session)!\n"));
1111 #endif
1112           session = create_session (plugin,
1113                                     target,
1114                                     NULL, 
1115                                     GNUNET_YES);
1116           GNUNET_assert (session != NULL);
1117
1118           /* create new message entry */
1119           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1120           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1121           pm->msg = (const char*) &pm[1];
1122           memcpy (&pm[1], msg, msgbuf_size);
1123           /* FIXME: this memcpy can be up to 7% of our total run-time
1124              (for transport service) */
1125           pm->message_size = msgbuf_size;
1126           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1127           pm->transmit_cont = cont;
1128           pm->transmit_cont_cls = cont_cls;
1129
1130           /* append pm to pending_messages list */
1131           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1132                                              session->pending_messages_tail,
1133                                              session->pending_messages_tail,
1134                                              pm);
1135
1136           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns,
1137                                                           &target->hashPubKey,
1138                                                           session, 
1139                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1140 #if DEBUG_TCP_NAT
1141           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1142                            "tcp",
1143                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1144                            GNUNET_i2s (target),
1145                            GNUNET_a2s (sb, sbs));
1146 #endif
1147           GNUNET_NAT_run_client (plugin->nat, &a4);
1148           return 0;
1149         }
1150       if ( (is_natd == GNUNET_YES) && 
1151            (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, 
1152                                                                  &target->hashPubKey)) )
1153         {
1154           /* Only do one NAT punch attempt per peer identity */
1155           return -1;
1156         }
1157       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1158       if (sa == NULL)
1159         {
1160 #if DEBUG_TCP
1161           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1162                            "tcp",
1163                            "Failed to create connection to `%4s' at `%s'\n",
1164                            GNUNET_i2s (target),
1165                            GNUNET_a2s (sb, sbs));
1166 #endif
1167           GNUNET_STATISTICS_update (plugin->env->stats,
1168                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1169                                     msgbuf_size,
1170                                     GNUNET_NO);
1171           return -1;
1172         }
1173       GNUNET_assert (0 != plugin->max_connections);
1174       plugin->max_connections--;
1175 #if DEBUG_TCP_NAT
1176       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1177                        "tcp",
1178                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1179                        GNUNET_i2s (target),
1180                        GNUNET_a2s (sb, sbs));
1181 #endif
1182       session = create_session (plugin,
1183                                 target,
1184                                 GNUNET_SERVER_connect_socket (plugin->server,
1185                                                               sa), 
1186                                 GNUNET_NO);
1187       session->connect_addr = GNUNET_malloc (addrlen);
1188       memcpy (session->connect_addr,
1189               addr,
1190               addrlen);
1191       session->connect_alen = addrlen;
1192     }
1193   else  /* session != NULL */
1194     {
1195       /* check if session is valid */
1196       struct Session * ses = plugin->sessions;
1197       while ((ses != NULL) && (ses != session))
1198         ses = ses->next;
1199       if (ses == NULL)
1200         return -1;
1201     }
1202   GNUNET_assert (session != NULL);
1203   GNUNET_assert (session->client != NULL);
1204
1205
1206   GNUNET_SERVER_client_set_timeout(session->client, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1207   GNUNET_STATISTICS_update (plugin->env->stats,
1208                             gettext_noop ("# bytes currently in TCP buffers"),
1209                             msgbuf_size,
1210                             GNUNET_NO);
1211   /* create new message entry */
1212   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1213   pm->msg = (const char*) &pm[1];
1214   memcpy (&pm[1], msg, msgbuf_size);
1215   pm->message_size = msgbuf_size;
1216   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1217   pm->transmit_cont = cont;
1218   pm->transmit_cont_cls = cont_cls;
1219
1220   /* append pm to pending_messages list */
1221   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1222                                      session->pending_messages_tail,
1223                                      session->pending_messages_tail,
1224                                      pm);
1225 #if DEBUG_TCP
1226   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1227                    "tcp",
1228                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1229                    msgbuf_size,
1230                    GNUNET_i2s (target));
1231 #endif
1232   process_pending_messages (session);
1233   return msgbuf_size;
1234 }
1235
1236
1237 /**
1238  * Function that can be called to force a disconnect from the
1239  * specified neighbour.  This should also cancel all previously
1240  * scheduled transmissions.  Obviously the transmission may have been
1241  * partially completed already, which is OK.  The plugin is supposed
1242  * to close the connection (if applicable) and no longer call the
1243  * transmit continuation(s).
1244  *
1245  * Finally, plugin MUST NOT call the services's receive function to
1246  * notify the service that the connection to the specified target was
1247  * closed after a getting this call.
1248  *
1249  * @param cls closure
1250  * @param target peer for which the last transmission is
1251  *        to be cancelled
1252  */
1253 static void
1254 tcp_plugin_disconnect (void *cls,
1255                        const struct GNUNET_PeerIdentity *target)
1256 {
1257   struct Plugin *plugin = cls;
1258   struct Session *session;
1259   struct Session *next;
1260   struct PendingMessage *pm;
1261
1262 #if DEBUG_TCP
1263   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1264                    "tcp",
1265                    "Asked to cancel session with `%4s'\n",
1266                    GNUNET_i2s (target));
1267 #endif
1268   next = plugin->sessions;
1269   while (NULL != (session = next))
1270     {
1271       next = session->next;
1272       if (0 != memcmp (target,
1273                        &session->target,
1274                        sizeof (struct GNUNET_PeerIdentity)))
1275         continue;
1276       pm = session->pending_messages_head;
1277       while (pm != NULL)
1278         {
1279           pm->transmit_cont = NULL;
1280           pm->transmit_cont_cls = NULL;
1281           pm = pm->next;
1282         }
1283       GNUNET_STATISTICS_update (session->plugin->env->stats,
1284                                 gettext_noop ("# transport-service disconnect requests for TCP"),
1285                                 1,
1286                                 GNUNET_NO);
1287       disconnect_session (session);
1288     }
1289 }
1290
1291
1292 /**
1293  * Context for address to string conversion.
1294  */
1295 struct PrettyPrinterContext
1296 {
1297   /**
1298    * Function to call with the result.
1299    */
1300   GNUNET_TRANSPORT_AddressStringCallback asc;
1301
1302   /**
1303    * Clsoure for 'asc'.
1304    */
1305   void *asc_cls;
1306
1307   /**
1308    * Port to add after the IP address.
1309    */
1310   uint16_t port;
1311 };
1312
1313
1314 /**
1315  * Append our port and forward the result.
1316  *
1317  * @param cls the 'struct PrettyPrinterContext*'
1318  * @param hostname hostname part of the address
1319  */
1320 static void
1321 append_port (void *cls, const char *hostname)
1322 {
1323   struct PrettyPrinterContext *ppc = cls;
1324   char *ret;
1325
1326   if (hostname == NULL)
1327     {
1328       ppc->asc (ppc->asc_cls, NULL);
1329       GNUNET_free (ppc);
1330       return;
1331     }
1332   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1333   ppc->asc (ppc->asc_cls, ret);
1334   GNUNET_free (ret);
1335 }
1336
1337
1338 /**
1339  * Convert the transports address to a nice, human-readable
1340  * format.
1341  *
1342  * @param cls closure
1343  * @param type name of the transport that generated the address
1344  * @param addr one of the addresses of the host, NULL for the last address
1345  *        the specific address format depends on the transport
1346  * @param addrlen length of the address
1347  * @param numeric should (IP) addresses be displayed in numeric form?
1348  * @param timeout after how long should we give up?
1349  * @param asc function to call on each string
1350  * @param asc_cls closure for asc
1351  */
1352 static void
1353 tcp_plugin_address_pretty_printer (void *cls,
1354                                    const char *type,
1355                                    const void *addr,
1356                                    size_t addrlen,
1357                                    int numeric,
1358                                    struct GNUNET_TIME_Relative timeout,
1359                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1360                                    void *asc_cls)
1361 {
1362   struct PrettyPrinterContext *ppc;
1363   const void *sb;
1364   size_t sbs;
1365   struct sockaddr_in a4;
1366   struct sockaddr_in6 a6;
1367   const struct IPv4TcpAddress *t4;
1368   const struct IPv6TcpAddress *t6;
1369   uint16_t port;
1370
1371   if (addrlen == sizeof (struct IPv6TcpAddress))
1372     {
1373       t6 = addr;
1374       memset (&a6, 0, sizeof (a6));
1375       a6.sin6_family = AF_INET6;
1376       a6.sin6_port = t6->t6_port;
1377       memcpy (&a6.sin6_addr,
1378               &t6->ipv6_addr,
1379               sizeof (struct in6_addr));
1380       port = ntohs (t6->t6_port);
1381       sb = &a6;
1382       sbs = sizeof (a6);
1383     }
1384   else if (addrlen == sizeof (struct IPv4TcpAddress))
1385     {
1386       t4 = addr;
1387       memset (&a4, 0, sizeof (a4));
1388       a4.sin_family = AF_INET;
1389       a4.sin_port = t4->t4_port;
1390       a4.sin_addr.s_addr = t4->ipv4_addr;
1391       port = ntohs (t4->t4_port);
1392       sb = &a4;
1393       sbs = sizeof (a4);
1394     }
1395   else
1396     {
1397       /* invalid address */
1398       GNUNET_break_op (0);
1399       asc (asc_cls, NULL);
1400       return;
1401     }
1402   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1403   ppc->asc = asc;
1404   ppc->asc_cls = asc_cls;
1405   ppc->port = port;
1406   GNUNET_RESOLVER_hostname_get (sb,
1407                                 sbs,
1408                                 !numeric, timeout, &append_port, ppc);
1409 }
1410
1411
1412 /**
1413  * Check if the given port is plausible (must be either our listen
1414  * port or our advertised port), or any port if we are behind NAT
1415  * and do not have a port open.  If it is neither, we return
1416  * GNUNET_SYSERR.
1417  *
1418  * @param plugin global variables
1419  * @param in_port port number to check
1420  * @return GNUNET_OK if port is either open_port or adv_port
1421  */
1422 static int
1423 check_port (struct Plugin *plugin, 
1424             uint16_t in_port)
1425 {
1426   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1427     return GNUNET_OK;
1428   return GNUNET_SYSERR;
1429 }
1430
1431
1432 /**
1433  * Function that will be called to check if a binary address for this
1434  * plugin is well-formed and corresponds to an address for THIS peer
1435  * (as per our configuration).  Naturally, if absolutely necessary,
1436  * plugins can be a bit conservative in their answer, but in general
1437  * plugins should make sure that the address does not redirect
1438  * traffic to a 3rd party that might try to man-in-the-middle our
1439  * traffic.
1440  *
1441  * @param cls closure, our 'struct Plugin*'
1442  * @param addr pointer to the address
1443  * @param addrlen length of addr
1444  * @return GNUNET_OK if this is a plausible address for this peer
1445  *         and transport, GNUNET_SYSERR if not
1446  */
1447 static int
1448 tcp_plugin_check_address (void *cls,
1449                           const void *addr,
1450                           size_t addrlen)
1451 {
1452   struct Plugin *plugin = cls;
1453   struct IPv4TcpAddress *v4;
1454   struct IPv6TcpAddress *v6;
1455
1456   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1457       (addrlen != sizeof (struct IPv6TcpAddress)))
1458     {
1459       GNUNET_break_op (0);
1460       return GNUNET_SYSERR;
1461     }
1462   if (addrlen == sizeof (struct IPv4TcpAddress))
1463     {
1464       v4 = (struct IPv4TcpAddress *) addr;
1465       if (GNUNET_OK !=
1466           check_port (plugin, ntohs (v4->t4_port)))
1467         return GNUNET_SYSERR;
1468       if (GNUNET_OK !=
1469           GNUNET_NAT_test_address (plugin->nat,
1470                                    &v4->ipv4_addr, sizeof (struct in_addr)))
1471         return GNUNET_SYSERR;   
1472     }
1473   else
1474     {
1475       v6 = (struct IPv6TcpAddress *) addr;
1476       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1477         {
1478           GNUNET_break_op (0);
1479           return GNUNET_SYSERR;
1480         }
1481       if (GNUNET_OK !=
1482           check_port (plugin, ntohs (v6->t6_port)))
1483         return GNUNET_SYSERR;
1484       if (GNUNET_OK !=
1485           GNUNET_NAT_test_address (plugin->nat,
1486                                    &v6->ipv6_addr, sizeof (struct in6_addr)))
1487         return GNUNET_SYSERR;
1488     }
1489   return GNUNET_OK;
1490 }
1491
1492
1493 /**
1494  * We've received a nat probe from this peer via TCP.  Finish
1495  * creating the client session and resume sending of queued
1496  * messages.
1497  *
1498  * @param cls closure
1499  * @param client identification of the client
1500  * @param message the actual message
1501  */
1502 static void
1503 handle_tcp_nat_probe (void *cls,
1504                       struct GNUNET_SERVER_Client *client,
1505                       const struct GNUNET_MessageHeader *message)
1506 {
1507   struct Plugin *plugin = cls;
1508   struct Session *session;
1509   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1510   size_t alen;
1511   void *vaddr;
1512   struct IPv4TcpAddress *t4;
1513   struct IPv6TcpAddress *t6;
1514   const struct sockaddr_in *s4;
1515   const struct sockaddr_in6 *s6;
1516
1517 #if DEBUG_TCP_NAT
1518   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1519                    "tcp",
1520                    "received NAT probe\n");
1521 #endif
1522   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1523    * a connection to this peer by running gnunet-nat-client.  This peer
1524    * received the punch message and now wants us to use the new connection
1525    * as the default for that peer.  Do so and then send a WELCOME message
1526    * so we can really be connected!
1527    */
1528   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1529     {
1530       GNUNET_break_op(0);
1531       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1532       return;
1533     }
1534
1535   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *)message;
1536   if (0 == memcmp (&tcp_nat_probe->clientIdentity,
1537                    plugin->env->my_identity,
1538                    sizeof (struct GNUNET_PeerIdentity)))
1539     {
1540       /* refuse connections from ourselves */
1541       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1542       return;
1543     }
1544
1545   session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, 
1546                                               &tcp_nat_probe->clientIdentity.hashPubKey);
1547   if (session == NULL)
1548     {
1549 #if DEBUG_TCP_NAT
1550       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1551                        "tcp",
1552                        "Did NOT find session for NAT probe!\n");
1553 #endif
1554       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1555       return;
1556     }
1557 #if DEBUG_TCP_NAT
1558   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1559                    "tcp",
1560                    "Found session for NAT probe!\n");
1561 #endif
1562   GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, 
1563                                                      &tcp_nat_probe->clientIdentity.hashPubKey,
1564                                                      session) == GNUNET_YES);
1565   if (GNUNET_OK !=
1566       GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1567     {
1568       GNUNET_break (0);
1569       GNUNET_free (session);
1570       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1571       return;
1572     }
1573
1574   GNUNET_SERVER_client_keep (client);
1575   session->client = client;
1576   session->last_activity = GNUNET_TIME_absolute_get ();
1577   session->inbound = GNUNET_NO;
1578
1579 #if DEBUG_TCP_NAT
1580   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1581                    "tcp",
1582                    "Found address `%s' for incoming connection\n",
1583                    GNUNET_a2s (vaddr, alen));
1584 #endif
1585   switch (((const struct sockaddr *)vaddr)->sa_family)
1586     {
1587     case AF_INET:
1588       s4 = vaddr;
1589       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1590       t4->t4_port = s4->sin_port;
1591       t4->ipv4_addr = s4->sin_addr.s_addr;
1592       session->connect_addr = t4;
1593       session->connect_alen = sizeof (struct IPv4TcpAddress);
1594       break;
1595     case AF_INET6:    
1596       s6 = vaddr;
1597       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1598       t6->t6_port = s6->sin6_port;
1599       memcpy (&t6->ipv6_addr,
1600               &s6->sin6_addr,
1601               sizeof (struct in6_addr));
1602       session->connect_addr = t6;
1603       session->connect_alen = sizeof (struct IPv6TcpAddress);
1604       break;
1605     default:
1606       GNUNET_break_op (0);
1607 #if DEBUG_TCP_NAT
1608       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1609                        "tcp",
1610                        "Bad address for incoming connection!\n");
1611 #endif
1612       GNUNET_free (vaddr);
1613       GNUNET_SERVER_client_drop (client);
1614       GNUNET_free (session);
1615       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1616       return;
1617     }
1618   GNUNET_free (vaddr);
1619   
1620   session->next = plugin->sessions;
1621   plugin->sessions = session;
1622   GNUNET_STATISTICS_update (plugin->env->stats,
1623                             gettext_noop ("# TCP sessions active"),
1624                             1,
1625                             GNUNET_NO);
1626   process_pending_messages (session);
1627   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1628 }
1629
1630
1631 /**
1632  * We've received a welcome from this peer via TCP.  Possibly create a
1633  * fresh client record and send back our welcome.
1634  *
1635  * @param cls closure
1636  * @param client identification of the client
1637  * @param message the actual message
1638  */
1639 static void
1640 handle_tcp_welcome (void *cls,
1641                     struct GNUNET_SERVER_Client *client,
1642                     const struct GNUNET_MessageHeader *message)
1643 {
1644   struct Plugin *plugin = cls;
1645   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1646   struct Session *session;
1647   size_t alen;
1648   void *vaddr;
1649   struct IPv4TcpAddress *t4;
1650   struct IPv6TcpAddress *t6;
1651   const struct sockaddr_in *s4;
1652   const struct sockaddr_in6 *s6;
1653   
1654   if (0 == memcmp (&wm->clientIdentity,
1655                    plugin->env->my_identity,
1656                    sizeof (struct GNUNET_PeerIdentity)))
1657     {
1658       /* refuse connections from ourselves */
1659       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1660       return;
1661     }
1662 #if DEBUG_TCP
1663   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1664                    "tcp",
1665                    "Received %s message from `%4s'.\n",
1666                    "WELCOME",
1667                    GNUNET_i2s (&wm->clientIdentity));
1668 #endif
1669   GNUNET_STATISTICS_update (plugin->env->stats,
1670                             gettext_noop ("# TCP WELCOME messages received"),
1671                             1,
1672                             GNUNET_NO);
1673   session = find_session_by_client (plugin, client);
1674
1675   if (session == NULL)
1676     {
1677 #if DEBUG_TCP_NAT
1678       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1679                        "tcp",
1680                        "Received %s message from a `%4s', creating new session\n",
1681                        "WELCOME",
1682                        GNUNET_i2s (&wm->clientIdentity));
1683 #endif
1684       GNUNET_SERVER_client_keep (client);
1685       session = create_session (plugin,
1686                                 &wm->clientIdentity,
1687                                 client,
1688                                 GNUNET_NO);
1689       session->inbound = GNUNET_YES;
1690       if (GNUNET_OK ==
1691           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1692         {
1693 #if DEBUG_TCP_NAT
1694           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1695                            "tcp",
1696                            "Found address `%s' for incoming connection\n",
1697                            GNUNET_a2s (vaddr, alen));
1698 #endif
1699           if (alen == sizeof (struct sockaddr_in))
1700             {
1701               s4 = vaddr;
1702               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1703               t4->t4_port = s4->sin_port;
1704               t4->ipv4_addr = s4->sin_addr.s_addr;
1705               session->connect_addr = t4;
1706               session->connect_alen = sizeof (struct IPv4TcpAddress);
1707             }
1708           else if (alen == sizeof (struct sockaddr_in6))
1709             {
1710               s6 = vaddr;
1711               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1712               t6->t6_port = s6->sin6_port;
1713               memcpy (&t6->ipv6_addr,
1714                       &s6->sin6_addr,
1715                       sizeof (struct in6_addr));
1716               session->connect_addr = t6;
1717               session->connect_alen = sizeof (struct IPv6TcpAddress);
1718             }
1719
1720           GNUNET_free (vaddr);
1721         }
1722       else
1723         {
1724 #if DEBUG_TCP
1725           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1726                            "tcp",
1727                            "Did not obtain TCP socket address for incoming connection\n");
1728 #endif
1729         }
1730       process_pending_messages (session);
1731     }
1732   else
1733     {
1734 #if DEBUG_TCP_NAT
1735     if (GNUNET_OK ==
1736         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1737       {
1738         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1739                          "tcp",
1740                          "Found address `%s' (already have session)\n",
1741                          GNUNET_a2s (vaddr, alen));
1742         GNUNET_free (vaddr);
1743       }
1744 #endif
1745     }
1746
1747   if (session->expecting_welcome != GNUNET_YES)
1748     {
1749       GNUNET_break_op (0);
1750       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1751       return;
1752     }
1753   session->last_activity = GNUNET_TIME_absolute_get ();
1754   session->expecting_welcome = GNUNET_NO;
1755   GNUNET_SERVER_client_set_timeout(client, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1756   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1757 }
1758
1759
1760 /**
1761  * Task to signal the server that we can continue
1762  * receiving from the TCP client now.
1763  *
1764  * @param cls the 'struct Session*'
1765  * @param tc task context (unused)
1766  */
1767 static void
1768 delayed_done (void *cls, 
1769               const struct GNUNET_SCHEDULER_TaskContext *tc)
1770 {
1771   struct Session *session = cls;
1772   struct GNUNET_TIME_Relative delay;
1773
1774   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1775   delay = session->plugin->env->receive (session->plugin->env->cls,
1776                                          &session->target,
1777                                          NULL,
1778                                          NULL, 0,
1779                                          session,
1780                                          NULL, 0);
1781   if (delay.rel_value == 0)
1782     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1783   else
1784     session->receive_delay_task =
1785       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1786 }
1787
1788
1789 /**
1790  * We've received data for this peer via TCP.  Unbox,
1791  * compute latency and forward.
1792  *
1793  * @param cls closure
1794  * @param client identification of the client
1795  * @param message the actual message
1796  */
1797 static void
1798 handle_tcp_data (void *cls,
1799                  struct GNUNET_SERVER_Client *client,
1800                  const struct GNUNET_MessageHeader *message)
1801 {
1802   struct Plugin *plugin = cls;
1803   struct Session *session;
1804   struct GNUNET_TIME_Relative delay;
1805   uint16_t type;
1806
1807   type = ntohs (message->type);
1808   if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) || 
1809        (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
1810     {
1811       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1812       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1813       return;
1814     }
1815   session = find_session_by_client (plugin, client);
1816   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome) )
1817     {
1818       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1819       return;
1820     }
1821   session->last_activity = GNUNET_TIME_absolute_get ();
1822 #if DEBUG_TCP > 1
1823   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1824                    "tcp",
1825                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1826                    (unsigned int) ntohs (message->size),
1827                    (unsigned int) ntohs (message->type),
1828                    GNUNET_i2s (&session->target));
1829 #endif
1830   GNUNET_STATISTICS_update (plugin->env->stats,
1831                             gettext_noop ("# bytes received via TCP"),
1832                             ntohs (message->size),
1833                             GNUNET_NO);
1834   struct GNUNET_TRANSPORT_ATS_Information distance[2];
1835   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
1836   distance[0].value = htonl (1);
1837   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1838   distance[1].value = htonl (0);
1839   delay = plugin->env->receive (plugin->env->cls, &session->target, message,
1840                                 (const struct GNUNET_TRANSPORT_ATS_Information *) &distance,
1841                                 2,
1842                                 session,
1843                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1844                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1845   if (delay.rel_value == 0)
1846     {
1847       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1848     }
1849   else
1850     {
1851 #if DEBUG_TCP 
1852       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1853                        "tcp",
1854                        "Throttling receiving from `%s' for %llu ms\n",
1855                        GNUNET_i2s (&session->target),
1856                        (unsigned long long) delay.rel_value);
1857 #endif
1858       GNUNET_SERVER_disable_receive_done_warning (client);
1859       session->receive_delay_task =
1860         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1861     }
1862 }
1863
1864
1865 /**
1866  * Functions with this signature are called whenever a peer
1867  * is disconnected on the network level.
1868  *
1869  * @param cls closure
1870  * @param client identification of the client
1871  */
1872 static void
1873 disconnect_notify (void *cls,
1874                    struct GNUNET_SERVER_Client *client)
1875 {
1876   struct Plugin *plugin = cls;
1877   struct Session *session;
1878
1879   if (client == NULL)
1880     return;
1881   plugin->max_connections++;
1882   session = find_session_by_client (plugin, client);
1883   if (session == NULL)
1884     return;                     /* unknown, nothing to do */
1885 #if DEBUG_TCP
1886   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1887                    "tcp",
1888                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1889                    GNUNET_i2s (&session->target),
1890                    (session->connect_addr != NULL) ?
1891                    tcp_address_to_string (session->plugin,
1892                                           session->connect_addr,
1893                                           session->connect_alen) : "*");
1894 #endif
1895   GNUNET_STATISTICS_update (session->plugin->env->stats,
1896                             gettext_noop ("# network-level TCP disconnect events"),
1897                             1,
1898                             GNUNET_NO);
1899   disconnect_session (session);
1900 }
1901
1902
1903 /**
1904  * We can now send a probe message, copy into buffer to really send.
1905  *
1906  * @param cls closure, a struct TCPProbeContext
1907  * @param size max size to copy
1908  * @param buf buffer to copy message to
1909  * @return number of bytes copied into buf
1910  */
1911 static size_t
1912 notify_send_probe (void *cls,
1913                    size_t size,
1914                    void *buf)
1915 {
1916   struct TCPProbeContext *tcp_probe_ctx = cls;
1917   struct Plugin *plugin = tcp_probe_ctx->plugin;
1918   size_t ret;
1919
1920   tcp_probe_ctx->transmit_handle = NULL;
1921   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
1922                                plugin->probe_tail,
1923                                tcp_probe_ctx);
1924   if (buf == NULL)
1925     {
1926       GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1927       GNUNET_free(tcp_probe_ctx);
1928       return 0;    
1929     }
1930   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1931   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1932   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1933                                 tcp_probe_ctx->sock);
1934   ret = sizeof(tcp_probe_ctx->message);
1935   GNUNET_free(tcp_probe_ctx);
1936   return ret;
1937 }
1938
1939
1940 /**
1941  * Function called by the NAT subsystem suggesting another peer wants
1942  * to connect to us via connection reversal.  Try to connect back to the
1943  * given IP.
1944  *
1945  * @param cls closure
1946  * @param addr address to try
1947  * @param addrlen number of bytes in addr
1948  */
1949 static void
1950 try_connection_reversal (void *cls,
1951                          const struct sockaddr *addr,
1952                          socklen_t addrlen)
1953 {
1954   struct Plugin *plugin = cls;
1955   struct GNUNET_CONNECTION_Handle *sock;
1956   struct TCPProbeContext *tcp_probe_ctx;
1957
1958   /**
1959    * We have received an ICMP response, ostensibly from a peer
1960    * that wants to connect to us! Send a message to establish a connection.
1961    */
1962   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, 
1963                                                  addr,
1964                                                  addrlen);
1965   if (sock == NULL)
1966     {
1967       /* failed for some odd reason (out of sockets?); ignore attempt */
1968       return;
1969     }
1970
1971   /* FIXME: do we need to track these probe context objects so that
1972      we can clean them up on plugin unload? */
1973   tcp_probe_ctx
1974     = GNUNET_malloc(sizeof(struct TCPProbeContext));
1975   tcp_probe_ctx->message.header.size
1976     = htons(sizeof(struct TCP_NAT_ProbeMessage));
1977   tcp_probe_ctx->message.header.type
1978     = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1979   memcpy (&tcp_probe_ctx->message.clientIdentity,
1980           plugin->env->my_identity,
1981           sizeof(struct GNUNET_PeerIdentity));
1982   tcp_probe_ctx->plugin = plugin;
1983   tcp_probe_ctx->sock = sock;
1984   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
1985                                plugin->probe_tail,
1986                                tcp_probe_ctx);
1987   tcp_probe_ctx->transmit_handle 
1988     = GNUNET_CONNECTION_notify_transmit_ready (sock,
1989                                                ntohs (tcp_probe_ctx->message.header.size),
1990                                                GNUNET_TIME_UNIT_FOREVER_REL,
1991                                                &notify_send_probe, tcp_probe_ctx);
1992   
1993 }
1994
1995
1996 /**
1997  * Entry point for the plugin.
1998  *
1999  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2000  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2001  */
2002 void *
2003 libgnunet_plugin_transport_tcp_init (void *cls)
2004 {
2005   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2006     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2007      sizeof (struct WelcomeMessage)},
2008     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2009     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2010     {NULL, NULL, 0, 0}
2011   };
2012   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2013   struct GNUNET_TRANSPORT_PluginFunctions *api;
2014   struct Plugin *plugin;
2015   struct GNUNET_SERVICE_Context *service;
2016   unsigned long long aport;
2017   unsigned long long bport;
2018   unsigned long long max_connections;
2019   unsigned int i;
2020   struct GNUNET_TIME_Relative idle_timeout;
2021   int ret;
2022   struct sockaddr **addrs;
2023   socklen_t *addrlens;
2024
2025   if (GNUNET_OK !=
2026       GNUNET_CONFIGURATION_get_value_number (env->cfg,
2027                                              "transport-tcp",
2028                                              "MAX_CONNECTIONS",
2029                                              &max_connections))
2030     max_connections = 128;
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)) && 
2044         (aport > 65535)) )
2045     {
2046       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2047                        "tcp",
2048                        _("Require valid port number for service `%s' in configuration!\n"),
2049                        "transport-tcp");
2050       return NULL;
2051     } 
2052   if (aport == 0)
2053     aport = bport;
2054   if (bport == 0)
2055     aport = 0;
2056   if (bport != 0)
2057     {
2058       service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);      
2059       if (service == NULL)
2060         {
2061           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2062                            "tcp",
2063                            _("Failed to start service.\n"));
2064           return NULL;
2065         }
2066     }
2067   else
2068     service = NULL;
2069
2070
2071
2072   plugin = GNUNET_malloc (sizeof (struct Plugin));
2073   plugin->max_connections = max_connections;
2074   plugin->open_port = bport;
2075   plugin->adv_port = aport;
2076   plugin->env = env;
2077   plugin->lsock = NULL;
2078   if ( (service != NULL) &&
2079        (GNUNET_SYSERR !=
2080         (ret = GNUNET_SERVICE_get_server_addresses ("transport-tcp",
2081                                                     env->cfg,
2082                                                     &addrs,
2083                                                     &addrlens))) )
2084     {
2085       plugin->nat = GNUNET_NAT_register (env->cfg,
2086                                          GNUNET_YES,
2087                                          aport,
2088                                          (unsigned int) ret,
2089                                          (const struct sockaddr **) addrs,
2090                                          addrlens,
2091                                          &tcp_nat_port_map_callback,
2092                                          &try_connection_reversal,
2093                                          plugin);
2094       while (ret > 0)
2095       {
2096         ret--;
2097         GNUNET_assert (addrs[ret] != NULL);
2098         GNUNET_free (addrs[ret]);
2099       }
2100       GNUNET_free_non_null (addrs);
2101       GNUNET_free_non_null (addrlens);
2102     }
2103   else
2104     {
2105       plugin->nat = GNUNET_NAT_register (env->cfg,
2106                                          GNUNET_YES,
2107                                          0,
2108                                          0, NULL, NULL,
2109                                          NULL,
2110                                          &try_connection_reversal,
2111                                          plugin);
2112     }
2113   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2114   api->cls = plugin;
2115   api->send = &tcp_plugin_send;
2116   api->disconnect = &tcp_plugin_disconnect;
2117   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2118   api->check_address = &tcp_plugin_check_address;
2119   api->address_to_string = &tcp_address_to_string;
2120   plugin->service = service;
2121   if (service != NULL)   
2122     {
2123       plugin->server = GNUNET_SERVICE_get_server (service);
2124     }
2125   else
2126     {
2127       if (GNUNET_OK !=
2128           GNUNET_CONFIGURATION_get_value_time (env->cfg,
2129                                                "transport-tcp",
2130                                                "TIMEOUT",
2131                                                &idle_timeout))
2132         {
2133           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2134                            "tcp",
2135                            _("Failed to find option %s in section %s!\n"),
2136                            "TIMEOUT",
2137                            "transport-tcp");
2138           if (plugin->nat != NULL)
2139             GNUNET_NAT_unregister (plugin->nat);
2140           GNUNET_free (plugin);
2141           GNUNET_free (api);
2142           return NULL;
2143         }
2144       plugin->server = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin, NULL,
2145                                                           idle_timeout, GNUNET_YES);
2146     }
2147   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2148   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2149   for (i = 0;
2150        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2151        i++)
2152     plugin->handlers[i].callback_cls = plugin;
2153   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2154   GNUNET_SERVER_disconnect_notify (plugin->server,
2155                                    &disconnect_notify,
2156                                    plugin);    
2157   plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(16);
2158   if (bport != 0)
2159     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
2160                      "tcp",
2161                      _("TCP transport listening on port %llu\n"), 
2162                      bport);
2163   else
2164     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
2165                      "tcp",
2166                      _("TCP transport not listening on any port (client only)\n"));
2167   if (aport != bport)
2168     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2169                      "tcp",
2170                      _("TCP transport advertises itself as being on port %llu\n"),
2171                      aport);
2172   return api;
2173 }
2174
2175
2176 /**
2177  * Exit point from the plugin.
2178  */
2179 void *
2180 libgnunet_plugin_transport_tcp_done (void *cls)
2181 {
2182   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2183   struct Plugin *plugin = api->cls;
2184   struct Session *session;
2185   struct TCPProbeContext *tcp_probe;
2186
2187   while (NULL != (session = plugin->sessions))
2188     disconnect_session (session);
2189   if (plugin->service != NULL)
2190     GNUNET_SERVICE_stop (plugin->service);
2191   else
2192     GNUNET_SERVER_destroy (plugin->server);
2193   GNUNET_free (plugin->handlers);
2194   if (plugin->nat != NULL)
2195     GNUNET_NAT_unregister (plugin->nat);
2196   while (NULL != (tcp_probe = plugin->probe_head))
2197     {
2198       GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2199                                    plugin->probe_tail,
2200                                    tcp_probe);
2201       GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2202       GNUNET_free (tcp_probe);
2203     }
2204   GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2205   GNUNET_free (plugin);
2206   GNUNET_free (api);
2207   return NULL;
2208 }
2209
2210 /* end of plugin_transport_tcp.c */