-more logging, etc.
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002--2013 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 LOG(kind,...) GNUNET_log_from (kind, "transport-tcp",__VA_ARGS__)
43
44 #define PLUGIN_NAME "tcp"
45
46 /**
47  * How long until we give up on establishing an NAT connection?
48  * Must be > 4 RTT
49  */
50 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
51
52
53 GNUNET_NETWORK_STRUCT_BEGIN
54
55 /**
56  * Address options
57  */
58 static uint32_t myoptions;
59
60 /**
61  * Initial handshake message for a session.
62  */
63 struct WelcomeMessage
64 {
65   /**
66    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
67    */
68   struct GNUNET_MessageHeader header;
69
70   /**
71    * Identity of the node connecting (TCP client)
72    */
73   struct GNUNET_PeerIdentity clientIdentity;
74
75 };
76
77
78 /**
79  * Basically a WELCOME message, but with the purpose
80  * of giving the waiting peer a client handle to use
81  */
82 struct TCP_NAT_ProbeMessage
83 {
84   /**
85    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
86    */
87   struct GNUNET_MessageHeader header;
88
89   /**
90    * Identity of the sender of the message.
91    */
92   struct GNUNET_PeerIdentity clientIdentity;
93
94 };
95 GNUNET_NETWORK_STRUCT_END
96
97 /**
98  * Context for sending a NAT probe via TCP.
99  */
100 struct TCPProbeContext
101 {
102
103   /**
104    * Active probes are kept in a DLL.
105    */
106   struct TCPProbeContext *next;
107
108   /**
109    * Active probes are kept in a DLL.
110    */
111   struct TCPProbeContext *prev;
112
113   /**
114    * Probe connection.
115    */
116   struct GNUNET_CONNECTION_Handle *sock;
117
118   /**
119    * Message to be sent.
120    */
121   struct TCP_NAT_ProbeMessage message;
122
123   /**
124    * Handle to the transmission.
125    */
126   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
127
128   /**
129    * Transport plugin handle.
130    */
131   struct Plugin *plugin;
132 };
133
134
135 GNUNET_NETWORK_STRUCT_BEGIN
136
137 /**
138  * Network format for IPv4 addresses.
139  */
140 struct IPv4TcpAddress
141 {
142   /**
143    * Optional options and flags for this address
144    */
145   uint32_t options;
146
147   /**
148    * IPv4 address, in network byte order.
149    */
150   uint32_t ipv4_addr GNUNET_PACKED;
151
152   /**
153    * Port number, in network byte order.
154    */
155   uint16_t t4_port GNUNET_PACKED;
156
157 };
158
159
160 /**
161  * Network format for IPv6 addresses.
162  */
163 struct IPv6TcpAddress
164 {
165   /**
166    * Optional flags for this address
167    */
168   uint32_t options;
169
170   /**
171    * IPv6 address.
172    */
173   struct in6_addr ipv6_addr GNUNET_PACKED;
174
175   /**
176    * Port number, in network byte order.
177    */
178   uint16_t t6_port GNUNET_PACKED;
179
180 };
181 GNUNET_NETWORK_STRUCT_END
182
183 /**
184  * Encapsulation of all of the state of the plugin.
185  */
186 struct Plugin;
187
188
189 /**
190  * Information kept for each message that is yet to
191  * be transmitted.
192  */
193 struct PendingMessage
194 {
195
196   /**
197    * This is a doubly-linked list.
198    */
199   struct PendingMessage *next;
200
201   /**
202    * This is a doubly-linked list.
203    */
204   struct PendingMessage *prev;
205
206   /**
207    * The pending message
208    */
209   const char *msg;
210
211   /**
212    * Continuation function to call once the message
213    * has been sent.  Can be NULL if there is no
214    * continuation to call.
215    */
216   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
217
218   /**
219    * Closure for transmit_cont.
220    */
221   void *transmit_cont_cls;
222
223   /**
224    * Timeout value for the pending message.
225    */
226   struct GNUNET_TIME_Absolute timeout;
227
228   /**
229    * So that the gnunet-service-transport can group messages together,
230    * these pending messages need to accept a message buffer and size
231    * instead of just a GNUNET_MessageHeader.
232    */
233   size_t message_size;
234
235 };
236
237
238 /**
239  * Session handle for TCP connections.
240  */
241 struct Session
242 {
243   /**
244    * To whom are we talking to (set to our identity
245    * if we are still waiting for the welcome message)
246    */
247   struct GNUNET_PeerIdentity target;
248
249   /**
250    * API requirement.
251    */
252   struct SessionHeader header;
253
254   /**
255    * Pointer to the global plugin struct.
256    */
257   struct Plugin *plugin;
258
259   /**
260    * The client (used to identify this connection)
261    */
262   struct GNUNET_SERVER_Client *client;
263
264   /**
265    * Task cleaning up a NAT client connection establishment attempt;
266    */
267   GNUNET_SCHEDULER_TaskIdentifier nat_connection_timeout;
268
269   /**
270    * Messages currently pending for transmission
271    * to this peer, if any.
272    */
273   struct PendingMessage *pending_messages_head;
274
275   /**
276    * Messages currently pending for transmission
277    * to this peer, if any.
278    */
279   struct PendingMessage *pending_messages_tail;
280
281   /**
282    * Handle for pending transmission request.
283    */
284   struct GNUNET_SERVER_TransmitHandle *transmit_handle;
285
286   /**
287    * ID of task used to delay receiving more to throttle sender.
288    */
289   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
290
291   /**
292    * Session timeout task
293    */
294   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
295
296   /**
297    * Address of the other peer (either based on our 'connect'
298    * call or on our 'accept' call).
299    *
300    * struct IPv4TcpAddress or struct IPv6TcpAddress
301    *
302    */
303   void *addr;
304
305   /**
306    * Length of connect_addr.
307    */
308   size_t addrlen;
309
310   /**
311    * Last activity on this connection.  Used to select preferred
312    * connection.
313    */
314   struct GNUNET_TIME_Absolute last_activity;
315
316   /**
317    * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
318    */
319   int expecting_welcome;
320
321   /**
322    * Was this a connection that was inbound (we accepted)? (#GNUNET_YES/#GNUNET_NO)
323    */
324   int inbound;
325
326   /**
327    * Was this session created using NAT traversal?
328    */
329   int is_nat;
330
331   /**
332    * ATS network type in NBO
333    */
334   uint32_t ats_address_network_type;
335 };
336
337
338 /**
339  * Encapsulation of all of the state of the plugin.
340  */
341 struct Plugin
342 {
343   /**
344    * Our environment.
345    */
346   struct GNUNET_TRANSPORT_PluginEnvironment *env;
347
348   /**
349    * The listen socket.
350    */
351   struct GNUNET_CONNECTION_Handle *lsock;
352
353   /**
354    * Our handle to the NAT module.
355    */
356   struct GNUNET_NAT_Handle *nat;
357
358   /**
359    * Map from peer identities to sessions for the given peer.
360    */
361   struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
362
363   /**
364    * Handle to the network service.
365    */
366   struct GNUNET_SERVICE_Context *service;
367
368   /**
369    * Handle to the server for this service.
370    */
371   struct GNUNET_SERVER_Handle *server;
372
373   /**
374    * Copy of the handler array where the closures are
375    * set to this struct's instance.
376    */
377   struct GNUNET_SERVER_MessageHandler *handlers;
378
379   /**
380    * Map of peers we have tried to contact behind a NAT
381    */
382   struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
383
384   /**
385    * List of active TCP probes.
386    */
387   struct TCPProbeContext *probe_head;
388
389   /**
390    * List of active TCP probes.
391    */
392   struct TCPProbeContext *probe_tail;
393
394   /**
395    * Handle for (DYN)DNS lookup of our external IP.
396    */
397   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
398
399   /**
400    * How many more TCP sessions are we allowed to open right now?
401    */
402   unsigned long long max_connections;
403
404   /**
405    * How many more TCP sessions do we have right now?
406    */
407   unsigned long long cur_connections;
408
409   /**
410    * ID of task used to update our addresses when one expires.
411    */
412   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
413
414   /**
415    * Port that we are actually listening on.
416    */
417   uint16_t open_port;
418
419   /**
420    * Port that the user said we would have visible to the
421    * rest of the world.
422    */
423   uint16_t adv_port;
424
425 };
426
427
428 /**
429  * Start session timeout
430  */
431 static void
432 start_session_timeout (struct Session *s);
433
434
435 /**
436  * Increment session timeout due to activity
437  */
438 static void
439 reschedule_session_timeout (struct Session *s);
440
441
442 /**
443  * Cancel timeout
444  *
445  * @param s session to cancel timeout for
446  */
447 static void
448 stop_session_timeout (struct Session *s);
449
450
451 /* DEBUG CODE */
452 static const char *
453 tcp_address_to_string (void *cls, const void *addr, size_t addrlen);
454
455
456 static unsigned int sessions;
457
458
459 static void
460 inc_sessions (struct Plugin *plugin, struct Session *session, int line)
461 {
462   sessions++;
463   unsigned int size = GNUNET_CONTAINER_multipeermap_size (plugin->sessionmap);
464   if (sessions != size)
465     LOG (GNUNET_ERROR_TYPE_DEBUG,
466          "Inconsistent sessions %u <-> session map size: %u\n",
467          sessions, size);
468   LOG (GNUNET_ERROR_TYPE_DEBUG,
469        "%4i Session increased to %u (session map size: %u): `%s' `%s'\n",
470        line,
471        sessions,
472        size,
473        GNUNET_i2s (&session->target),
474        tcp_address_to_string (NULL, session->addr, session->addrlen));
475 }
476
477
478 static void
479 dec_sessions (struct Plugin *plugin,
480               struct Session *session, int line)
481 {
482   GNUNET_assert (sessions > 0);
483   unsigned int size = GNUNET_CONTAINER_multipeermap_size(plugin->sessionmap);
484   sessions--;
485   if (sessions != size)
486     LOG (GNUNET_ERROR_TYPE_DEBUG,
487          "Inconsistent sessions %u <-> session map size: %u\n",
488          sessions, size);
489   LOG (GNUNET_ERROR_TYPE_DEBUG,
490        "%4i Session decreased to %u (session map size: %u): `%s' `%s'\n",
491        line,
492        sessions,
493        size,
494        GNUNET_i2s (&session->target),
495        tcp_address_to_string (NULL, session->addr, session->addrlen));
496 }
497 /* DEBUG CODE */
498
499
500 /**
501  * Function to check if an inbound connection is acceptable.
502  * Mostly used to limit the total number of open connections
503  * we can have.
504  *
505  * @param cls the 'struct Plugin'
506  * @param ucred credentials, if available, otherwise NULL
507  * @param addr address
508  * @param addrlen length of address
509  * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
510  *   for unknown address family (will be denied).
511  */
512 static int
513 plugin_tcp_access_check (void *cls,
514                          const struct GNUNET_CONNECTION_Credentials *ucred,
515                          const struct sockaddr *addr, socklen_t addrlen)
516 {
517   struct Plugin *plugin = cls;
518   LOG (GNUNET_ERROR_TYPE_DEBUG,
519        "Accepting new incoming TCP connection from `%s'\n",
520        GNUNET_a2s (addr, addrlen));
521   if (plugin->cur_connections >= plugin->max_connections)
522     return GNUNET_NO;
523   plugin->cur_connections ++;
524   return GNUNET_YES;
525 }
526
527
528 /**
529  * Our external IP address/port mapping has changed.
530  *
531  * @param cls closure, the 'struct LocalAddrList'
532  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
533  *     the previous (now invalid) one
534  * @param addr either the previous or the new public IP address
535  * @param addrlen actual lenght of the address
536  */
537 static void
538 tcp_nat_port_map_callback (void *cls, int add_remove,
539                            const struct sockaddr *addr, socklen_t addrlen)
540 {
541   struct Plugin *plugin = cls;
542   struct IPv4TcpAddress t4;
543   struct IPv6TcpAddress t6;
544   void *arg;
545   size_t args;
546
547   LOG (GNUNET_ERROR_TYPE_INFO,
548        "NAT notification to %s address `%s'\n",
549        (GNUNET_YES == add_remove) ? "add" : "remove",
550        GNUNET_a2s (addr, addrlen));
551   /* convert 'addr' to our internal format */
552   switch (addr->sa_family)
553   {
554   case AF_INET:
555     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
556     memset (&t4,0, sizeof (t4));
557     t4.options = htonl (myoptions);
558     t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
559     t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
560     arg = &t4;
561     args = sizeof (t4);
562     break;
563   case AF_INET6:
564     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
565     memset (&t6, 0, sizeof (t6));
566     memcpy (&t6.ipv6_addr, &((struct sockaddr_in6 *) addr)->sin6_addr,
567             sizeof (struct in6_addr));
568     t6.options = htonl (myoptions);
569     t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
570     arg = &t6;
571     args = sizeof (t6);
572     break;
573   default:
574     GNUNET_break (0);
575     return;
576   }
577   /* modify our published address list */
578   plugin->env->notify_address (plugin->env->cls, add_remove, arg, args, "tcp");
579 }
580
581
582 /**
583  * Function called for a quick conversion of the binary address to
584  * a numeric address.  Note that the caller must not free the
585  * address and that the next call to this function is allowed
586  * to override the address again.
587  *
588  * @param cls closure ('struct Plugin*')
589  * @param addr binary address
590  * @param addrlen length of the address
591  * @return string representing the same address
592  */
593 static const char *
594 tcp_address_to_string (void *cls, const void *addr, size_t addrlen)
595 {
596   static char rbuf[INET6_ADDRSTRLEN + 12];
597   char buf[INET6_ADDRSTRLEN];
598   const void *sb;
599   struct in_addr a4;
600   struct in6_addr a6;
601   const struct IPv4TcpAddress *t4;
602   const struct IPv6TcpAddress *t6;
603   int af;
604   uint16_t port;
605   uint32_t options;
606
607   switch (addrlen)
608   {
609   case sizeof (struct IPv6TcpAddress):
610     t6 = addr;
611     af = AF_INET6;
612     port = ntohs (t6->t6_port);
613     options = ntohl (t6->options);
614     memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
615     sb = &a6;
616     break;
617   case sizeof (struct IPv4TcpAddress):
618     t4 = addr;
619     af = AF_INET;
620     port = ntohs (t4->t4_port);
621     options = ntohl (t4->options);
622     memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
623     sb = &a4;
624     break;
625   case 0:
626     {
627       GNUNET_snprintf (rbuf, sizeof (rbuf), "%s",
628                 TRANSPORT_SESSION_INBOUND_STRING);
629       return rbuf;
630     }
631   default:
632     LOG (GNUNET_ERROR_TYPE_WARNING,
633                 _("Unexpected address length: %u bytes\n"),
634                 (unsigned int) addrlen);
635     return NULL;
636   }
637   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
638   {
639     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
640     return NULL;
641   }
642   GNUNET_snprintf (rbuf, sizeof (rbuf), (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
643                    PLUGIN_NAME, options, buf, port);
644   return rbuf;
645 }
646
647
648 /**
649  * Function called to convert a string address to
650  * a binary address.
651  *
652  * @param cls closure ('struct Plugin*')
653  * @param addr string address
654  * @param addrlen length of the address
655  * @param buf location to store the buffer
656  * @param added location to store the number of bytes in the buffer.
657  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
658  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
659  */
660 static int
661 tcp_string_to_address (void *cls,
662                        const char *addr,
663                        uint16_t addrlen,
664                        void **buf, size_t *added)
665 {
666   struct sockaddr_storage socket_address;
667   char *address;
668   char *plugin;
669   char *optionstr;
670   uint32_t options;
671
672   /* Format tcp.options.address:port */
673   address = NULL;
674   plugin = NULL;
675   optionstr = NULL;
676   if ((NULL == addr) || (addrlen == 0))
677   {
678     GNUNET_break (0);
679     return GNUNET_SYSERR;
680   }
681   if ('\0' != addr[addrlen - 1])
682   {
683     GNUNET_break (0);
684     return GNUNET_SYSERR;
685   }
686   if (strlen (addr) != addrlen - 1)
687   {
688     GNUNET_break (0);
689     return GNUNET_SYSERR;
690   }
691   plugin = GNUNET_strdup (addr);
692   optionstr = strchr (plugin, '.');
693   if (NULL == optionstr)
694   {
695     GNUNET_break (0);
696     GNUNET_free (plugin);
697     return GNUNET_SYSERR;
698   }
699   optionstr[0] = '\0';
700   optionstr ++;
701   options = atol (optionstr);
702   address = strchr (optionstr, '.');
703   if (NULL == address)
704   {
705     GNUNET_break (0);
706     GNUNET_free (plugin);
707     return GNUNET_SYSERR;
708   }
709   address[0] = '\0';
710   address ++;
711
712   if (GNUNET_OK !=
713       GNUNET_STRINGS_to_address_ip (address, strlen (address),
714                                     &socket_address))
715   {
716     GNUNET_break (0);
717     GNUNET_free (plugin);
718     return GNUNET_SYSERR;
719   }
720
721   GNUNET_free (plugin);
722   switch (socket_address.ss_family)
723   {
724   case AF_INET:
725     {
726       struct IPv4TcpAddress *t4;
727       struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
728       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
729       t4->options =  htonl (options);
730       t4->ipv4_addr = in4->sin_addr.s_addr;
731       t4->t4_port = in4->sin_port;
732       *buf = t4;
733       *added = sizeof (struct IPv4TcpAddress);
734       return GNUNET_OK;
735     }
736   case AF_INET6:
737     {
738       struct IPv6TcpAddress *t6;
739       struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
740       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
741       t6->options = htonl (options);
742       t6->ipv6_addr = in6->sin6_addr;
743       t6->t6_port = in6->sin6_port;
744       *buf = t6;
745       *added = sizeof (struct IPv6TcpAddress);
746       return GNUNET_OK;
747     }
748   default:
749     return GNUNET_SYSERR;
750   }
751 }
752
753
754 struct SessionClientCtx
755 {
756   const struct GNUNET_SERVER_Client *client;
757   struct Session *ret;
758 };
759
760
761 static int
762 session_lookup_by_client_it (void *cls,
763                              const struct GNUNET_PeerIdentity *key,
764                              void *value)
765 {
766   struct SessionClientCtx *sc_ctx = cls;
767   struct Session *s = value;
768
769   if (s->client == sc_ctx->client)
770   {
771     sc_ctx->ret = s;
772     return GNUNET_NO;
773   }
774   return GNUNET_YES;
775 }
776
777
778 /**
779  * Find the session handle for the given client.
780  *
781  * @param plugin the plugin
782  * @param client which client to find the session handle for
783  * @return NULL if no matching session exists
784  */
785 static struct Session *
786 lookup_session_by_client (struct Plugin *plugin,
787                           const struct GNUNET_SERVER_Client *client)
788 {
789   struct SessionClientCtx sc_ctx;
790
791   sc_ctx.client = client;
792   sc_ctx.ret = NULL;
793   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_lookup_by_client_it, &sc_ctx);
794   return sc_ctx.ret;
795 }
796
797
798 /**
799  * Create a new session.  Also queues a welcome message.
800  *
801  * @param plugin the plugin
802  * @param target peer to connect to
803  * @param client client to use, reference counter must have already been increased
804  * @param is_nat this a NAT session, we should wait for a client to
805  *               connect to us from an address, then assign that to
806  *               the session
807  * @return new session object
808  */
809 static struct Session *
810 create_session (struct Plugin *plugin, const struct GNUNET_PeerIdentity *target,
811                 struct GNUNET_SERVER_Client *client, int is_nat)
812 {
813   struct Session *session;
814   struct PendingMessage *pm;
815   struct WelcomeMessage welcome;
816
817   if (GNUNET_YES != is_nat)
818     GNUNET_assert (NULL != client);
819   else
820     GNUNET_assert (NULL == client);
821
822   LOG (GNUNET_ERROR_TYPE_DEBUG,
823        "Creating new session for peer `%4s'\n",
824        GNUNET_i2s (target));
825   session = GNUNET_malloc (sizeof (struct Session));
826   session->last_activity = GNUNET_TIME_absolute_get ();
827   session->plugin = plugin;
828   session->is_nat = is_nat;
829   session->client = client;
830   session->target = *target;
831   session->expecting_welcome = GNUNET_YES;
832   session->ats_address_network_type = htonl (GNUNET_ATS_NET_UNSPECIFIED);
833   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
834                       sizeof (struct WelcomeMessage));
835   pm->msg = (const char *) &pm[1];
836   pm->message_size = sizeof (struct WelcomeMessage);
837   welcome.header.size = htons (sizeof (struct WelcomeMessage));
838   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
839   welcome.clientIdentity = *plugin->env->my_identity;
840   memcpy (&pm[1], &welcome, sizeof (welcome));
841   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
842   GNUNET_STATISTICS_update (plugin->env->stats,
843                             gettext_noop ("# bytes currently in TCP buffers"),
844                             pm->message_size, GNUNET_NO);
845   GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
846                                session->pending_messages_tail, pm);
847   if (GNUNET_YES != is_nat)
848   {
849     GNUNET_STATISTICS_update (plugin->env->stats,
850                               gettext_noop ("# TCP sessions active"), 1,
851                               GNUNET_NO);
852   }
853   start_session_timeout (session);
854
855   return session;
856 }
857
858
859 /**
860  * If we have pending messages, ask the server to
861  * transmit them (schedule the respective tasks, etc.)
862  *
863  * @param session for which session should we do this
864  */
865 static void
866 process_pending_messages (struct Session *session);
867
868
869 /**
870  * Function called to notify a client about the socket
871  * being ready to queue more data.  "buf" will be
872  * NULL and "size" zero if the socket was closed for
873  * writing in the meantime.
874  *
875  * @param cls closure
876  * @param size number of bytes available in buf
877  * @param buf where the callee should write the message
878  * @return number of bytes written to buf
879  */
880 static size_t
881 do_transmit (void *cls, size_t size, void *buf)
882 {
883   struct Session *session = cls;
884   struct GNUNET_PeerIdentity pid;
885   struct Plugin *plugin;
886   struct PendingMessage *pos;
887   struct PendingMessage *hd;
888   struct PendingMessage *tl;
889   struct GNUNET_TIME_Absolute now;
890   char *cbuf;
891   size_t ret;
892
893   GNUNET_assert (NULL != session);
894   session->transmit_handle = NULL;
895   plugin = session->plugin;
896   if (NULL == buf)
897   {
898     LOG (GNUNET_ERROR_TYPE_DEBUG,
899          "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
900          GNUNET_i2s (&session->target));
901     /* timeout; cancel all messages that have already expired */
902     hd = NULL;
903     tl = NULL;
904     ret = 0;
905     now = GNUNET_TIME_absolute_get ();
906     while ((NULL != (pos = session->pending_messages_head)) &&
907            (pos->timeout.abs_value_us <= now.abs_value_us))
908     {
909       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
910                                    session->pending_messages_tail, pos);
911       LOG (GNUNET_ERROR_TYPE_DEBUG,
912            "Failed to transmit %u byte message to `%4s'.\n",
913            pos->message_size, GNUNET_i2s (&session->target));
914       ret += pos->message_size;
915       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
916     }
917     /* do this call before callbacks (so that if callbacks destroy
918      * session, they have a chance to cancel actions done by this
919      * call) */
920     process_pending_messages (session);
921     pid = session->target;
922     /* no do callbacks and do not use session again since
923      * the callbacks may abort the session */
924     while (NULL != (pos = hd))
925     {
926       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
927       if (pos->transmit_cont != NULL)
928         pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_SYSERR, pos->message_size, 0);
929       GNUNET_free (pos);
930     }
931     GNUNET_STATISTICS_update (plugin->env->stats,
932                               gettext_noop ("# bytes currently in TCP buffers"),
933                               -(int64_t) ret, GNUNET_NO);
934     GNUNET_STATISTICS_update (plugin->env->stats,
935                               gettext_noop
936                               ("# bytes discarded by TCP (timeout)"), ret,
937                               GNUNET_NO);
938     return 0;
939   }
940   /* copy all pending messages that would fit */
941   ret = 0;
942   cbuf = buf;
943   hd = NULL;
944   tl = NULL;
945   while (NULL != (pos = session->pending_messages_head))
946   {
947     if (ret + pos->message_size > size)
948       break;
949     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
950                                  session->pending_messages_tail, pos);
951     GNUNET_assert (size >= pos->message_size);
952     LOG (GNUNET_ERROR_TYPE_DEBUG,
953          "Transmitting message of type %u\n",
954          ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type));
955     /* FIXME: this memcpy can be up to 7% of our total runtime */
956     memcpy (cbuf, pos->msg, pos->message_size);
957     cbuf += pos->message_size;
958     ret += pos->message_size;
959     size -= pos->message_size;
960     GNUNET_CONTAINER_DLL_insert_tail (hd, tl, pos);
961   }
962   /* schedule 'continuation' before callbacks so that callbacks that
963    * cancel everything don't cause us to use a session that no longer
964    * exists... */
965   process_pending_messages (session);
966   session->last_activity = GNUNET_TIME_absolute_get ();
967   pid = session->target;
968   /* we'll now call callbacks that may cancel the session; hence
969    * we should not use 'session' after this point */
970   while (NULL != (pos = hd))
971   {
972     GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
973     if (pos->transmit_cont != NULL)
974       pos->transmit_cont (pos->transmit_cont_cls, &pid, GNUNET_OK, pos->message_size, pos->message_size); /* FIXME: include TCP overhead */
975     GNUNET_free (pos);
976   }
977   GNUNET_assert (hd == NULL);
978   GNUNET_assert (tl == NULL);
979   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes\n",
980                    ret);
981   GNUNET_STATISTICS_update (plugin->env->stats,
982                             gettext_noop ("# bytes currently in TCP buffers"),
983                             -(int64_t) ret, GNUNET_NO);
984   GNUNET_STATISTICS_update (plugin->env->stats,
985                             gettext_noop ("# bytes transmitted via TCP"), ret,
986                             GNUNET_NO);
987   return ret;
988 }
989
990
991 /**
992  * If we have pending messages, ask the server to
993  * transmit them (schedule the respective tasks, etc.)
994  *
995  * @param session for which session should we do this
996  */
997 static void
998 process_pending_messages (struct Session *session)
999 {
1000   struct PendingMessage *pm;
1001
1002   GNUNET_assert (session->client != NULL);
1003   if (session->transmit_handle != NULL)
1004     return;
1005   if (NULL == (pm = session->pending_messages_head))
1006     return;
1007
1008   session->transmit_handle =
1009       GNUNET_SERVER_notify_transmit_ready (session->client, pm->message_size,
1010                                            GNUNET_TIME_absolute_get_remaining
1011                                            (pm->timeout), &do_transmit,
1012                                            session);
1013 }
1014
1015
1016 /**
1017  * Functions with this signature are called whenever we need
1018  * to close a session due to a disconnect or failure to
1019  * establish a connection.
1020  *
1021  * @param session session to close down
1022  */
1023 static void
1024 disconnect_session (struct Session *session)
1025 {
1026   struct PendingMessage *pm;
1027   struct Plugin * plugin = session->plugin;
1028
1029   LOG (GNUNET_ERROR_TYPE_DEBUG,
1030        "Disconnecting session of peer `%s' address `%s'\n",
1031        GNUNET_i2s (&session->target),
1032        tcp_address_to_string (NULL, session->addr, session->addrlen));
1033
1034   stop_session_timeout (session);
1035
1036   if (GNUNET_YES ==
1037       GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
1038                                             &session->target,
1039                                             session))
1040   {
1041     GNUNET_STATISTICS_update (session->plugin->env->stats,
1042                               gettext_noop ("# TCP sessions active"), -1,
1043                               GNUNET_NO);
1044     dec_sessions (plugin, session, __LINE__);
1045   }
1046   else
1047   {
1048     GNUNET_assert (GNUNET_YES ==
1049                    GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
1050                                                          &session->target,
1051                                                          session));
1052   }
1053   /* clean up state */
1054   if (NULL != session->transmit_handle)
1055   {
1056     GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
1057     session->transmit_handle = NULL;
1058   }
1059   session->plugin->env->session_end (session->plugin->env->cls,
1060                                      &session->target, session);
1061
1062   if (GNUNET_SCHEDULER_NO_TASK != session->nat_connection_timeout)
1063   {
1064     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1065     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1066   }
1067
1068   while (NULL != (pm = session->pending_messages_head))
1069   {
1070     LOG (GNUNET_ERROR_TYPE_DEBUG,
1071          pm->transmit_cont !=
1072          NULL ? "Could not deliver message to `%4s'.\n" :
1073          "Could not deliver message to `%4s', notifying.\n",
1074          GNUNET_i2s (&session->target));
1075     GNUNET_STATISTICS_update (session->plugin->env->stats,
1076                               gettext_noop ("# bytes currently in TCP buffers"),
1077                               -(int64_t) pm->message_size, GNUNET_NO);
1078     GNUNET_STATISTICS_update (session->plugin->env->stats,
1079                               gettext_noop
1080                               ("# bytes discarded by TCP (disconnect)"),
1081                               pm->message_size, GNUNET_NO);
1082     GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1083                                  session->pending_messages_tail, pm);
1084     if (NULL != pm->transmit_cont)
1085       pm->transmit_cont (pm->transmit_cont_cls, &session->target,
1086                          GNUNET_SYSERR, pm->message_size, 0);
1087     GNUNET_free (pm);
1088   }
1089   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
1090   {
1091     GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1092     if (NULL != session->client)
1093       GNUNET_SERVER_receive_done (session->client, GNUNET_SYSERR);
1094   }
1095   if (NULL != session->client)
1096   {
1097     GNUNET_SERVER_client_disconnect (session->client);
1098     GNUNET_SERVER_client_drop (session->client);
1099     session->client = NULL;
1100   }
1101   GNUNET_free_non_null (session->addr);
1102   GNUNET_assert (NULL == session->transmit_handle);
1103   GNUNET_free (session);
1104 }
1105
1106
1107 struct FindSessionContext
1108 {
1109   struct Session *s;
1110   int res;
1111 };
1112
1113
1114 static int
1115 session_it (void *cls,
1116             const struct GNUNET_PeerIdentity * key,
1117             void *value)
1118 {
1119   struct FindSessionContext *res = cls;
1120
1121   if (res->s == value)
1122   {
1123     res->res = GNUNET_OK;
1124     return GNUNET_NO;
1125   }
1126   return GNUNET_YES;
1127 }
1128
1129
1130 static int
1131 find_session (struct Plugin *plugin, struct Session *session)
1132 {
1133   struct FindSessionContext session_map_res;
1134   struct FindSessionContext nat_map_res;
1135
1136   session_map_res.s = session;
1137   session_map_res.res = GNUNET_SYSERR;
1138   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap, &session_it, &session_map_res);
1139
1140   nat_map_res.s = session;
1141   nat_map_res.res = GNUNET_SYSERR;
1142   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns, &session_it, &nat_map_res);
1143
1144   if ((session_map_res.res == GNUNET_SYSERR) && (nat_map_res.res == GNUNET_SYSERR))
1145   {
1146     GNUNET_break (0);
1147     return GNUNET_SYSERR;
1148   }
1149   return GNUNET_OK;
1150 }
1151
1152
1153 /**
1154  * Function that can be used by the transport service to transmit
1155  * a message using the plugin.   Note that in the case of a
1156  * peer disconnecting, the continuation MUST be called
1157  * prior to the disconnect notification itself.  This function
1158  * will be called with this peer's HELLO message to initiate
1159  * a fresh connection to another peer.
1160  *
1161  * @param cls closure
1162  * @param session which session must be used
1163  * @param msgbuf the message to transmit
1164  * @param msgbuf_size number of bytes in 'msgbuf'
1165  * @param priority how important is the message (most plugins will
1166  *                 ignore message priority and just FIFO)
1167  * @param to how long to wait at most for the transmission (does not
1168  *                require plugins to discard the message after the timeout,
1169  *                just advisory for the desired delay; most plugins will ignore
1170  *                this as well)
1171  * @param cont continuation to call once the message has
1172  *        been transmitted (or if the transport is ready
1173  *        for the next transmission call; or if the
1174  *        peer disconnected...); can be NULL
1175  * @param cont_cls closure for cont
1176  * @return number of bytes used (on the physical network, with overheads);
1177  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1178  *         and does NOT mean that the message was not transmitted (DV)
1179  */
1180 static ssize_t
1181 tcp_plugin_send (void *cls,
1182     struct Session *session,
1183     const char *msgbuf, size_t msgbuf_size,
1184     unsigned int priority,
1185     struct GNUNET_TIME_Relative to,
1186     GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1187 {
1188   struct Plugin * plugin = cls;
1189   struct PendingMessage *pm;
1190
1191   GNUNET_assert (NULL != plugin);
1192   GNUNET_assert (NULL != session);
1193
1194   if (GNUNET_SYSERR == find_session(plugin, session))
1195   {
1196       LOG (GNUNET_ERROR_TYPE_ERROR,
1197            _("Trying to send with invalid session %p\n"));
1198       return GNUNET_SYSERR;
1199   }
1200
1201   /* create new message entry */
1202   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1203   pm->msg = (const char *) &pm[1];
1204   memcpy (&pm[1], msgbuf, msgbuf_size);
1205   pm->message_size = msgbuf_size;
1206   pm->timeout = GNUNET_TIME_relative_to_absolute (to);
1207   pm->transmit_cont = cont;
1208   pm->transmit_cont_cls = cont_cls;
1209
1210   LOG (GNUNET_ERROR_TYPE_DEBUG,
1211        "Asked to transmit %u bytes to `%s', added message to list.\n",
1212        msgbuf_size, GNUNET_i2s (&session->target));
1213
1214   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
1215                                                                   &session->target,
1216                                                                   session))
1217   {
1218     GNUNET_assert (session->client != NULL);
1219     reschedule_session_timeout (session);
1220     GNUNET_SERVER_client_set_timeout (session->client,
1221                                       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1222     GNUNET_STATISTICS_update (plugin->env->stats,
1223                               gettext_noop ("# bytes currently in TCP buffers"),
1224                               msgbuf_size, GNUNET_NO);
1225
1226     /* append pm to pending_messages list */
1227     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1228                                       session->pending_messages_tail, pm);
1229
1230     process_pending_messages (session);
1231     return msgbuf_size;
1232   }
1233   else if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains_value(plugin->nat_wait_conns, &session->target, session))
1234   {
1235     LOG (GNUNET_ERROR_TYPE_DEBUG,
1236          "This NAT WAIT session for peer `%s' is not yet ready!\n",
1237          GNUNET_i2s (&session->target));
1238     reschedule_session_timeout (session);
1239     GNUNET_STATISTICS_update (plugin->env->stats,
1240                               gettext_noop ("# bytes currently in TCP buffers"),
1241                               msgbuf_size, GNUNET_NO);
1242
1243     /* append pm to pending_messages list */
1244     GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
1245                                       session->pending_messages_tail, pm);
1246     return msgbuf_size;
1247   }
1248   else
1249   {
1250     LOG (GNUNET_ERROR_TYPE_ERROR,
1251          "Invalid session %p\n", session);
1252     if (NULL != cont)
1253       cont (cont_cls, &session->target, GNUNET_SYSERR, pm->message_size, 0);
1254     GNUNET_break (0);
1255     GNUNET_free (pm);
1256     return GNUNET_SYSERR; /* session does not exist here */
1257   }
1258 }
1259
1260
1261 struct SessionItCtx
1262 {
1263   void *addr;
1264   size_t addrlen;
1265   struct Session *result;
1266 };
1267
1268
1269 static int
1270 session_lookup_it (void *cls,
1271                    const struct GNUNET_PeerIdentity *key,
1272                    void *value)
1273 {
1274   struct SessionItCtx * si_ctx = cls;
1275   struct Session * session = value;
1276 #if 0
1277   char * a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1278   char * a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1279   LOG (GNUNET_ERROR_TYPE_DEBUG,
1280        "Comparing: %s %u <-> %s %u\n",
1281        a1,
1282        session->addrlen,
1283        a2,
1284        si_ctx->addrlen);
1285   GNUNET_free (a1);
1286   GNUNET_free (a2);
1287 #endif
1288   if (session->addrlen != si_ctx->addrlen)
1289   {
1290     return GNUNET_YES;
1291   }
1292   if (0 != memcmp (session->addr, si_ctx->addr, si_ctx->addrlen))
1293   {
1294     return GNUNET_YES;
1295   }
1296 #if 0
1297   a1 = strdup (tcp_address_to_string(NULL, session->addr, session->addrlen));
1298   a2 = strdup (tcp_address_to_string(NULL, si_ctx->addr, si_ctx->addrlen));
1299   LOG (GNUNET_ERROR_TYPE_DEBUG,
1300        "Comparing: %s %u <-> %s %u , OK!\n",
1301        a1,
1302        session->addrlen,
1303        a2,
1304        si_ctx->addrlen);
1305   GNUNET_free (a1);
1306   GNUNET_free (a2);
1307 #endif
1308   /* Found existing session */
1309   si_ctx->result = session;
1310   return GNUNET_NO;
1311 }
1312
1313
1314 /**
1315  * Task cleaning up a NAT connection attempt after timeout
1316  */
1317 static void
1318 nat_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1319 {
1320   struct Session *session = cls;
1321
1322   session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1323   LOG (GNUNET_ERROR_TYPE_DEBUG,
1324        "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
1325        GNUNET_i2s (&session->target), tcp_address_to_string(NULL, session->addr, session->addrlen));
1326   disconnect_session (session);
1327 }
1328
1329
1330 /**
1331  * Create a new session to transmit data to the target
1332  * This session will used to send data to this peer and the plugin will
1333  * notify us by calling the env->session_end function
1334  *
1335  * @param cls closure
1336  * @param address pointer to the GNUNET_HELLO_Address
1337  * @return the session if the address is valid, NULL otherwise
1338  */
1339 static struct Session *
1340 tcp_plugin_get_session (void *cls,
1341                         const struct GNUNET_HELLO_Address *address)
1342 {
1343   struct Plugin *plugin = cls;
1344   struct Session *session = NULL;
1345   int af;
1346   const void *sb;
1347   size_t sbs;
1348   struct GNUNET_CONNECTION_Handle *sa;
1349   struct sockaddr_in a4;
1350   struct sockaddr_in6 a6;
1351   const struct IPv4TcpAddress *t4;
1352   const struct IPv6TcpAddress *t6;
1353   struct GNUNET_ATS_Information ats;
1354   unsigned int is_natd = GNUNET_NO;
1355   size_t addrlen;
1356
1357   GNUNET_assert (plugin != NULL);
1358   GNUNET_assert (address != NULL);
1359   addrlen = address->address_length;
1360   LOG (GNUNET_ERROR_TYPE_DEBUG,
1361        "Trying to get session for `%s' address of peer `%s'\n",
1362        tcp_address_to_string(NULL, address->address, address->address_length),
1363        GNUNET_i2s (&address->peer));
1364
1365   /* look for existing session */
1366   if (GNUNET_YES ==
1367       GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
1368                                               &address->peer))
1369   {
1370     struct SessionItCtx si_ctx;
1371
1372     si_ctx.addr = (void *) address->address;
1373     si_ctx.addrlen = address->address_length;
1374
1375     si_ctx.result = NULL;
1376
1377     GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
1378                                                 &address->peer,
1379                                                 &session_lookup_it, &si_ctx);
1380     if (si_ctx.result != NULL)
1381     {
1382       session = si_ctx.result;
1383       LOG (GNUNET_ERROR_TYPE_DEBUG,
1384            "Found existing session for `%s' address `%s' session %p\n",
1385            GNUNET_i2s (&address->peer),
1386            tcp_address_to_string(NULL, address->address, address->address_length),
1387            session);
1388       return session;
1389     }
1390     LOG (GNUNET_ERROR_TYPE_DEBUG,
1391          "Existing sessions did not match address `%s' or peer `%s'\n",
1392          tcp_address_to_string(NULL, address->address, address->address_length),
1393          GNUNET_i2s (&address->peer));
1394   }
1395
1396   if (addrlen == sizeof (struct IPv6TcpAddress))
1397   {
1398     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1399     t6 = address->address;
1400     af = AF_INET6;
1401     memset (&a6, 0, sizeof (a6));
1402 #if HAVE_SOCKADDR_IN_SIN_LEN
1403     a6.sin6_len = sizeof (a6);
1404 #endif
1405     a6.sin6_family = AF_INET6;
1406     a6.sin6_port = t6->t6_port;
1407     if (t6->t6_port == 0)
1408       is_natd = GNUNET_YES;
1409     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1410     sb = &a6;
1411     sbs = sizeof (a6);
1412   }
1413   else if (addrlen == sizeof (struct IPv4TcpAddress))
1414   {
1415     GNUNET_assert (NULL != address->address);     /* make static analysis happy */
1416     t4 = address->address;
1417     af = AF_INET;
1418     memset (&a4, 0, sizeof (a4));
1419 #if HAVE_SOCKADDR_IN_SIN_LEN
1420     a4.sin_len = sizeof (a4);
1421 #endif
1422     a4.sin_family = AF_INET;
1423     a4.sin_port = t4->t4_port;
1424     if (t4->t4_port == 0)
1425       is_natd = GNUNET_YES;
1426     a4.sin_addr.s_addr = t4->ipv4_addr;
1427     sb = &a4;
1428     sbs = sizeof (a4);
1429   }
1430   else
1431   {
1432     GNUNET_STATISTICS_update (plugin->env->stats,
1433                               gettext_noop
1434                               ("# requests to create session with invalid address"),
1435                               1, GNUNET_NO);
1436     return NULL;
1437   }
1438
1439   ats = plugin->env->get_address_type (plugin->env->cls, sb ,sbs);
1440
1441   if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1442   {
1443     /* NAT client only works with IPv4 addresses */
1444     return NULL;
1445   }
1446
1447   if (plugin->cur_connections >= plugin->max_connections)
1448   {
1449     /* saturated */
1450     return NULL;
1451   }
1452
1453   if ((is_natd == GNUNET_YES) &&
1454       (GNUNET_YES ==
1455        GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1456                                                &address->peer)))
1457   {
1458     /* Only do one NAT punch attempt per peer identity */
1459      return NULL;
1460   }
1461
1462   if ((is_natd == GNUNET_YES) && (NULL != plugin->nat) &&
1463       (GNUNET_NO ==
1464        GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
1465                                                &address->peer)))
1466   {
1467     LOG (GNUNET_ERROR_TYPE_DEBUG,
1468          "Found valid IPv4 NAT address (creating session)!\n") ;
1469     session = create_session (plugin, &address->peer, NULL, GNUNET_YES);
1470     session->addrlen = 0;
1471     session->addr = NULL;
1472     session->ats_address_network_type = ats.value;
1473     session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
1474                                                                     &nat_connect_timeout,
1475                                                                     session);
1476     GNUNET_assert (session != NULL);
1477     GNUNET_assert (GNUNET_OK ==
1478                    GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
1479                                                       &session->target,
1480                                                       session,
1481                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1482
1483     LOG (GNUNET_ERROR_TYPE_DEBUG,
1484          "Created NAT WAIT connection to `%4s' at `%s'\n",
1485          GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1486
1487     if (GNUNET_OK == GNUNET_NAT_run_client (plugin->nat, &a4))
1488       return session;
1489     else
1490     {
1491       LOG (GNUNET_ERROR_TYPE_DEBUG,
1492            "Running NAT client for `%4s' at `%s' failed\n",
1493            GNUNET_i2s (&session->target), GNUNET_a2s (sb, sbs));
1494       disconnect_session (session);
1495       return NULL;
1496     }
1497   }
1498
1499   /* create new outbound session */
1500   GNUNET_assert (plugin->cur_connections <= plugin->max_connections);
1501   sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1502   if (sa == NULL)
1503   {
1504     LOG (GNUNET_ERROR_TYPE_DEBUG,
1505          "Failed to create connection to `%4s' at `%s'\n",
1506          GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1507     return NULL;
1508   }
1509   plugin->cur_connections++;
1510   if (plugin->cur_connections == plugin->max_connections)
1511         GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
1512
1513   LOG (GNUNET_ERROR_TYPE_DEBUG,
1514        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1515        GNUNET_i2s (&address->peer), GNUNET_a2s (sb, sbs));
1516
1517   session = create_session (plugin,
1518                             &address->peer,
1519                             GNUNET_SERVER_connect_socket (plugin->server, sa),
1520                             GNUNET_NO);
1521   session->addr = GNUNET_malloc (addrlen);
1522   memcpy (session->addr, address->address, addrlen);
1523   session->addrlen = addrlen;
1524   session->ats_address_network_type = ats.value;
1525
1526   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
1527                                      &session->target,
1528                                      session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1529   inc_sessions (plugin, session, __LINE__);
1530   LOG (GNUNET_ERROR_TYPE_DEBUG,
1531        "Creating new session for `%s' address `%s' session %p\n",
1532        GNUNET_i2s (&address->peer),
1533        tcp_address_to_string(NULL, address->address, address->address_length),
1534        session);
1535   /* Send TCP Welcome */
1536   process_pending_messages (session);
1537
1538   return session;
1539 }
1540
1541
1542 static int
1543 session_disconnect_it (void *cls,
1544                        const struct GNUNET_PeerIdentity *key,
1545                        void *value)
1546 {
1547   struct Session *session = value;
1548
1549   GNUNET_STATISTICS_update (session->plugin->env->stats,
1550                             gettext_noop
1551                             ("# transport-service disconnect requests for TCP"),
1552                             1, GNUNET_NO);
1553   disconnect_session (session);
1554   return GNUNET_YES;
1555 }
1556
1557
1558 /**
1559  * Function that can be called to force a disconnect from the
1560  * specified neighbour.  This should also cancel all previously
1561  * scheduled transmissions.  Obviously the transmission may have been
1562  * partially completed already, which is OK.  The plugin is supposed
1563  * to close the connection (if applicable) and no longer call the
1564  * transmit continuation(s).
1565  *
1566  * Finally, plugin MUST NOT call the services's receive function to
1567  * notify the service that the connection to the specified target was
1568  * closed after a getting this call.
1569  *
1570  * @param cls closure
1571  * @param target peer for which the last transmission is
1572  *        to be cancelled
1573  */
1574 static void
1575 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1576 {
1577   struct Plugin *plugin = cls;
1578
1579   LOG (GNUNET_ERROR_TYPE_DEBUG,
1580        "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1581   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap, target,
1582                                               &session_disconnect_it, plugin);
1583   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns, target,
1584                                               &session_disconnect_it, plugin);
1585 }
1586
1587
1588 /**
1589  * Running pretty printers: head
1590  */
1591 static struct PrettyPrinterContext *ppc_dll_head;
1592
1593 /**
1594  * Running pretty printers: tail
1595  */
1596 static struct PrettyPrinterContext *ppc_dll_tail;
1597
1598 /**
1599  * Context for address to string conversion.
1600  */
1601 struct PrettyPrinterContext
1602 {
1603         /**
1604          * DLL
1605          */
1606         struct PrettyPrinterContext *next;
1607
1608         /**
1609          * DLL
1610          */
1611         struct PrettyPrinterContext *prev;
1612
1613         /**
1614          * Timeout task
1615          */
1616         GNUNET_SCHEDULER_TaskIdentifier timeout_task;
1617
1618         /**
1619          * Resolver handle
1620          */
1621         struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
1622
1623   /**
1624    * Function to call with the result.
1625    */
1626   GNUNET_TRANSPORT_AddressStringCallback asc;
1627
1628   /**
1629    * Clsoure for 'asc'.
1630    */
1631   void *asc_cls;
1632
1633   /**
1634    * Port to add after the IP address.
1635    */
1636   uint16_t port;
1637
1638   /**
1639    * IPv6 address
1640    */
1641   int ipv6;
1642
1643   /**
1644    * Options
1645    */
1646   uint32_t options;
1647 };
1648
1649
1650 static void
1651 ppc_cancel_task (void *cls,
1652                  const struct GNUNET_SCHEDULER_TaskContext *tc)
1653 {
1654   int count = 0;
1655   struct PrettyPrinterContext *ppc = cls;
1656   struct PrettyPrinterContext *cur;
1657
1658   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1659   {
1660     if (cur != ppc)
1661       count++;
1662   }
1663
1664   // GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cancel request %p, %u pending\n", ppc, count);
1665   ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1666   if (NULL != ppc->resolver_handle)
1667   {
1668     GNUNET_RESOLVER_request_cancel (ppc->resolver_handle);
1669     ppc->resolver_handle = NULL;
1670   }
1671   GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1672   GNUNET_free (ppc);
1673 }
1674
1675
1676 /**
1677  * Append our port and forward the result.
1678  *
1679  * @param cls the 'struct PrettyPrinterContext*'
1680  * @param hostname hostname part of the address
1681  */
1682 static void
1683 append_port (void *cls, const char *hostname)
1684 {
1685   struct PrettyPrinterContext *ppc = cls;
1686   struct PrettyPrinterContext *cur;
1687   char *ret;
1688   int count = 0;
1689
1690   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1691   {
1692     if (cur != ppc)
1693       count++;
1694   }
1695   //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Callback request %p == %s, %u pending\n", ppc, hostname, count);
1696   if (hostname == NULL)
1697   {
1698     ppc->asc (ppc->asc_cls, NULL);
1699     GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, ppc);
1700     GNUNET_SCHEDULER_cancel (ppc->timeout_task);
1701     ppc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1702     ppc->resolver_handle = NULL;
1703     //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Done request %p, %u pending\n", ppc, count);
1704     GNUNET_free (ppc);
1705     return;
1706   }
1707   for (cur = ppc_dll_head; (NULL != cur); cur = cur->next)
1708   {
1709         if (cur == ppc)
1710                 break;
1711   }
1712   if (NULL == cur)
1713   {
1714         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid callback for PPC %p \n", ppc);
1715         return;
1716   }
1717
1718   if (GNUNET_YES == ppc->ipv6)
1719     GNUNET_asprintf (&ret, "%s.%u.[%s]:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1720   else
1721     GNUNET_asprintf (&ret, "%s.%u.%s:%d", PLUGIN_NAME, ppc->options, hostname, ppc->port);
1722   ppc->asc (ppc->asc_cls, ret);
1723   GNUNET_free (ret);
1724 }
1725
1726
1727 /**
1728  * Convert the transports address to a nice, human-readable
1729  * format.
1730  *
1731  * @param cls closure
1732  * @param type name of the transport that generated the address
1733  * @param addr one of the addresses of the host, NULL for the last address
1734  *        the specific address format depends on the transport
1735  * @param addrlen length of the address
1736  * @param numeric should (IP) addresses be displayed in numeric form?
1737  * @param timeout after how long should we give up?
1738  * @param asc function to call on each string
1739  * @param asc_cls closure for asc
1740  */
1741 static void
1742 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1743                                    const void *addr, size_t addrlen,
1744                                    int numeric,
1745                                    struct GNUNET_TIME_Relative timeout,
1746                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1747                                    void *asc_cls)
1748 {
1749   struct PrettyPrinterContext *ppc;
1750   const void *sb;
1751   size_t sbs;
1752   struct sockaddr_in a4;
1753   struct sockaddr_in6 a6;
1754   const struct IPv4TcpAddress *t4;
1755   const struct IPv6TcpAddress *t6;
1756   uint16_t port;
1757   uint32_t options;
1758
1759   if (addrlen == sizeof (struct IPv6TcpAddress))
1760   {
1761     t6 = addr;
1762     memset (&a6, 0, sizeof (a6));
1763     a6.sin6_family = AF_INET6;
1764     a6.sin6_port = t6->t6_port;
1765     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1766     port = ntohs (t6->t6_port);
1767     options = ntohl (t6->options);
1768     sb = &a6;
1769     sbs = sizeof (a6);
1770   }
1771   else if (addrlen == sizeof (struct IPv4TcpAddress))
1772   {
1773     t4 = addr;
1774     memset (&a4, 0, sizeof (a4));
1775     a4.sin_family = AF_INET;
1776     a4.sin_port = t4->t4_port;
1777     a4.sin_addr.s_addr = t4->ipv4_addr;
1778     port = ntohs (t4->t4_port);
1779     options = ntohl (t4->options);
1780     sb = &a4;
1781     sbs = sizeof (a4);
1782   }
1783   else if (0 == addrlen)
1784   {
1785     asc (asc_cls, TRANSPORT_SESSION_INBOUND_STRING);
1786     asc (asc_cls, NULL);
1787     return;
1788   }
1789   else
1790   {
1791     /* invalid address */
1792     GNUNET_break_op (0);
1793     asc (asc_cls, NULL);
1794     return;
1795   }
1796   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1797   if (addrlen == sizeof (struct IPv6TcpAddress))
1798     ppc->ipv6 = GNUNET_YES;
1799   else
1800     ppc->ipv6 = GNUNET_NO;
1801   ppc->asc = asc;
1802   ppc->asc_cls = asc_cls;
1803   ppc->port = port;
1804   ppc->options = options;
1805   ppc->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(timeout, 2),
1806                                                     &ppc_cancel_task, ppc);
1807   ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric,
1808                                                        timeout,
1809                                                        &append_port, ppc);
1810   if (NULL != ppc->resolver_handle)
1811   {
1812     //GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding request %p\n", ppc);
1813     GNUNET_CONTAINER_DLL_insert (ppc_dll_head, ppc_dll_tail, ppc);
1814   }
1815   else
1816   {
1817     GNUNET_break (0);
1818     GNUNET_free (ppc);
1819   }
1820 }
1821
1822
1823 /**
1824  * Check if the given port is plausible (must be either our listen
1825  * port or our advertised port), or any port if we are behind NAT
1826  * and do not have a port open.  If it is neither, we return
1827  * GNUNET_SYSERR.
1828  *
1829  * @param plugin global variables
1830  * @param in_port port number to check
1831  * @return GNUNET_OK if port is either open_port or adv_port
1832  */
1833 static int
1834 check_port (struct Plugin *plugin, uint16_t in_port)
1835 {
1836   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1837     return GNUNET_OK;
1838   return GNUNET_SYSERR;
1839 }
1840
1841
1842 /**
1843  * Function that will be called to check if a binary address for this
1844  * plugin is well-formed and corresponds to an address for THIS peer
1845  * (as per our configuration).  Naturally, if absolutely necessary,
1846  * plugins can be a bit conservative in their answer, but in general
1847  * plugins should make sure that the address does not redirect
1848  * traffic to a 3rd party that might try to man-in-the-middle our
1849  * traffic.
1850  *
1851  * @param cls closure, our 'struct Plugin*'
1852  * @param addr pointer to the address
1853  * @param addrlen length of addr
1854  * @return GNUNET_OK if this is a plausible address for this peer
1855  *         and transport, GNUNET_SYSERR if not
1856  */
1857 static int
1858 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1859 {
1860   struct Plugin *plugin = cls;
1861   struct IPv4TcpAddress *v4;
1862   struct IPv6TcpAddress *v6;
1863
1864   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1865       (addrlen != sizeof (struct IPv6TcpAddress)))
1866   {
1867
1868
1869         return GNUNET_SYSERR;
1870   }
1871
1872   if (addrlen == sizeof (struct IPv4TcpAddress))
1873   {
1874     v4 = (struct IPv4TcpAddress *) addr;
1875     if (0 != memcmp (&v4->options, &myoptions, sizeof (myoptions)))
1876     {
1877         GNUNET_break (0);
1878         return GNUNET_SYSERR;
1879     }
1880     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1881       return GNUNET_SYSERR;
1882     if (GNUNET_OK !=
1883         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1884                                  sizeof (struct in_addr)))
1885       return GNUNET_SYSERR;
1886   }
1887   else
1888   {
1889     v6 = (struct IPv6TcpAddress *) addr;
1890     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1891     {
1892       GNUNET_break_op (0);
1893       return GNUNET_SYSERR;
1894     }
1895     if (0 != memcmp (&v6->options, &myoptions, sizeof (myoptions)))
1896     {
1897         GNUNET_break (0);
1898         return GNUNET_SYSERR;
1899     }
1900     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1901       return GNUNET_SYSERR;
1902     if (GNUNET_OK !=
1903         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1904                                  sizeof (struct in6_addr)))
1905       return GNUNET_SYSERR;
1906   }
1907   return GNUNET_OK;
1908 }
1909
1910
1911 /**
1912  * We've received a nat probe from this peer via TCP.  Finish
1913  * creating the client session and resume sending of queued
1914  * messages.
1915  *
1916  * @param cls closure
1917  * @param client identification of the client
1918  * @param message the actual message
1919  */
1920 static void
1921 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1922                       const struct GNUNET_MessageHeader *message)
1923 {
1924   struct Plugin *plugin = cls;
1925   struct Session *session;
1926   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1927   size_t alen;
1928   void *vaddr;
1929   struct IPv4TcpAddress *t4;
1930   struct IPv6TcpAddress *t6;
1931   const struct sockaddr_in *s4;
1932   const struct sockaddr_in6 *s6;
1933
1934   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received NAT probe\n");
1935
1936   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1937    * a connection to this peer by running gnunet-nat-client.  This peer
1938    * received the punch message and now wants us to use the new connection
1939    * as the default for that peer.  Do so and then send a WELCOME message
1940    * so we can really be connected!
1941    */
1942   if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1943   {
1944     GNUNET_break_op (0);
1945     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1946     return;
1947   }
1948
1949   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1950   if (0 ==
1951       memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1952               sizeof (struct GNUNET_PeerIdentity)))
1953   {
1954     /* refuse connections from ourselves */
1955     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1956     return;
1957   }
1958
1959   session =
1960       GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
1961                                          &tcp_nat_probe->
1962                                          clientIdentity);
1963   if (session == NULL)
1964   {
1965     LOG (GNUNET_ERROR_TYPE_DEBUG,
1966          "Did NOT find session for NAT probe!\n");
1967     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1968     return;
1969   }
1970   LOG (GNUNET_ERROR_TYPE_DEBUG,
1971        "Found session for NAT probe!\n");
1972
1973   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1974   {
1975     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1976     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1977   }
1978
1979   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1980   {
1981     GNUNET_break (0);
1982     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1983     disconnect_session (session);
1984     return;
1985   }
1986   GNUNET_assert (GNUNET_CONTAINER_multipeermap_remove
1987                  (plugin->nat_wait_conns,
1988                   &tcp_nat_probe->clientIdentity,
1989                   session) == GNUNET_YES);
1990   GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
1991                                      &session->target, session,
1992                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1993   session->last_activity = GNUNET_TIME_absolute_get ();
1994   session->inbound = GNUNET_NO;
1995   LOG (GNUNET_ERROR_TYPE_DEBUG,
1996        "Found address `%s' for incoming connection\n",
1997        GNUNET_a2s (vaddr, alen));
1998   switch (((const struct sockaddr *) vaddr)->sa_family)
1999   {
2000   case AF_INET:
2001     s4 = vaddr;
2002     t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
2003     t4->options = 0;
2004     t4->t4_port = s4->sin_port;
2005     t4->ipv4_addr = s4->sin_addr.s_addr;
2006     session->addr = t4;
2007     session->addrlen = sizeof (struct IPv4TcpAddress);
2008     break;
2009   case AF_INET6:
2010     s6 = vaddr;
2011     t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
2012     t6->options = 0;
2013     t6->t6_port = s6->sin6_port;
2014     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2015     session->addr = t6;
2016     session->addrlen = sizeof (struct IPv6TcpAddress);
2017     break;
2018   default:
2019     GNUNET_break_op (0);
2020     LOG (GNUNET_ERROR_TYPE_DEBUG,
2021          "Bad address for incoming connection!\n");
2022     GNUNET_free (vaddr);
2023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2024     disconnect_session (session);
2025     return;
2026   }
2027   GNUNET_free (vaddr);
2028   GNUNET_break (NULL == session->client);
2029   GNUNET_SERVER_client_keep (client);
2030   session->client = client;
2031   inc_sessions (plugin, session, __LINE__);
2032   GNUNET_STATISTICS_update (plugin->env->stats,
2033                             gettext_noop ("# TCP sessions active"), 1,
2034                             GNUNET_NO);
2035   process_pending_messages (session);
2036   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2037 }
2038
2039
2040 /**
2041  * We've received a welcome from this peer via TCP.  Possibly create a
2042  * fresh client record and send back our welcome.
2043  *
2044  * @param cls closure
2045  * @param client identification of the client
2046  * @param message the actual message
2047  */
2048 static void
2049 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
2050                     const struct GNUNET_MessageHeader *message)
2051 {
2052   struct Plugin *plugin = cls;
2053   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
2054   struct Session *session;
2055   size_t alen;
2056   void *vaddr;
2057   struct IPv4TcpAddress *t4;
2058   struct IPv6TcpAddress *t6;
2059   const struct sockaddr_in *s4;
2060   const struct sockaddr_in6 *s6;
2061   struct GNUNET_ATS_Information ats;
2062
2063   if (0 ==
2064       memcmp (&wm->clientIdentity, plugin->env->my_identity,
2065               sizeof (struct GNUNET_PeerIdentity)))
2066   {
2067     /* refuse connections from ourselves */
2068     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2069     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2070     {
2071         LOG (GNUNET_ERROR_TYPE_WARNING,
2072          "Received %s message from my own identity `%4s' on address `%s'\n",
2073          "WELCOME", GNUNET_i2s (&wm->clientIdentity), GNUNET_a2s (vaddr, alen));
2074         GNUNET_free (vaddr);
2075     }
2076     GNUNET_break_op (0);
2077     return;
2078   }
2079   LOG (GNUNET_ERROR_TYPE_DEBUG,
2080        "Received %s message from `%4s' %p\n", "WELCOME",
2081        GNUNET_i2s (&wm->clientIdentity), client);
2082   GNUNET_STATISTICS_update (plugin->env->stats,
2083                             gettext_noop ("# TCP WELCOME messages received"), 1,
2084                             GNUNET_NO);
2085   session = lookup_session_by_client (plugin, client);
2086   if (session != NULL)
2087   {
2088     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2089     {
2090       LOG (GNUNET_ERROR_TYPE_DEBUG,
2091            "Found existing session %p for peer `%s'\n",
2092            session,
2093            GNUNET_a2s (vaddr, alen));
2094       GNUNET_free (vaddr);
2095     }
2096   }
2097   else
2098   {
2099     GNUNET_SERVER_client_keep (client);
2100     if (plugin->service != NULL) /* Otherwise value is incremented in tcp_access_check */
2101         plugin->cur_connections++;
2102     if (plugin->cur_connections == plugin->max_connections)
2103         GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
2104
2105     session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
2106     session->inbound = GNUNET_YES;
2107     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2108     {
2109       if (alen == sizeof (struct sockaddr_in))
2110       {
2111         s4 = vaddr;
2112         t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
2113         t4->options = htonl (0);
2114         t4->t4_port = s4->sin_port;
2115         t4->ipv4_addr = s4->sin_addr.s_addr;
2116         session->addr = t4;
2117         session->addrlen = sizeof (struct IPv4TcpAddress);
2118       }
2119       else if (alen == sizeof (struct sockaddr_in6))
2120       {
2121         s6 = vaddr;
2122         t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
2123         t6->options = htonl (0);
2124         t6->t6_port = s6->sin6_port;
2125         memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
2126         session->addr = t6;
2127         session->addrlen = sizeof (struct IPv6TcpAddress);
2128       }
2129
2130       ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
2131       session->ats_address_network_type = ats.value;
2132       LOG (GNUNET_ERROR_TYPE_DEBUG,
2133      "Creating new session %p for peer `%s'\n",
2134      session,
2135      GNUNET_a2s (vaddr, alen));
2136       GNUNET_free (vaddr);
2137       GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2138                                        &session->target,
2139                                        session,
2140                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2141       inc_sessions (plugin, session, __LINE__);
2142     }
2143     else
2144     {
2145       LOG (GNUNET_ERROR_TYPE_DEBUG,
2146            "Did not obtain TCP socket address for incoming connection\n");
2147       GNUNET_break (0);
2148     }
2149   }
2150
2151   if (session->expecting_welcome != GNUNET_YES)
2152   {
2153     GNUNET_break_op (0);
2154     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2155     GNUNET_break (0);
2156     return;
2157   }
2158   session->last_activity = GNUNET_TIME_absolute_get ();
2159   session->expecting_welcome = GNUNET_NO;
2160
2161   /* Notify transport and ATS about new session */
2162   if (GNUNET_YES == session->inbound)
2163   {
2164         plugin->env->session_start (NULL, &wm->clientIdentity, PLUGIN_NAME,
2165                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2166                   (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2167                   session, &ats, 1);
2168   }
2169
2170   process_pending_messages (session);
2171
2172   GNUNET_SERVER_client_set_timeout (client,
2173                                     GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2174   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2175 }
2176
2177
2178 /**
2179  * Task to signal the server that we can continue
2180  * receiving from the TCP client now.
2181  *
2182  * @param cls the 'struct Session*'
2183  * @param tc task context (unused)
2184  */
2185 static void
2186 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2187 {
2188   struct Session *session = cls;
2189
2190   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2191   reschedule_session_timeout (session);
2192
2193   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2194 }
2195
2196
2197 /**
2198  * We've received data for this peer via TCP.  Unbox,
2199  * compute latency and forward.
2200  *
2201  * @param cls closure
2202  * @param client identification of the client
2203  * @param message the actual message
2204  */
2205 static void
2206 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
2207                  const struct GNUNET_MessageHeader *message)
2208 {
2209   struct Plugin *plugin = cls;
2210   struct Session *session;
2211   struct GNUNET_TIME_Relative delay;
2212   uint16_t type;
2213
2214   type = ntohs (message->type);
2215   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
2216       (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
2217   {
2218     /* We don't want to propagate WELCOME and NAT Probe messages up! */
2219     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2220     return;
2221   }
2222   session = lookup_session_by_client (plugin, client);
2223   if (NULL == session)
2224   {
2225     /* No inbound session found */
2226     void *vaddr;
2227     size_t alen;
2228
2229     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2230     LOG (GNUNET_ERROR_TYPE_ERROR,
2231          "Received unexpected %u bytes of type %u from `%s'\n",
2232          (unsigned int) ntohs (message->size),
2233          (unsigned int) ntohs (message->type),
2234          GNUNET_a2s(vaddr, alen));
2235     GNUNET_break_op (0);
2236     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2237     GNUNET_free_non_null(vaddr);
2238     return;
2239   }
2240   else if (GNUNET_YES == session->expecting_welcome)
2241   {
2242     /* Session is expecting WELCOME message */
2243     void *vaddr;
2244     size_t alen;
2245
2246     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
2247     LOG (GNUNET_ERROR_TYPE_ERROR,
2248          "Received unexpected %u bytes of type %u from `%s'\n",
2249          (unsigned int) ntohs (message->size),
2250          (unsigned int) ntohs (message->type),
2251          GNUNET_a2s(vaddr, alen));
2252     GNUNET_break_op (0);
2253     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2254     GNUNET_free_non_null(vaddr);
2255     return;
2256   }
2257
2258   session->last_activity = GNUNET_TIME_absolute_get ();
2259   LOG (GNUNET_ERROR_TYPE_DEBUG,
2260                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2261                    (unsigned int) ntohs (message->size),
2262                    (unsigned int) ntohs (message->type),
2263                    GNUNET_i2s (&session->target));
2264
2265   GNUNET_STATISTICS_update (plugin->env->stats,
2266                             gettext_noop ("# bytes received via TCP"),
2267                             ntohs (message->size), GNUNET_NO);
2268   struct GNUNET_ATS_Information distance;
2269
2270   distance.type = htonl (GNUNET_ATS_NETWORK_TYPE);
2271   distance.value = session->ats_address_network_type;
2272   GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
2273
2274   GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2275                                                                &session->target,
2276                                                                session));
2277
2278   delay = plugin->env->receive (plugin->env->cls,
2279                                 &session->target,
2280                                 message,
2281                                 session,
2282                                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2283                                 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
2284   plugin->env->update_address_metrics (plugin->env->cls,
2285                 &session->target,
2286                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
2287                   (GNUNET_YES == session->inbound) ? 0 : session->addrlen,
2288                   session, &distance, 1);
2289
2290   reschedule_session_timeout (session);
2291
2292   if (0 == delay.rel_value_us)
2293   {
2294     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2295   }
2296   else
2297   {
2298     LOG (GNUNET_ERROR_TYPE_DEBUG,
2299          "Throttling receiving from `%s' for %s\n",
2300          GNUNET_i2s (&session->target),
2301          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2302     GNUNET_SERVER_disable_receive_done_warning (client);
2303     session->receive_delay_task =
2304         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2305   }
2306 }
2307
2308
2309 /**
2310  * Functions with this signature are called whenever a peer
2311  * is disconnected on the network level.
2312  *
2313  * @param cls closure
2314  * @param client identification of the client
2315  */
2316 static void
2317 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
2318 {
2319   struct Plugin *plugin = cls;
2320   struct Session *session;
2321
2322   if (client == NULL)
2323     return;
2324   session = lookup_session_by_client (plugin, client);
2325   if (session == NULL)
2326     return;                     /* unknown, nothing to do */
2327   LOG (GNUNET_ERROR_TYPE_DEBUG,
2328        "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2329        GNUNET_i2s (&session->target),
2330        (session->addr !=
2331         NULL) ? tcp_address_to_string (session->plugin,
2332                                        session->addr,
2333                                        session->addrlen) :
2334        "*");
2335
2336   if (plugin->cur_connections == plugin->max_connections)
2337         GNUNET_SERVER_resume (plugin->server); /* Resume server  */
2338
2339   if (plugin->cur_connections < 1)
2340         GNUNET_break (0);
2341   else
2342         plugin->cur_connections--;
2343
2344   GNUNET_STATISTICS_update (session->plugin->env->stats,
2345                             gettext_noop
2346                             ("# network-level TCP disconnect events"), 1,
2347                             GNUNET_NO);
2348   disconnect_session (session);
2349 }
2350
2351
2352 /**
2353  * We can now send a probe message, copy into buffer to really send.
2354  *
2355  * @param cls closure, a struct TCPProbeContext
2356  * @param size max size to copy
2357  * @param buf buffer to copy message to
2358  * @return number of bytes copied into buf
2359  */
2360 static size_t
2361 notify_send_probe (void *cls, size_t size, void *buf)
2362 {
2363   struct TCPProbeContext *tcp_probe_ctx = cls;
2364   struct Plugin *plugin = tcp_probe_ctx->plugin;
2365   size_t ret;
2366
2367   tcp_probe_ctx->transmit_handle = NULL;
2368   GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2369                                tcp_probe_ctx);
2370   if (buf == NULL)
2371   {
2372     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2373     GNUNET_free (tcp_probe_ctx);
2374     return 0;
2375   }
2376   GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2377   memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2378   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2379                                 tcp_probe_ctx->sock);
2380   ret = sizeof (tcp_probe_ctx->message);
2381   GNUNET_free (tcp_probe_ctx);
2382   return ret;
2383 }
2384
2385
2386 /**
2387  * Function called by the NAT subsystem suggesting another peer wants
2388  * to connect to us via connection reversal.  Try to connect back to the
2389  * given IP.
2390  *
2391  * @param cls closure
2392  * @param addr address to try
2393  * @param addrlen number of bytes in @a addr
2394  */
2395 static void
2396 try_connection_reversal (void *cls, const struct sockaddr *addr,
2397                          socklen_t addrlen)
2398 {
2399   struct Plugin *plugin = cls;
2400   struct GNUNET_CONNECTION_Handle *sock;
2401   struct TCPProbeContext *tcp_probe_ctx;
2402
2403   /**
2404    * We have received an ICMP response, ostensibly from a peer
2405    * that wants to connect to us! Send a message to establish a connection.
2406    */
2407   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2408   if (sock == NULL)
2409   {
2410     /* failed for some odd reason (out of sockets?); ignore attempt */
2411     return;
2412   }
2413
2414   /* FIXME: do we need to track these probe context objects so that
2415    * we can clean them up on plugin unload? */
2416   tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2417   tcp_probe_ctx->message.header.size =
2418       htons (sizeof (struct TCP_NAT_ProbeMessage));
2419   tcp_probe_ctx->message.header.type =
2420       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2421   memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2422           sizeof (struct GNUNET_PeerIdentity));
2423   tcp_probe_ctx->plugin = plugin;
2424   tcp_probe_ctx->sock = sock;
2425   GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2426                                tcp_probe_ctx);
2427   tcp_probe_ctx->transmit_handle =
2428       GNUNET_CONNECTION_notify_transmit_ready (sock,
2429                                                ntohs (tcp_probe_ctx->
2430                                                       message.header.size),
2431                                                GNUNET_TIME_UNIT_FOREVER_REL,
2432                                                &notify_send_probe,
2433                                                tcp_probe_ctx);
2434
2435 }
2436
2437
2438 /**
2439  * Session was idle, so disconnect it
2440  */
2441 static void
2442 session_timeout (void *cls,
2443                  const struct GNUNET_SCHEDULER_TaskContext *tc)
2444 {
2445   struct Session *s = cls;
2446
2447   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449               "Session %p was idle for %s, disconnecting\n",
2450               s,
2451               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2452                                                       GNUNET_YES));
2453   /* call session destroy function */
2454   disconnect_session (s);
2455 }
2456
2457
2458 /**
2459  * Start session timeout
2460  */
2461 static void
2462 start_session_timeout (struct Session *s)
2463 {
2464   GNUNET_assert (NULL != s);
2465   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2466   s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2467                                                    &session_timeout,
2468                                                    s);
2469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470               "Timeout for session %p set to %s\n",
2471               s,
2472               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2473                                                       GNUNET_YES));
2474 }
2475
2476
2477 /**
2478  * Increment session timeout due to activity
2479  */
2480 static void
2481 reschedule_session_timeout (struct Session *s)
2482 {
2483   GNUNET_assert (NULL != s);
2484   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2485
2486   GNUNET_SCHEDULER_cancel (s->timeout_task);
2487   s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2488                                                   &session_timeout,
2489                                                   s);
2490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2491               "Timeout rescheduled for session %p set to %s\n",
2492               s,
2493               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2494                                                       GNUNET_YES));
2495 }
2496
2497
2498 /**
2499  * Cancel timeout.
2500  *
2501  * @param s session to cancel timeout for
2502  */
2503 static void
2504 stop_session_timeout (struct Session *s)
2505 {
2506   GNUNET_assert (NULL != s);
2507
2508   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
2509   {
2510     GNUNET_SCHEDULER_cancel (s->timeout_task);
2511     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2512     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2513                 "Timeout stopped for session %p canceled\n",
2514                 s);
2515   }
2516 }
2517
2518 /**
2519  * Function obtain the network type for a session
2520  *
2521  * @param cls closure ('struct Plugin*')
2522  * @param session the session
2523  * @return the network type in HBO or GNUNET_SYSERR
2524  */
2525 static enum GNUNET_ATS_Network_Type
2526 tcp_get_network (void *cls,
2527                  struct Session *session)
2528 {
2529   GNUNET_assert (NULL != session);
2530   return ntohl (session->ats_address_network_type);
2531 }
2532
2533
2534 /**
2535  * Entry point for the plugin.
2536  *
2537  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2538  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2539  */
2540 void *
2541 libgnunet_plugin_transport_tcp_init (void *cls)
2542 {
2543   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2544     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2545      sizeof (struct WelcomeMessage)},
2546     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2547      sizeof (struct TCP_NAT_ProbeMessage)},
2548     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2549     {NULL, NULL, 0, 0}
2550   };
2551   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2552   struct GNUNET_TRANSPORT_PluginFunctions *api;
2553   struct Plugin *plugin;
2554   struct GNUNET_SERVICE_Context *service;
2555   unsigned long long aport;
2556   unsigned long long bport;
2557   unsigned long long max_connections;
2558   unsigned int i;
2559   struct GNUNET_TIME_Relative idle_timeout;
2560   int ret;
2561   int ret_s;
2562   struct sockaddr **addrs;
2563   socklen_t *addrlens;
2564
2565
2566   if (NULL == env->receive)
2567   {
2568     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2569        initialze the plugin or the API */
2570     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2571     api->cls = NULL;
2572     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2573     api->address_to_string = &tcp_address_to_string;
2574     api->string_to_address = &tcp_string_to_address;
2575     return api;
2576   }
2577
2578   GNUNET_assert (NULL != env->cfg);
2579   if (GNUNET_OK !=
2580       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2581                                              "MAX_CONNECTIONS",
2582                                              &max_connections))
2583     max_connections = 128;
2584
2585   aport = 0;
2586   if ((GNUNET_OK !=
2587        GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2588                                               &bport)) || (bport > 65535) ||
2589       ((GNUNET_OK ==
2590         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2591                                                "ADVERTISED-PORT", &aport)) &&
2592        (aport > 65535)))
2593   {
2594     LOG (GNUNET_ERROR_TYPE_ERROR,
2595          _
2596          ("Require valid port number for service `%s' in configuration!\n"),
2597          "transport-tcp");
2598     return NULL;
2599   }
2600   if (aport == 0)
2601     aport = bport;
2602   if (bport == 0)
2603     aport = 0;
2604   if (bport != 0)
2605   {
2606     service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2607     if (service == NULL)
2608     {
2609       LOG (GNUNET_ERROR_TYPE_WARNING,
2610            _("Failed to start service.\n"));
2611       return NULL;
2612     }
2613   }
2614   else
2615     service = NULL;
2616
2617   /* Initialize my flags */
2618   myoptions = 0;
2619
2620   plugin = GNUNET_malloc (sizeof (struct Plugin));
2621   plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections, GNUNET_YES);
2622   plugin->max_connections = max_connections;
2623   plugin->cur_connections = 0;
2624   plugin->open_port = bport;
2625   plugin->adv_port = aport;
2626   plugin->env = env;
2627   plugin->lsock = NULL;
2628   if ((service != NULL) &&
2629       (GNUNET_SYSERR !=
2630        (ret_s =
2631         GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2632                                              &addrlens))))
2633   {
2634     for (ret = ret_s-1; ret >= 0; ret--)
2635       LOG (GNUNET_ERROR_TYPE_INFO,
2636            "Binding to address `%s'\n",
2637            GNUNET_a2s (addrs[ret], addrlens[ret]));
2638     plugin->nat =
2639         GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret_s,
2640                              (const struct sockaddr **) addrs, addrlens,
2641                              &tcp_nat_port_map_callback,
2642                              &try_connection_reversal, plugin);
2643     for (ret = ret_s -1; ret >= 0; ret--)
2644     {
2645       GNUNET_assert (addrs[ret] != NULL);
2646       GNUNET_free (addrs[ret]);
2647     }
2648     GNUNET_free_non_null (addrs);
2649     GNUNET_free_non_null (addrlens);
2650   }
2651   else
2652   {
2653     plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
2654                                        GNUNET_YES, 0, 0, NULL, NULL, NULL,
2655                                        &try_connection_reversal, plugin);
2656   }
2657   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2658   api->cls = plugin;
2659   api->send = &tcp_plugin_send;
2660   api->get_session = &tcp_plugin_get_session;
2661
2662   api->disconnect = &tcp_plugin_disconnect;
2663   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2664   api->check_address = &tcp_plugin_check_address;
2665   api->address_to_string = &tcp_address_to_string;
2666   api->string_to_address = &tcp_string_to_address;
2667   api->get_network = &tcp_get_network;
2668   plugin->service = service;
2669   if (service != NULL)
2670   {
2671     plugin->server = GNUNET_SERVICE_get_server (service);
2672   }
2673   else
2674   {
2675     if (GNUNET_OK !=
2676         GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2677                                              "TIMEOUT", &idle_timeout))
2678     {
2679       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2680                                  "transport-tcp", "TIMEOUT");
2681       if (plugin->nat != NULL)
2682         GNUNET_NAT_unregister (plugin->nat);
2683       GNUNET_free (plugin);
2684       GNUNET_free (api);
2685       return NULL;
2686     }
2687     plugin->server =
2688         GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2689                                            NULL, idle_timeout, GNUNET_YES);
2690   }
2691   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2692   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2693   for (i = 0;
2694        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2695        i++)
2696     plugin->handlers[i].callback_cls = plugin;
2697
2698   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2699   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2700   plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
2701   if (bport != 0)
2702     LOG (GNUNET_ERROR_TYPE_INFO,
2703          _("TCP transport listening on port %llu\n"), bport);
2704   else
2705     LOG (GNUNET_ERROR_TYPE_INFO,
2706          _
2707          ("TCP transport not listening on any port (client only)\n"));
2708   if (aport != bport)
2709     LOG (GNUNET_ERROR_TYPE_INFO,
2710                      _
2711                      ("TCP transport advertises itself as being on port %llu\n"),
2712                      aport);
2713   /* Initially set connections to 0 */
2714   GNUNET_assert (NULL != plugin->env->stats);
2715   GNUNET_STATISTICS_set (plugin->env->stats,
2716                         gettext_noop ("# TCP sessions active"), 0,
2717                         GNUNET_NO);
2718   return api;
2719 }
2720
2721
2722 /**
2723  * Exit point from the plugin.
2724  */
2725 void *
2726 libgnunet_plugin_transport_tcp_done (void *cls)
2727 {
2728   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2729   struct Plugin *plugin = api->cls;
2730   struct TCPProbeContext *tcp_probe;
2731   struct PrettyPrinterContext *cur;
2732   struct PrettyPrinterContext *next;
2733
2734   if (NULL == plugin)
2735   {
2736     GNUNET_free (api);
2737     return NULL;
2738   }
2739   LOG (GNUNET_ERROR_TYPE_DEBUG,
2740        "Shutting down TCP plugin\n");
2741
2742   /* Removing leftover sessions */
2743   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
2744                                          &session_disconnect_it, NULL);
2745   /* Removing leftover NAT sessions */
2746   GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
2747                                          &session_disconnect_it, NULL);
2748
2749   next = ppc_dll_head;
2750   for (cur = next; NULL != cur; cur = next)
2751   {
2752     next = cur->next;
2753     GNUNET_CONTAINER_DLL_remove (ppc_dll_head, ppc_dll_tail, cur);
2754     if (NULL != cur->resolver_handle)
2755       GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
2756     GNUNET_SCHEDULER_cancel (cur->timeout_task);
2757     GNUNET_free (cur);
2758     GNUNET_break (0);
2759   }
2760
2761   if (plugin->service != NULL)
2762     GNUNET_SERVICE_stop (plugin->service);
2763   else
2764     GNUNET_SERVER_destroy (plugin->server);
2765   GNUNET_free (plugin->handlers);
2766   if (plugin->nat != NULL)
2767     GNUNET_NAT_unregister (plugin->nat);
2768   while (NULL != (tcp_probe = plugin->probe_head))
2769   {
2770     GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2771                                  tcp_probe);
2772     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2773     GNUNET_free (tcp_probe);
2774   }
2775   GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
2776   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
2777   GNUNET_free (plugin);
2778   GNUNET_free (api);
2779   return NULL;
2780 }
2781
2782 /* end of plugin_transport_tcp.c */