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