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