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