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