872bac4ce3becad695c0a82802b0491f7086680c
[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 /**
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   else if (session->client != NULL)
872     GNUNET_SERVER_client_drop (session->client);
873   GNUNET_STATISTICS_update (session->plugin->env->stats,
874                             gettext_noop ("# TCP sessions active"),
875                             -1,
876                             GNUNET_NO);
877   GNUNET_free_non_null (session->connect_addr);
878
879   session->plugin->env->session_end (session->plugin->env->cls,
880                                      &session->target,
881                                      session);
882
883   GNUNET_free (session);
884 }
885
886
887 /**
888  * Given two otherwise equivalent sessions, pick the better one.
889  *
890  * @param s1 one session (also default)
891  * @param s2 other session
892  * @return "better" session (more active)
893  */
894 static struct Session *
895 select_better_session (struct Session *s1,
896                        struct Session *s2)
897 {
898   if (s1 == NULL)
899     return s2;
900   if (s2 == NULL)
901     return s1;
902   if ( (s1->expecting_welcome == GNUNET_NO) &&
903        (s2->expecting_welcome == GNUNET_YES) )
904     return s1;
905   if ( (s1->expecting_welcome == GNUNET_YES) &&
906        (s2->expecting_welcome == GNUNET_NO) )
907     return s2;
908   if (s1->last_activity.abs_value < s2->last_activity.abs_value)
909     return s2;
910   if (s1->last_activity.abs_value > s2->last_activity.abs_value)
911     return s1;
912   if ( (GNUNET_YES == s1->inbound) &&
913        (GNUNET_NO  == s2->inbound) )
914     return s1;
915   if ( (GNUNET_NO  == s1->inbound) &&
916        (GNUNET_YES == s2->inbound) )
917     return s2;
918   return s1;
919 }
920
921
922
923 /**
924  * Function that can be used by the transport service to transmit
925  * a message using the plugin.   Note that in the case of a
926  * peer disconnecting, the continuation MUST be called
927  * prior to the disconnect notification itself.  This function
928  * will be called with this peer's HELLO message to initiate
929  * a fresh connection to another peer.
930  *
931  * @param cls closure
932  * @param target who should receive this message
933  * @param msg the message to transmit
934  * @param msgbuf_size number of bytes in 'msg'
935  * @param priority how important is the message (most plugins will
936  *                 ignore message priority and just FIFO)
937  * @param timeout how long to wait at most for the transmission (does not
938  *                require plugins to discard the message after the timeout,
939  *                just advisory for the desired delay; most plugins will ignore
940  *                this as well)
941  * @param session which session must be used (or NULL for "any")
942  * @param addr the address to use (can be NULL if the plugin
943  *                is "on its own" (i.e. re-use existing TCP connection))
944  * @param addrlen length of the address in bytes
945  * @param force_address GNUNET_YES if the plugin MUST use the given address,
946  *                GNUNET_NO means the plugin may use any other address and
947  *                GNUNET_SYSERR means that only reliable existing
948  *                bi-directional connections should be used (regardless
949  *                of address)
950  * @param cont continuation to call once the message has
951  *        been transmitted (or if the transport is ready
952  *        for the next transmission call; or if the
953  *        peer disconnected...); can be NULL
954  * @param cont_cls closure for cont
955  * @return number of bytes used (on the physical network, with overheads);
956  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
957  *         and does NOT mean that the message was not transmitted (DV and NAT)
958  */
959 static ssize_t
960 tcp_plugin_send (void *cls,
961                  const struct GNUNET_PeerIdentity *target,
962                  const char *msg,
963                  size_t msgbuf_size,
964                  uint32_t priority,
965                  struct GNUNET_TIME_Relative timeout,
966                  struct Session *session,
967                  const void *addr,
968                  size_t addrlen,
969                  int force_address,
970                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
971 {
972   struct Plugin *plugin = cls;
973   struct Session *cand_session;
974   struct Session *next;
975   struct PendingMessage *pm;
976   struct GNUNET_CONNECTION_Handle *sa;
977   int af;
978   const void *sb;
979   size_t sbs;
980   struct sockaddr_in a4;
981   struct sockaddr_in6 a6;
982   const struct IPv4TcpAddress *t4;
983   const struct IPv6TcpAddress *t6;
984   unsigned int is_natd;
985
986   GNUNET_STATISTICS_update (plugin->env->stats,
987                             gettext_noop ("# bytes TCP was asked to transmit"),
988                             msgbuf_size,
989                             GNUNET_NO);
990   /* FIXME: we could do this cheaper with a hash table
991      where we could restrict the iteration to entries that match
992      the target peer... */
993   is_natd = GNUNET_NO;
994   if (session == NULL)
995     {
996       cand_session = NULL;
997       next = plugin->sessions;
998       while (NULL != (session = next))
999         {
1000           next = session->next;
1001           GNUNET_assert (session->client != NULL);
1002           if (0 != memcmp (target,
1003                            &session->target,
1004                            sizeof (struct GNUNET_PeerIdentity)))
1005             continue;
1006           if ( ( (GNUNET_SYSERR == force_address) &&
1007                  (session->expecting_welcome == GNUNET_NO) ) ||
1008                (GNUNET_NO == force_address) )
1009             {
1010               cand_session = select_better_session (cand_session,
1011                                                     session);
1012               continue;
1013             }
1014           if (GNUNET_SYSERR == force_address)
1015             continue;
1016           GNUNET_break (GNUNET_YES == force_address);
1017           if (addr == NULL)
1018             {
1019               GNUNET_break (0);
1020               break;
1021             }
1022           if ( (addrlen != session->connect_alen) && 
1023                (session->is_nat == GNUNET_NO) )
1024             continue;
1025           if ((0 != memcmp (session->connect_addr,
1026                            addr,
1027                            addrlen)) && (session->is_nat == GNUNET_NO))
1028             continue;
1029           cand_session = select_better_session (cand_session,
1030                                                 session);       
1031         }
1032       session = cand_session;
1033     }
1034   if ( (session == NULL) &&
1035        (addr == NULL) )
1036     {
1037 #if DEBUG_TCP
1038       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1039                        "tcp",
1040                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1041                        GNUNET_i2s (target));
1042 #endif
1043       GNUNET_STATISTICS_update (plugin->env->stats,
1044                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1045                                 msgbuf_size,
1046                                 GNUNET_NO);
1047       return -1;
1048     }
1049   if (session == NULL)
1050     {
1051       if (addrlen == sizeof (struct IPv6TcpAddress))
1052         {
1053           t6 = addr;
1054           af = AF_INET6;
1055           memset (&a6, 0, sizeof (a6));
1056 #if HAVE_SOCKADDR_IN_SIN_LEN
1057           a6.sin6_len = sizeof (a6);
1058 #endif
1059           a6.sin6_family = AF_INET6;
1060           a6.sin6_port = t6->t6_port;
1061           if (t6->t6_port == 0)
1062             is_natd = GNUNET_YES;
1063           memcpy (&a6.sin6_addr,
1064                   &t6->ipv6_addr,
1065                   sizeof (struct in6_addr));
1066           sb = &a6;
1067           sbs = sizeof (a6);
1068         }
1069       else if (addrlen == sizeof (struct IPv4TcpAddress))
1070         {
1071           t4 = addr;
1072           af = AF_INET;
1073           memset (&a4, 0, sizeof (a4));
1074 #if HAVE_SOCKADDR_IN_SIN_LEN
1075           a4.sin_len = sizeof (a4);
1076 #endif
1077           a4.sin_family = AF_INET;
1078           a4.sin_port = t4->t4_port;
1079           if (t4->t4_port == 0)
1080             is_natd = GNUNET_YES;
1081           a4.sin_addr.s_addr = t4->ipv4_addr;
1082           sb = &a4;
1083           sbs = sizeof (a4);
1084         }
1085       else
1086         {
1087           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1088                            "tcp",
1089                            _("Address of unexpected length: %u\n"),
1090                            addrlen);
1091           GNUNET_break (0);
1092           return -1;
1093         }
1094
1095       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1096         return -1; /* NAT client only works with IPv4 addresses */
1097       if (0 == plugin->max_connections)
1098         return -1; /* saturated */
1099
1100       if ( (is_natd == GNUNET_YES) &&
1101            (NULL != plugin->nat) &&
1102            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns,
1103                                                                 &target->hashPubKey)) )
1104         {
1105 #if DEBUG_TCP_NAT
1106           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1107                            "tcp",
1108                            _("Found valid IPv4 NAT address (creating session)!\n"));
1109 #endif
1110           session = create_session (plugin,
1111                                     target,
1112                                     NULL, 
1113                                     GNUNET_YES);
1114
1115           /* create new message entry */
1116           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1117           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1118           pm->msg = (const char*) &pm[1];
1119           memcpy (&pm[1], msg, msgbuf_size);
1120           /* FIXME: this memcpy can be up to 7% of our total run-time
1121              (for transport service) */
1122           pm->message_size = msgbuf_size;
1123           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1124           pm->transmit_cont = cont;
1125           pm->transmit_cont_cls = cont_cls;
1126
1127           /* append pm to pending_messages list */
1128           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1129                                              session->pending_messages_tail,
1130                                              session->pending_messages_tail,
1131                                              pm);
1132
1133           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns,
1134                                                           &target->hashPubKey,
1135                                                           session, 
1136                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1137 #if DEBUG_TCP_NAT
1138           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1139                            "tcp",
1140                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1141                            GNUNET_i2s (target),
1142                            GNUNET_a2s (sb, sbs));
1143 #endif
1144           GNUNET_NAT_run_client (plugin->nat, &a4);
1145           return 0;
1146         }
1147       if ( (is_natd == GNUNET_YES) && 
1148            (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, 
1149                                                                  &target->hashPubKey)) )
1150         {
1151           /* Only do one NAT punch attempt per peer identity */
1152           return -1;
1153         }
1154       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1155       if (sa == NULL)
1156         {
1157 #if DEBUG_TCP
1158           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1159                            "tcp",
1160                            "Failed to create connection to `%4s' at `%s'\n",
1161                            GNUNET_i2s (target),
1162                            GNUNET_a2s (sb, sbs));
1163 #endif
1164           GNUNET_STATISTICS_update (plugin->env->stats,
1165                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1166                                     msgbuf_size,
1167                                     GNUNET_NO);
1168           return -1;
1169         }
1170       GNUNET_assert (0 != plugin->max_connections);
1171       plugin->max_connections--;
1172 #if DEBUG_TCP_NAT
1173       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1174                        "tcp",
1175                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1176                        GNUNET_i2s (target),
1177                        GNUNET_a2s (sb, sbs));
1178 #endif
1179       session = create_session (plugin,
1180                                 target,
1181                                 GNUNET_SERVER_connect_socket (plugin->server,
1182                                                               sa), 
1183                                 GNUNET_NO);
1184       session->connect_addr = GNUNET_malloc (addrlen);
1185       memcpy (session->connect_addr,
1186               addr,
1187               addrlen);
1188       session->connect_alen = addrlen;
1189     }
1190   GNUNET_assert (session != NULL);
1191   GNUNET_assert (session->client != NULL);
1192   GNUNET_STATISTICS_update (plugin->env->stats,
1193                             gettext_noop ("# bytes currently in TCP buffers"),
1194                             msgbuf_size,
1195                             GNUNET_NO);
1196   /* create new message entry */
1197   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1198   pm->msg = (const char*) &pm[1];
1199   memcpy (&pm[1], msg, msgbuf_size);
1200   pm->message_size = msgbuf_size;
1201   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1202   pm->transmit_cont = cont;
1203   pm->transmit_cont_cls = cont_cls;
1204
1205   /* append pm to pending_messages list */
1206   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1207                                      session->pending_messages_tail,
1208                                      session->pending_messages_tail,
1209                                      pm);
1210 #if DEBUG_TCP
1211   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1212                    "tcp",
1213                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1214                    msgbuf_size,
1215                    GNUNET_i2s (target));
1216 #endif
1217   process_pending_messages (session);
1218   return msgbuf_size;
1219 }
1220
1221
1222 /**
1223  * Function that can be called to force a disconnect from the
1224  * specified neighbour.  This should also cancel all previously
1225  * scheduled transmissions.  Obviously the transmission may have been
1226  * partially completed already, which is OK.  The plugin is supposed
1227  * to close the connection (if applicable) and no longer call the
1228  * transmit continuation(s).
1229  *
1230  * Finally, plugin MUST NOT call the services's receive function to
1231  * notify the service that the connection to the specified target was
1232  * closed after a getting this call.
1233  *
1234  * @param cls closure
1235  * @param target peer for which the last transmission is
1236  *        to be cancelled
1237  */
1238 static void
1239 tcp_plugin_disconnect (void *cls,
1240                        const struct GNUNET_PeerIdentity *target)
1241 {
1242   struct Plugin *plugin = cls;
1243   struct Session *session;
1244   struct Session *next;
1245   struct PendingMessage *pm;
1246
1247 #if DEBUG_TCP
1248   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1249                    "tcp",
1250                    "Asked to cancel session with `%4s'\n",
1251                    GNUNET_i2s (target));
1252 #endif
1253   next = plugin->sessions;
1254   while (NULL != (session = next))
1255     {
1256       next = session->next;
1257       if (0 != memcmp (target,
1258                        &session->target,
1259                        sizeof (struct GNUNET_PeerIdentity)))
1260         continue;
1261       pm = session->pending_messages_head;
1262       while (pm != NULL)
1263         {
1264           pm->transmit_cont = NULL;
1265           pm->transmit_cont_cls = NULL;
1266           pm = pm->next;
1267         }
1268       GNUNET_STATISTICS_update (session->plugin->env->stats,
1269                                 gettext_noop ("# transport-service disconnect requests for TCP"),
1270                                 1,
1271                                 GNUNET_NO);
1272       disconnect_session (session);
1273     }
1274 }
1275
1276
1277 /**
1278  * Context for address to string conversion.
1279  */
1280 struct PrettyPrinterContext
1281 {
1282   /**
1283    * Function to call with the result.
1284    */
1285   GNUNET_TRANSPORT_AddressStringCallback asc;
1286
1287   /**
1288    * Clsoure for 'asc'.
1289    */
1290   void *asc_cls;
1291
1292   /**
1293    * Port to add after the IP address.
1294    */
1295   uint16_t port;
1296 };
1297
1298
1299 /**
1300  * Append our port and forward the result.
1301  *
1302  * @param cls the 'struct PrettyPrinterContext*'
1303  * @param hostname hostname part of the address
1304  */
1305 static void
1306 append_port (void *cls, const char *hostname)
1307 {
1308   struct PrettyPrinterContext *ppc = cls;
1309   char *ret;
1310
1311   if (hostname == NULL)
1312     {
1313       ppc->asc (ppc->asc_cls, NULL);
1314       GNUNET_free (ppc);
1315       return;
1316     }
1317   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1318   ppc->asc (ppc->asc_cls, ret);
1319   GNUNET_free (ret);
1320 }
1321
1322
1323 /**
1324  * Convert the transports address to a nice, human-readable
1325  * format.
1326  *
1327  * @param cls closure
1328  * @param type name of the transport that generated the address
1329  * @param addr one of the addresses of the host, NULL for the last address
1330  *        the specific address format depends on the transport
1331  * @param addrlen length of the address
1332  * @param numeric should (IP) addresses be displayed in numeric form?
1333  * @param timeout after how long should we give up?
1334  * @param asc function to call on each string
1335  * @param asc_cls closure for asc
1336  */
1337 static void
1338 tcp_plugin_address_pretty_printer (void *cls,
1339                                    const char *type,
1340                                    const void *addr,
1341                                    size_t addrlen,
1342                                    int numeric,
1343                                    struct GNUNET_TIME_Relative timeout,
1344                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1345                                    void *asc_cls)
1346 {
1347   struct PrettyPrinterContext *ppc;
1348   const void *sb;
1349   size_t sbs;
1350   struct sockaddr_in a4;
1351   struct sockaddr_in6 a6;
1352   const struct IPv4TcpAddress *t4;
1353   const struct IPv6TcpAddress *t6;
1354   uint16_t port;
1355
1356   if (addrlen == sizeof (struct IPv6TcpAddress))
1357     {
1358       t6 = addr;
1359       memset (&a6, 0, sizeof (a6));
1360       a6.sin6_family = AF_INET6;
1361       a6.sin6_port = t6->t6_port;
1362       memcpy (&a6.sin6_addr,
1363               &t6->ipv6_addr,
1364               sizeof (struct in6_addr));
1365       port = ntohs (t6->t6_port);
1366       sb = &a6;
1367       sbs = sizeof (a6);
1368     }
1369   else if (addrlen == sizeof (struct IPv4TcpAddress))
1370     {
1371       t4 = addr;
1372       memset (&a4, 0, sizeof (a4));
1373       a4.sin_family = AF_INET;
1374       a4.sin_port = t4->t4_port;
1375       a4.sin_addr.s_addr = t4->ipv4_addr;
1376       port = ntohs (t4->t4_port);
1377       sb = &a4;
1378       sbs = sizeof (a4);
1379     }
1380   else
1381     {
1382       /* invalid address */
1383       GNUNET_break_op (0);
1384       asc (asc_cls, NULL);
1385       return;
1386     }
1387   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1388   ppc->asc = asc;
1389   ppc->asc_cls = asc_cls;
1390   ppc->port = port;
1391   GNUNET_RESOLVER_hostname_get (sb,
1392                                 sbs,
1393                                 !numeric, timeout, &append_port, ppc);
1394 }
1395
1396
1397 /**
1398  * Check if the given port is plausible (must be either our listen
1399  * port or our advertised port), or any port if we are behind NAT
1400  * and do not have a port open.  If it is neither, we return
1401  * GNUNET_SYSERR.
1402  *
1403  * @param plugin global variables
1404  * @param in_port port number to check
1405  * @return GNUNET_OK if port is either open_port or adv_port
1406  */
1407 static int
1408 check_port (struct Plugin *plugin, 
1409             uint16_t in_port)
1410 {
1411   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1412     return GNUNET_OK;
1413   return GNUNET_SYSERR;
1414 }
1415
1416
1417 /**
1418  * Function that will be called to check if a binary address for this
1419  * plugin is well-formed and corresponds to an address for THIS peer
1420  * (as per our configuration).  Naturally, if absolutely necessary,
1421  * plugins can be a bit conservative in their answer, but in general
1422  * plugins should make sure that the address does not redirect
1423  * traffic to a 3rd party that might try to man-in-the-middle our
1424  * traffic.
1425  *
1426  * @param cls closure, our 'struct Plugin*'
1427  * @param addr pointer to the address
1428  * @param addrlen length of addr
1429  * @return GNUNET_OK if this is a plausible address for this peer
1430  *         and transport, GNUNET_SYSERR if not
1431  */
1432 static int
1433 tcp_plugin_check_address (void *cls,
1434                           const void *addr,
1435                           size_t addrlen)
1436 {
1437   struct Plugin *plugin = cls;
1438   struct IPv4TcpAddress *v4;
1439   struct IPv6TcpAddress *v6;
1440
1441   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1442       (addrlen != sizeof (struct IPv6TcpAddress)))
1443     {
1444       GNUNET_break_op (0);
1445       return GNUNET_SYSERR;
1446     }
1447   if (addrlen == sizeof (struct IPv4TcpAddress))
1448     {
1449       v4 = (struct IPv4TcpAddress *) addr;
1450       if (GNUNET_OK !=
1451           check_port (plugin, ntohs (v4->t4_port)))
1452         return GNUNET_SYSERR;
1453       if (GNUNET_OK !=
1454           GNUNET_NAT_test_address (plugin->nat,
1455                                    &v4->ipv4_addr, sizeof (struct in_addr)))
1456         return GNUNET_SYSERR;   
1457     }
1458   else
1459     {
1460       v6 = (struct IPv6TcpAddress *) addr;
1461       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1462         {
1463           GNUNET_break_op (0);
1464           return GNUNET_SYSERR;
1465         }
1466       if (GNUNET_OK !=
1467           check_port (plugin, ntohs (v6->t6_port)))
1468         return GNUNET_SYSERR;
1469       if (GNUNET_OK !=
1470           GNUNET_NAT_test_address (plugin->nat,
1471                                    &v6->ipv6_addr, sizeof (struct in6_addr)))
1472         return GNUNET_SYSERR;
1473     }
1474   return GNUNET_OK;
1475 }
1476
1477
1478 /**
1479  * We've received a nat probe from this peer via TCP.  Finish
1480  * creating the client session and resume sending of queued
1481  * messages.
1482  *
1483  * @param cls closure
1484  * @param client identification of the client
1485  * @param message the actual message
1486  */
1487 static void
1488 handle_tcp_nat_probe (void *cls,
1489                       struct GNUNET_SERVER_Client *client,
1490                       const struct GNUNET_MessageHeader *message)
1491 {
1492   struct Plugin *plugin = cls;
1493   struct Session *session;
1494   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1495   size_t alen;
1496   void *vaddr;
1497   struct IPv4TcpAddress *t4;
1498   struct IPv6TcpAddress *t6;
1499   const struct sockaddr_in *s4;
1500   const struct sockaddr_in6 *s6;
1501
1502 #if DEBUG_TCP_NAT
1503   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1504                    "tcp",
1505                    "received NAT probe\n");
1506 #endif
1507   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1508    * a connection to this peer by running gnunet-nat-client.  This peer
1509    * received the punch message and now wants us to use the new connection
1510    * as the default for that peer.  Do so and then send a WELCOME message
1511    * so we can really be connected!
1512    */
1513   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1514     {
1515       GNUNET_break_op(0);
1516       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1517       return;
1518     }
1519
1520   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *)message;
1521   if (0 == memcmp (&tcp_nat_probe->clientIdentity,
1522                    plugin->env->my_identity,
1523                    sizeof (struct GNUNET_PeerIdentity)))
1524     {
1525       /* refuse connections from ourselves */
1526       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1527       return;
1528     }
1529
1530   session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, 
1531                                               &tcp_nat_probe->clientIdentity.hashPubKey);
1532   if (session == NULL)
1533     {
1534 #if DEBUG_TCP_NAT
1535       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1536                        "tcp",
1537                        "Did NOT find session for NAT probe!\n");
1538 #endif
1539       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1540       return;
1541     }
1542 #if DEBUG_TCP_NAT
1543   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1544                    "tcp",
1545                    "Found session for NAT probe!\n");
1546 #endif
1547   GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, 
1548                                                      &tcp_nat_probe->clientIdentity.hashPubKey,
1549                                                      session) == GNUNET_YES);
1550   if (GNUNET_OK !=
1551       GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1552     {
1553       GNUNET_break (0);
1554       GNUNET_free (session);
1555       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1556       return;
1557     }
1558
1559   GNUNET_SERVER_client_keep (client);
1560   session->client = client;
1561   session->last_activity = GNUNET_TIME_absolute_get ();
1562   session->inbound = GNUNET_NO;
1563
1564 #if DEBUG_TCP_NAT
1565   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1566                    "tcp",
1567                    "Found address `%s' for incoming connection\n",
1568                    GNUNET_a2s (vaddr, alen));
1569 #endif
1570   switch (((const struct sockaddr *)vaddr)->sa_family)
1571     {
1572     case AF_INET:
1573       s4 = vaddr;
1574       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1575       t4->t4_port = s4->sin_port;
1576       t4->ipv4_addr = s4->sin_addr.s_addr;
1577       session->connect_addr = t4;
1578       session->connect_alen = sizeof (struct IPv4TcpAddress);
1579       break;
1580     case AF_INET6:    
1581       s6 = vaddr;
1582       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1583       t6->t6_port = s6->sin6_port;
1584       memcpy (&t6->ipv6_addr,
1585               &s6->sin6_addr,
1586               sizeof (struct in6_addr));
1587       session->connect_addr = t6;
1588       session->connect_alen = sizeof (struct IPv6TcpAddress);
1589       break;
1590     default:
1591       GNUNET_break_op (0);
1592 #if DEBUG_TCP_NAT
1593       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1594                        "tcp",
1595                        "Bad address for incoming connection!\n");
1596 #endif
1597       GNUNET_free (vaddr);
1598       GNUNET_SERVER_client_drop (client);
1599       GNUNET_free (session);
1600       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1601       return;
1602     }
1603   GNUNET_free (vaddr);
1604   
1605   session->next = plugin->sessions;
1606   plugin->sessions = session;
1607   GNUNET_STATISTICS_update (plugin->env->stats,
1608                             gettext_noop ("# TCP sessions active"),
1609                             1,
1610                             GNUNET_NO);
1611   process_pending_messages (session);
1612   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1613 }
1614
1615
1616 /**
1617  * We've received a welcome from this peer via TCP.  Possibly create a
1618  * fresh client record and send back our welcome.
1619  *
1620  * @param cls closure
1621  * @param client identification of the client
1622  * @param message the actual message
1623  */
1624 static void
1625 handle_tcp_welcome (void *cls,
1626                     struct GNUNET_SERVER_Client *client,
1627                     const struct GNUNET_MessageHeader *message)
1628 {
1629   struct Plugin *plugin = cls;
1630   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1631   struct Session *session;
1632   size_t alen;
1633   void *vaddr;
1634   struct IPv4TcpAddress *t4;
1635   struct IPv6TcpAddress *t6;
1636   const struct sockaddr_in *s4;
1637   const struct sockaddr_in6 *s6;
1638   
1639   if (0 == memcmp (&wm->clientIdentity,
1640                    plugin->env->my_identity,
1641                    sizeof (struct GNUNET_PeerIdentity)))
1642     {
1643       /* refuse connections from ourselves */
1644       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1645       return;
1646     }
1647 #if DEBUG_TCP
1648   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1649                    "tcp",
1650                    "Received %s message from `%4s'.\n",
1651                    "WELCOME",
1652                    GNUNET_i2s (&wm->clientIdentity));
1653 #endif
1654   GNUNET_STATISTICS_update (plugin->env->stats,
1655                             gettext_noop ("# TCP WELCOME messages received"),
1656                             1,
1657                             GNUNET_NO);
1658   session = find_session_by_client (plugin, client);
1659
1660   if (session == NULL)
1661     {
1662 #if DEBUG_TCP_NAT
1663       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1664                        "tcp",
1665                        "Received %s message from a `%4s', creating new session\n",
1666                        "WELCOME",
1667                        GNUNET_i2s (&wm->clientIdentity));
1668 #endif
1669       GNUNET_SERVER_client_keep (client);
1670       session = create_session (plugin,
1671                                 &wm->clientIdentity,
1672                                 client,
1673                                 GNUNET_NO);
1674       session->inbound = GNUNET_YES;
1675       if (GNUNET_OK ==
1676           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1677         {
1678 #if DEBUG_TCP_NAT
1679           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1680                            "tcp",
1681                            "Found address `%s' for incoming connection\n",
1682                            GNUNET_a2s (vaddr, alen));
1683 #endif
1684           if (alen == sizeof (struct sockaddr_in))
1685             {
1686               s4 = vaddr;
1687               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1688               t4->t4_port = s4->sin_port;
1689               t4->ipv4_addr = s4->sin_addr.s_addr;
1690               session->connect_addr = t4;
1691               session->connect_alen = sizeof (struct IPv4TcpAddress);
1692             }
1693           else if (alen == sizeof (struct sockaddr_in6))
1694             {
1695               s6 = vaddr;
1696               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1697               t6->t6_port = s6->sin6_port;
1698               memcpy (&t6->ipv6_addr,
1699                       &s6->sin6_addr,
1700                       sizeof (struct in6_addr));
1701               session->connect_addr = t6;
1702               session->connect_alen = sizeof (struct IPv6TcpAddress);
1703             }
1704
1705           GNUNET_free (vaddr);
1706         }
1707       else
1708         {
1709 #if DEBUG_TCP
1710           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1711                            "tcp",
1712                            "Did not obtain TCP socket address for incoming connection\n");
1713 #endif
1714         }
1715       process_pending_messages (session);
1716     }
1717   else
1718     {
1719 #if DEBUG_TCP_NAT
1720     if (GNUNET_OK ==
1721         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1722       {
1723         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1724                          "tcp",
1725                          "Found address `%s' (already have session)\n",
1726                          GNUNET_a2s (vaddr, alen));
1727         GNUNET_free (vaddr);
1728       }
1729 #endif
1730     }
1731
1732   if (session->expecting_welcome != GNUNET_YES)
1733     {
1734       GNUNET_break_op (0);
1735       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1736       return;
1737     }
1738   session->last_activity = GNUNET_TIME_absolute_get ();
1739   session->expecting_welcome = GNUNET_NO;
1740   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1741 }
1742
1743
1744 /**
1745  * Task to signal the server that we can continue
1746  * receiving from the TCP client now.
1747  *
1748  * @param cls the 'struct Session*'
1749  * @param tc task context (unused)
1750  */
1751 static void
1752 delayed_done (void *cls, 
1753               const struct GNUNET_SCHEDULER_TaskContext *tc)
1754 {
1755   struct Session *session = cls;
1756   struct GNUNET_TIME_Relative delay;
1757
1758   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1759   delay = session->plugin->env->receive (session->plugin->env->cls,
1760                                          &session->target,
1761                                          NULL,
1762                                          NULL, 0,
1763                                          session,
1764                                          NULL, 0);
1765   if (delay.rel_value == 0)
1766     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1767   else
1768     session->receive_delay_task =
1769       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1770 }
1771
1772
1773 /**
1774  * We've received data for this peer via TCP.  Unbox,
1775  * compute latency and forward.
1776  *
1777  * @param cls closure
1778  * @param client identification of the client
1779  * @param message the actual message
1780  */
1781 static void
1782 handle_tcp_data (void *cls,
1783                  struct GNUNET_SERVER_Client *client,
1784                  const struct GNUNET_MessageHeader *message)
1785 {
1786   struct Plugin *plugin = cls;
1787   struct Session *session;
1788   struct GNUNET_TIME_Relative delay;
1789   uint16_t type;
1790
1791   type = ntohs (message->type);
1792   if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) || 
1793        (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
1794     {
1795       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1796       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1797       return;
1798     }
1799   session = find_session_by_client (plugin, client);
1800   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome) )
1801     {
1802       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1803       return;
1804     }
1805   session->last_activity = GNUNET_TIME_absolute_get ();
1806 #if DEBUG_TCP > 1
1807   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1808                    "tcp",
1809                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1810                    (unsigned int) ntohs (message->size),
1811                    (unsigned int) ntohs (message->type),
1812                    GNUNET_i2s (&session->target));
1813 #endif
1814   GNUNET_STATISTICS_update (plugin->env->stats,
1815                             gettext_noop ("# bytes received via TCP"),
1816                             ntohs (message->size),
1817                             GNUNET_NO);
1818   struct GNUNET_TRANSPORT_ATS_Information distance[2];
1819   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
1820   distance[0].value = htonl (1);
1821   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
1822   distance[1].value = htonl (0);
1823   delay = plugin->env->receive (plugin->env->cls, &session->target, message,
1824                                 (const struct GNUNET_TRANSPORT_ATS_Information *) &distance,
1825                                 2,
1826                                 session,
1827                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1828                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1829   if (delay.rel_value == 0)
1830     {
1831       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1832     }
1833   else
1834     {
1835 #if DEBUG_TCP 
1836       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1837                        "tcp",
1838                        "Throttling receiving from `%s' for %llu ms\n",
1839                        GNUNET_i2s (&session->target),
1840                        (unsigned long long) delay.rel_value);
1841 #endif
1842       GNUNET_SERVER_disable_receive_done_warning (client);
1843       session->receive_delay_task =
1844         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1845     }
1846 }
1847
1848
1849 /**
1850  * Functions with this signature are called whenever a peer
1851  * is disconnected on the network level.
1852  *
1853  * @param cls closure
1854  * @param client identification of the client
1855  */
1856 static void
1857 disconnect_notify (void *cls,
1858                    struct GNUNET_SERVER_Client *client)
1859 {
1860   struct Plugin *plugin = cls;
1861   struct Session *session;
1862
1863   if (client == NULL)
1864     return;
1865   plugin->max_connections++;
1866   session = find_session_by_client (plugin, client);
1867   if (session == NULL)
1868     return;                     /* unknown, nothing to do */
1869 #if DEBUG_TCP
1870   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1871                    "tcp",
1872                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
1873                    GNUNET_i2s (&session->target),
1874                    (session->connect_addr != NULL) ?
1875                    tcp_address_to_string (session->plugin,
1876                                           session->connect_addr,
1877                                           session->connect_alen) : "*");
1878 #endif
1879   GNUNET_STATISTICS_update (session->plugin->env->stats,
1880                             gettext_noop ("# network-level TCP disconnect events"),
1881                             1,
1882                             GNUNET_NO);
1883   disconnect_session (session);
1884 }
1885
1886
1887 /**
1888  * We can now send a probe message, copy into buffer to really send.
1889  *
1890  * @param cls closure, a struct TCPProbeContext
1891  * @param size max size to copy
1892  * @param buf buffer to copy message to
1893  * @return number of bytes copied into buf
1894  */
1895 static size_t
1896 notify_send_probe (void *cls,
1897                    size_t size,
1898                    void *buf)
1899 {
1900   struct TCPProbeContext *tcp_probe_ctx = cls;
1901   struct Plugin *plugin = tcp_probe_ctx->plugin;
1902   size_t ret;
1903
1904   tcp_probe_ctx->transmit_handle = NULL;
1905   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
1906                                plugin->probe_tail,
1907                                tcp_probe_ctx);
1908   if (buf == NULL)
1909     {
1910       GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
1911       GNUNET_free(tcp_probe_ctx);
1912       return 0;    
1913     }
1914   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1915   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1916   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1917                                 tcp_probe_ctx->sock);
1918   ret = sizeof(tcp_probe_ctx->message);
1919   GNUNET_free(tcp_probe_ctx);
1920   return ret;
1921 }
1922
1923
1924 /**
1925  * Function called by the NAT subsystem suggesting another peer wants
1926  * to connect to us via connection reversal.  Try to connect back to the
1927  * given IP.
1928  *
1929  * @param cls closure
1930  * @param addr address to try
1931  * @param addrlen number of bytes in addr
1932  */
1933 static void
1934 try_connection_reversal (void *cls,
1935                          const struct sockaddr *addr,
1936                          socklen_t addrlen)
1937 {
1938   struct Plugin *plugin = cls;
1939   struct GNUNET_CONNECTION_Handle *sock;
1940   struct TCPProbeContext *tcp_probe_ctx;
1941
1942   /**
1943    * We have received an ICMP response, ostensibly from a peer
1944    * that wants to connect to us! Send a message to establish a connection.
1945    */
1946   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, 
1947                                                  addr,
1948                                                  addrlen);
1949   if (sock == NULL)
1950     {
1951       /* failed for some odd reason (out of sockets?); ignore attempt */
1952       return;
1953     }
1954
1955   /* FIXME: do we need to track these probe context objects so that
1956      we can clean them up on plugin unload? */
1957   tcp_probe_ctx
1958     = GNUNET_malloc(sizeof(struct TCPProbeContext));
1959   tcp_probe_ctx->message.header.size
1960     = htons(sizeof(struct TCP_NAT_ProbeMessage));
1961   tcp_probe_ctx->message.header.type
1962     = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
1963   memcpy (&tcp_probe_ctx->message.clientIdentity,
1964           plugin->env->my_identity,
1965           sizeof(struct GNUNET_PeerIdentity));
1966   tcp_probe_ctx->plugin = plugin;
1967   tcp_probe_ctx->sock = sock;
1968   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
1969                                plugin->probe_tail,
1970                                tcp_probe_ctx);
1971   tcp_probe_ctx->transmit_handle 
1972     = GNUNET_CONNECTION_notify_transmit_ready (sock,
1973                                                ntohs (tcp_probe_ctx->message.header.size),
1974                                                GNUNET_TIME_UNIT_FOREVER_REL,
1975                                                &notify_send_probe, tcp_probe_ctx);
1976   
1977 }
1978
1979
1980 /**
1981  * Entry point for the plugin.
1982  *
1983  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1984  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1985  */
1986 void *
1987 libgnunet_plugin_transport_tcp_init (void *cls)
1988 {
1989   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1990     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1991      sizeof (struct WelcomeMessage)},
1992     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
1993     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1994     {NULL, NULL, 0, 0}
1995   };
1996   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1997   struct GNUNET_TRANSPORT_PluginFunctions *api;
1998   struct Plugin *plugin;
1999   struct GNUNET_SERVICE_Context *service;
2000   unsigned long long aport;
2001   unsigned long long bport;
2002   unsigned long long max_connections;
2003   unsigned int i;
2004   struct GNUNET_TIME_Relative idle_timeout;
2005   int ret;
2006   struct sockaddr **addrs;
2007   socklen_t *addrlens;
2008
2009   if (GNUNET_OK !=
2010       GNUNET_CONFIGURATION_get_value_number (env->cfg,
2011                                              "transport-tcp",
2012                                              "MAX_CONNECTIONS",
2013                                              &max_connections))
2014     max_connections = 128;
2015   
2016   aport = 0;
2017   if ( (GNUNET_OK !=
2018         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2019                                                "transport-tcp",
2020                                                "PORT",
2021                                                &bport)) ||
2022        (bport > 65535) ||
2023        ((GNUNET_OK ==
2024          GNUNET_CONFIGURATION_get_value_number (env->cfg,
2025                                                 "transport-tcp",
2026                                                 "ADVERTISED-PORT",
2027                                                 &aport)) && 
2028         (aport > 65535)) )
2029     {
2030       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2031                        "tcp",
2032                        _("Require valid port number for service `%s' in configuration!\n"),
2033                        "transport-tcp");
2034       return NULL;
2035     } 
2036   if (aport == 0)
2037     aport = bport;
2038   if (bport == 0)
2039     aport = 0;
2040   if (bport != 0)
2041     {
2042       service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);      
2043       if (service == NULL)
2044         {
2045           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2046                            "tcp",
2047                            _("Failed to start service.\n"));
2048           return NULL;
2049         }
2050     }
2051   else
2052     service = NULL;
2053
2054
2055
2056   plugin = GNUNET_malloc (sizeof (struct Plugin));
2057   plugin->max_connections = max_connections;
2058   plugin->open_port = bport;
2059   plugin->adv_port = aport;
2060   plugin->env = env;
2061   plugin->lsock = NULL;
2062   if ( (service != NULL) &&
2063        (GNUNET_SYSERR !=
2064         (ret = GNUNET_SERVICE_get_server_addresses ("transport-tcp",
2065                                                     env->cfg,
2066                                                     &addrs,
2067                                                     &addrlens))) )
2068     {
2069       plugin->nat = GNUNET_NAT_register (env->cfg,
2070                                          GNUNET_YES,
2071                                          aport,
2072                                          (unsigned int) ret,
2073                                          (const struct sockaddr **) addrs,
2074                                          addrlens,
2075                                          &tcp_nat_port_map_callback,
2076                                          &try_connection_reversal,
2077                                          plugin);
2078       while (ret > 0)
2079         GNUNET_free (addrs[--ret]);
2080       GNUNET_free_non_null (addrs);
2081       GNUNET_free_non_null (addrlens);
2082     }
2083   else
2084     {
2085       plugin->nat = GNUNET_NAT_register (env->cfg,
2086                                          GNUNET_YES,
2087                                          0,
2088                                          0, NULL, NULL,
2089                                          NULL,
2090                                          &try_connection_reversal,
2091                                          plugin);
2092     }
2093   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2094   api->cls = plugin;
2095   api->send = &tcp_plugin_send;
2096   api->disconnect = &tcp_plugin_disconnect;
2097   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2098   api->check_address = &tcp_plugin_check_address;
2099   api->address_to_string = &tcp_address_to_string;
2100   plugin->service = service;
2101   if (service != NULL)   
2102     {
2103       plugin->server = GNUNET_SERVICE_get_server (service);
2104     }
2105   else
2106     {
2107       if (GNUNET_OK !=
2108           GNUNET_CONFIGURATION_get_value_time (env->cfg,
2109                                                "transport-tcp",
2110                                                "TIMEOUT",
2111                                                &idle_timeout))
2112         {
2113           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2114                            "tcp",
2115                            _("Failed to find option %s in section %s!\n"),
2116                            "TIMEOUT",
2117                            "transport-tcp");
2118           if (plugin->nat != NULL)
2119             GNUNET_NAT_unregister (plugin->nat);
2120           GNUNET_free (plugin);
2121           GNUNET_free (api);
2122           return NULL;
2123         }
2124       plugin->server = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin, NULL,
2125                                                           idle_timeout, GNUNET_YES);
2126     }
2127   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2128   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2129   for (i = 0;
2130        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2131        i++)
2132     plugin->handlers[i].callback_cls = plugin;
2133   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2134   GNUNET_SERVER_disconnect_notify (plugin->server,
2135                                    &disconnect_notify,
2136                                    plugin);    
2137   plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(16);
2138   if (bport != 0)
2139     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
2140                      "tcp",
2141                      _("TCP transport listening on port %llu\n"), 
2142                      bport);
2143   else
2144     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
2145                      "tcp",
2146                      _("TCP transport not listening on any port (client only)\n"));
2147   if (aport != bport)
2148     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2149                      "tcp",
2150                      _("TCP transport advertises itself as being on port %llu\n"),
2151                      aport);
2152   return api;
2153 }
2154
2155
2156 /**
2157  * Exit point from the plugin.
2158  */
2159 void *
2160 libgnunet_plugin_transport_tcp_done (void *cls)
2161 {
2162   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2163   struct Plugin *plugin = api->cls;
2164   struct Session *session;
2165   struct TCPProbeContext *tcp_probe;
2166
2167   while (NULL != (session = plugin->sessions))
2168     disconnect_session (session);
2169   if (plugin->service != NULL)
2170     GNUNET_SERVICE_stop (plugin->service);
2171   else
2172     GNUNET_SERVER_destroy (plugin->server);
2173   GNUNET_free (plugin->handlers);
2174   if (plugin->nat != NULL)
2175     GNUNET_NAT_unregister (plugin->nat);
2176   while (NULL != (tcp_probe = plugin->probe_head))
2177     {
2178       GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2179                                    plugin->probe_tail,
2180                                    tcp_probe);
2181       GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
2182       GNUNET_free (tcp_probe);
2183     }
2184   GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2185   GNUNET_free (plugin);
2186   GNUNET_free (api);
2187   return NULL;
2188 }
2189
2190 /* end of plugin_transport_tcp.c */