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