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