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