d8804b254941e3a0331be76ff0d91a568286bc30
[oweals/gnunet.git] / src / transport / plugin_transport_tcp.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 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_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_nat_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_resolver_service.h"
33 #include "gnunet_server_lib.h"
34 #include "gnunet_service_lib.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_transport_plugin.h"
39 #include "transport.h"
40
41 #define DEBUG_TCP GNUNET_NO
42
43 #define DEBUG_TCP_NAT GNUNET_YES
44
45 /**
46  * How long until we give up on transmitting the welcome message?
47  */
48 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
49
50
51 /**
52  * Initial handshake message for a session.
53  */
54 struct WelcomeMessage
55 {
56   /**
57    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
58    */
59   struct GNUNET_MessageHeader header;
60
61   /**
62    * Identity of the node connecting (TCP client)
63    */
64   struct GNUNET_PeerIdentity clientIdentity;
65
66 };
67
68
69 /**
70  * Basically a WELCOME message, but with the purpose
71  * of giving the waiting peer a client handle to use
72  */
73 struct TCP_NAT_ProbeMessage
74 {
75   /**
76    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
77    */
78   struct GNUNET_MessageHeader header;
79
80   /**
81    * Identity of the sender of the message.
82    */
83   struct GNUNET_PeerIdentity clientIdentity;
84
85 };
86
87
88 /**
89  * Context for sending a NAT probe via TCP.
90  */
91 struct TCPProbeContext
92 {
93
94   /**
95    * Active probes are kept in a DLL.
96    */
97   struct TCPProbeContext *next;
98
99   /**
100    * Active probes are kept in a DLL.
101    */
102   struct TCPProbeContext *prev;
103
104   /**
105    * Probe connection.
106    */
107   struct GNUNET_CONNECTION_Handle *sock;
108
109   /**
110    * Message to be sent.
111    */
112   struct TCP_NAT_ProbeMessage message;
113
114   /**
115    * Handle to the transmission.
116    */
117   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
118
119   /**
120    * Transport plugin handle.
121    */
122   struct Plugin *plugin;
123 };
124
125
126 /**
127  * Network format for IPv4 addresses.
128  */
129 struct IPv4TcpAddress
130 {
131   /**
132    * IPv4 address, in network byte order.
133    */
134   uint32_t ipv4_addr GNUNET_PACKED;
135
136   /**
137    * Port number, in network byte order.
138    */
139   uint16_t t_port GNUNET_PACKED;
140
141 };
142
143
144 /**
145  * Network format for IPv6 addresses.
146  */
147 struct IPv6TcpAddress
148 {
149   /**
150    * IPv6 address.
151    */
152   struct in6_addr ipv6_addr GNUNET_PACKED;
153
154   /**
155    * Port number, in network byte order.
156    */
157   uint16_t t6_port GNUNET_PACKED;
158
159 };
160
161
162 /**
163  * Encapsulation of all of the state of the plugin.
164  */
165 struct Plugin;
166
167
168 /**
169  * Local network addresses (actual IP address follows this struct).
170  * PORT is NOT included!
171  */
172 struct LocalAddrList
173 {
174
175   /**
176    * This is a doubly linked list.
177    */
178   struct LocalAddrList *next;
179
180   /**
181    * This is a doubly linked list.
182    */
183   struct LocalAddrList *prev;
184
185   /**
186    * Link to plugin.
187    */
188   struct Plugin *plugin;
189
190   /**
191    * Handle to NAT holes we've tried to punch for this address.
192    */
193   struct GNUNET_NAT_Handle *nat;
194
195   /**
196    * Pointer to a 'struct IPv4/V6TcpAddress' describing our external IP and port
197    * as obtained from the NAT by automatic port mapping.
198    */
199   void *external_nat_address;
200
201   /**
202    * Number of bytes in 'external_nat_address'
203    */
204   size_t ena_size;
205
206   /**
207    * Number of bytes of the address that follow
208    */
209   size_t size;
210
211 };
212
213
214 /**
215  * Information kept for each message that is yet to
216  * be transmitted.
217  */
218 struct PendingMessage
219 {
220
221   /**
222    * This is a doubly-linked list.
223    */
224   struct PendingMessage *next;
225
226   /**
227    * This is a doubly-linked list.
228    */
229   struct PendingMessage *prev;
230
231   /**
232    * The pending message
233    */
234   const char *msg;
235
236   /**
237    * Continuation function to call once the message
238    * has been sent.  Can be NULL if there is no
239    * continuation to call.
240    */
241   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
242
243   /**
244    * Closure for transmit_cont.
245    */
246   void *transmit_cont_cls;
247
248   /**
249    * Timeout value for the pending message.
250    */
251   struct GNUNET_TIME_Absolute timeout;
252
253   /**
254    * So that the gnunet-service-transport can group messages together,
255    * these pending messages need to accept a message buffer and size
256    * instead of just a GNUNET_MessageHeader.
257    */
258   size_t message_size;
259
260 };
261
262
263 /**
264  * Session handle for TCP connections.
265  */
266 struct Session
267 {
268
269   /**
270    * API requirement.
271    */
272   struct SessionHeader header;
273
274   /**
275    * Stored in a linked list.
276    */
277   struct Session *next;
278
279   /**
280    * Pointer to the global plugin struct.
281    */
282   struct Plugin *plugin;
283
284   /**
285    * The client (used to identify this connection)
286    */
287   struct GNUNET_SERVER_Client *client;
288
289   /**
290    * Messages currently pending for transmission
291    * to this peer, if any.
292    */
293   struct PendingMessage *pending_messages_head;
294
295   /**
296    * Messages currently pending for transmission
297    * to this peer, if any.
298    */
299   struct PendingMessage *pending_messages_tail;
300
301   /**
302    * Handle for pending transmission request.
303    */
304   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
305
306   /**
307    * To whom are we talking to (set to our identity
308    * if we are still waiting for the welcome message)
309    */
310   struct GNUNET_PeerIdentity target;
311
312   /**
313    * ID of task used to delay receiving more to throttle sender.
314    */
315   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
316
317   /**
318    * Address of the other peer (either based on our 'connect'
319    * call or on our 'accept' call).
320    */
321   void *connect_addr;
322
323   /**
324    * Last activity on this connection.  Used to select preferred
325    * connection.
326    */
327   struct GNUNET_TIME_Absolute last_activity;
328
329   /**
330    * Length of connect_addr.
331    */
332   size_t connect_alen;
333
334   /**
335    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
336    */
337   int expecting_welcome;
338
339   /**
340    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
341    */
342   int inbound;
343
344   /**
345    * Was this session created using NAT traversal?
346    */
347   int is_nat;
348
349 };
350
351
352 /**
353  * Encapsulation of all of the state of the plugin.
354  */
355 struct Plugin
356 {
357   /**
358    * Our environment.
359    */
360   struct GNUNET_TRANSPORT_PluginEnvironment *env;
361
362   /**
363    * The listen socket.
364    */
365   struct GNUNET_CONNECTION_Handle *lsock;
366
367   /**
368    * stdout pipe handle for the gnunet-nat-server process
369    */
370   struct GNUNET_DISK_PipeHandle *server_stdout;
371
372   /**
373    * stdout file handle (for reading) for the gnunet-nat-server process
374    */
375   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
376
377   /**
378    * ID of select gnunet-nat-server stdout read task
379    */
380   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
381
382   /**
383    * The process id of the server process (if behind NAT)
384    */
385   struct GNUNET_OS_Process *server_proc;
386
387   /**
388    * List of open TCP sessions.
389    */
390   struct Session *sessions;
391
392   /**
393    * Handle to the network service.
394    */
395   struct GNUNET_SERVICE_Context *service;
396
397   /**
398    * Handle to the server for this service.
399    */
400   struct GNUNET_SERVER_Handle *server;
401
402   /**
403    * Copy of the handler array where the closures are
404    * set to this struct's instance.
405    */
406   struct GNUNET_SERVER_MessageHandler *handlers;
407
408   /**
409    * Handle for request of hostname resolution, non-NULL if pending.
410    */
411   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
412
413   /**
414    * Map of peers we have tried to contact behind a NAT
415    */
416   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
417
418   /**
419    * The external address given to us by the user.  Used for HELLOs
420    * and address validation.
421    */
422   char *external_address;
423
424   /**
425    * The internal address given to us by the user (or discovered).
426    * Used for NAT traversal (ICMP method), but not as a 'validateable'
427    * address in HELLOs.
428    */
429   char *internal_address;
430
431   /**
432    * Address given for us to bind to (ONLY).
433    */
434   char *bind_address;
435
436   /**
437    * use local addresses?
438    */
439   int use_localaddresses;
440
441   /**
442    * List of our IP addresses.
443    */
444   struct LocalAddrList *lal_head;
445
446   /**
447    * Tail of our IP address list.
448    */
449   struct LocalAddrList *lal_tail;
450
451   /**
452    * List of active TCP probes.
453    */
454   struct TCPProbeContext *probe_head;
455
456   /**
457    * List of active TCP probes.
458    */
459   struct TCPProbeContext *probe_tail;
460
461   /**
462    * Handle for (DYN)DNS lookup of our external IP.
463    */
464   struct GNUNET_RESOLVER_RequestHandle *ext_dns;
465   
466   /**
467    * How many more TCP sessions are we allowed to open right now?
468    */
469   unsigned long long max_connections;
470
471   /**
472    * ID of task used to update our addresses when one expires.
473    */
474   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
475
476   /**
477    * Port that we are actually listening on.
478    */
479   uint16_t open_port;
480
481   /**
482    * Port that the user said we would have visible to the
483    * rest of the world.
484    */
485   uint16_t adv_port;
486
487   /**
488    * Is this transport configured to be behind a NAT?
489    */
490   int behind_nat;
491
492   /**
493    * Has the NAT been punched?
494    */
495   int nat_punched;
496
497   /**
498    * Is this transport configured to allow connections to NAT'd peers?
499    */
500   int enable_nat_client;
501
502   /**
503    * Should we run the gnunet-nat-server?
504    */
505   int enable_nat_server;
506
507   /**
508    * Are we allowed to try UPnP/PMP for NAT traversal?
509    */
510   int enable_upnp;
511
512 };
513
514
515 /**
516  * Function to check if an inbound connection is acceptable.
517  * Mostly used to limit the total number of open connections 
518  * we can have.
519  *
520  * @param cls the 'struct Plugin'
521  * @param ucred credentials, if available, otherwise NULL
522  * @param addr address
523  * @param addrlen length of address
524  * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
525  *   for unknown address family (will be denied).
526  */
527 static int
528 plugin_tcp_access_check (void *cls,
529                          const struct GNUNET_CONNECTION_Credentials *ucred,
530                          const struct sockaddr *addr,
531                          socklen_t addrlen)
532 {
533   struct Plugin *plugin = cls;
534
535   if (0 == plugin->max_connections)
536     return GNUNET_NO;
537   plugin->max_connections--;
538   return GNUNET_YES;
539 }
540
541
542 /**
543  * Our external IP address/port mapping has changed.
544  *
545  * @param cls closure, the 'struct LocalAddrList'
546  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
547  *     the previous (now invalid) one
548  * @param addr either the previous or the new public IP address
549  * @param addrlen actual lenght of the address
550  */
551 static void
552 nat_port_map_callback (void *cls,
553                        int add_remove,
554                        const struct sockaddr *addr,
555                        socklen_t addrlen)
556 {
557   struct LocalAddrList *lal = cls;
558   struct Plugin *plugin = lal->plugin;
559   int af;
560   struct IPv4TcpAddress t4;
561   struct IPv6TcpAddress t6;
562   void *arg;
563   uint16_t args;
564
565   /* convert 'addr' to our internal format */
566   af = addr->sa_family;
567   switch (af)
568     {
569     case AF_INET:
570       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
571       t4.t_port = ((struct sockaddr_in *) addr)->sin_port;
572       arg = &t4;
573       args = sizeof (t4);
574       break;
575     case AF_INET6:
576       memcpy (&t6.ipv6_addr,
577               &((struct sockaddr_in6 *) addr)->sin6_addr,
578               sizeof (struct in6_addr));
579       t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
580       arg = &t6;
581       args = sizeof (t6);    
582       break;
583     default:
584       GNUNET_break (0);
585       return;
586     } 
587
588   /* modify our published address list */
589   if (GNUNET_YES == add_remove)
590     {
591       plugin->env->notify_address (plugin->env->cls,
592                                    "tcp",
593                                    arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
594       GNUNET_free_non_null (lal->external_nat_address);
595       lal->external_nat_address = GNUNET_memdup (arg, args);
596       lal->ena_size = args;
597     }
598   else
599     {
600       plugin->env->notify_address (plugin->env->cls,
601                                    "tcp",
602                                    arg, args, GNUNET_TIME_UNIT_ZERO);
603       GNUNET_free_non_null (lal->external_nat_address);
604       lal->ena_size = 0;
605     }
606 }
607
608
609 /**
610  * Add the given address to the list of 'local' addresses, thereby
611  * making it a 'legal' address for this peer to have.  
612  * 
613  * @param plugin the plugin
614  * @param arg the address, either an IPv4 or an IPv6 IP address
615  * @param arg_size number of bytes in arg
616  */
617 static void
618 add_to_address_list (struct Plugin *plugin,
619                      const void *arg,
620                      size_t arg_size)
621 {
622   struct LocalAddrList *lal;
623   struct sockaddr_in v4;
624   struct sockaddr_in6 v6;
625   const struct sockaddr *sa;
626   socklen_t salen;
627
628   lal = plugin->lal_head;
629   while (NULL != lal)
630     {
631       if ( (lal->size == arg_size) &&
632            (0 == memcmp (&lal[1], arg, arg_size)) )
633         return;
634       lal = lal->next;
635     }
636   lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
637   lal->plugin = plugin;
638   lal->size = arg_size;
639   memcpy (&lal[1], arg, arg_size);
640   GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
641                                plugin->lal_tail,
642                                lal);
643   if (plugin->open_port == 0)
644     return; /* we're not listening at all... */
645   if (arg_size == sizeof (struct in_addr))
646     {
647       memset (&v4, 0, sizeof (v4));
648       v4.sin_family = AF_INET;
649       v4.sin_port = htons (plugin->open_port);
650       memcpy (&v4.sin_addr, arg, arg_size);
651 #if HAVE_SOCKADDR_IN_SIN_LEN
652       v4.sin_len = sizeof (struct sockaddr_in);
653 #endif
654       sa = (const struct sockaddr*) &v4;
655       salen = sizeof (v4);
656     }
657   else if (arg_size == sizeof (struct in6_addr))
658     {     
659       memset (&v6, 0, sizeof (v6));
660       v6.sin6_family = AF_INET6;
661       v6.sin6_port = htons (plugin->open_port);
662       memcpy (&v6.sin6_addr, arg, arg_size);
663 #if HAVE_SOCKADDR_IN_SIN_LEN
664       v6.sin6_len = sizeof (struct sockaddr_in6);
665 #endif
666       sa = (const struct sockaddr*) &v6;
667       salen = sizeof (v6);
668     }
669   else
670     {
671       GNUNET_break (0);
672       return;
673     }
674   if ( (plugin->behind_nat == GNUNET_YES) &&
675        (plugin->enable_upnp == GNUNET_YES) )
676     lal->nat = GNUNET_NAT_register (plugin->env->cfg,
677                                     sa, salen,
678                                     &nat_port_map_callback,
679                                     lal);
680 }
681
682
683 /**
684  * Check if the given address is in the list of 'local' addresses.
685  * 
686  * @param plugin the plugin
687  * @param arg the address, either an IPv4 or an IPv6 IP address
688  * @param arg_size number of bytes in arg
689  * @return GNUNET_OK if this is one of our IPs, GNUNET_SYSERR if not
690  */
691 static int
692 check_local_addr (struct Plugin *plugin,
693                   const void *arg,
694                   size_t arg_size)
695 {
696   struct LocalAddrList *lal;
697
698   lal = plugin->lal_head;
699   while (NULL != lal)
700     {
701       if ( (lal->size == arg_size) &&
702            (0 == memcmp (&lal[1], arg, arg_size)) )
703         return GNUNET_OK;
704       lal = lal->next;
705     }
706   return GNUNET_SYSERR;
707 }
708
709
710 /**
711  * Check if the given address is in the list of 'mapped' addresses.
712  * 
713  * @param plugin the plugin
714  * @param arg the address, either a 'struct IPv4TcpAddress' or a 'struct IPv6TcpAddress'
715  * @param arg_size number of bytes in arg
716  * @return GNUNET_OK if this is one of our IPs, GNUNET_SYSERR if not
717  */
718 static int
719 check_mapped_addr (struct Plugin *plugin,
720                    const void *arg,
721                    size_t arg_size)
722 {
723   struct LocalAddrList *lal;
724
725   lal = plugin->lal_head;
726   while (NULL != lal)
727     {
728       if ( (lal->ena_size == arg_size) &&
729            (0 == memcmp (lal->external_nat_address, arg, arg_size)) )
730         return GNUNET_OK;
731       lal = lal->next;
732     }
733   return GNUNET_SYSERR;
734 }
735
736
737 /**
738  * Function called for a quick conversion of the binary address to
739  * a numeric address.  Note that the caller must not free the
740  * address and that the next call to this function is allowed
741  * to override the address again.
742  *
743  * @param cls closure ('struct Plugin*')
744  * @param addr binary address
745  * @param addrlen length of the address
746  * @return string representing the same address
747  */
748 static const char*
749 tcp_address_to_string (void *cls,
750                        const void *addr,
751                        size_t addrlen)
752 {
753   static char rbuf[INET6_ADDRSTRLEN + 12];
754   char buf[INET6_ADDRSTRLEN];
755   const void *sb;
756   struct in_addr a4;
757   struct in6_addr a6;
758   const struct IPv4TcpAddress *t4;
759   const struct IPv6TcpAddress *t6;
760   int af;
761   uint16_t port;
762
763   if (addrlen == sizeof (struct IPv6TcpAddress))
764     {
765       t6 = addr;
766       af = AF_INET6;
767       port = ntohs (t6->t6_port);
768       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
769       sb = &a6;
770     }
771   else if (addrlen == sizeof (struct IPv4TcpAddress))
772     {
773       t4 = addr;
774       af = AF_INET;
775       port = ntohs (t4->t_port);
776       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
777       sb = &a4;
778     }
779   else
780     {
781       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
782                        "tcp",
783                        _("Unexpected address length: %u bytes\n"),
784                        (unsigned int) addrlen);
785       GNUNET_break (0);
786       return NULL;
787     }
788   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
789     {
790       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
791       return NULL;
792     }
793   GNUNET_snprintf (rbuf,
794                    sizeof (rbuf),
795                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
796                    buf,
797                    port);
798   return rbuf;
799 }
800
801
802 /**
803  * Find the session handle for the given client.
804  *
805  * @param plugin the plugin
806  * @param client which client to find the session handle for
807  * @return NULL if no matching session exists
808  */
809 static struct Session *
810 find_session_by_client (struct Plugin *plugin,
811                         const struct GNUNET_SERVER_Client *client)
812 {
813   struct Session *ret;
814
815   ret = plugin->sessions;
816   while ((ret != NULL) && (client != ret->client))
817     ret = ret->next;
818   return ret;
819 }
820
821
822 /**
823  * Create a new session.  Also queues a welcome message.
824  *
825  * @param plugin the plugin
826  * @param target peer to connect to
827  * @param client client to use
828  * @param is_nat this a NAT session, we should wait for a client to
829  *               connect to us from an address, then assign that to
830  *               the session
831  * @return new session object
832  */
833 static struct Session *
834 create_session (struct Plugin *plugin,
835                 const struct GNUNET_PeerIdentity *target,
836                 struct GNUNET_SERVER_Client *client, 
837                 int is_nat)
838 {
839   struct Session *ret;
840   struct PendingMessage *pm;
841   struct WelcomeMessage welcome;
842
843   if (is_nat != GNUNET_YES)
844     GNUNET_assert (client != NULL);
845   else
846     GNUNET_assert (client == NULL);
847 #if DEBUG_TCP
848   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
849                    "tcp",
850                    "Creating new session for peer `%4s'\n",
851                    GNUNET_i2s (target));
852 #endif
853   ret = GNUNET_malloc (sizeof (struct Session));
854   ret->last_activity = GNUNET_TIME_absolute_get ();
855   ret->plugin = plugin;
856   ret->is_nat = is_nat;
857   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
858     {
859       ret->next = plugin->sessions;
860       plugin->sessions = ret;
861     }
862   ret->client = client;
863   ret->target = *target;
864   ret->expecting_welcome = GNUNET_YES;
865   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
866   pm->msg = (const char*) &pm[1];
867   pm->message_size = sizeof (struct WelcomeMessage);
868   welcome.header.size = htons (sizeof (struct WelcomeMessage));
869   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
870   welcome.clientIdentity = *plugin->env->my_identity;
871   memcpy (&pm[1], &welcome, sizeof (welcome));
872   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
873   GNUNET_STATISTICS_update (plugin->env->stats,
874                             gettext_noop ("# bytes currently in TCP buffers"),
875                             pm->message_size,
876                             GNUNET_NO);
877   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
878                                ret->pending_messages_tail,
879                                pm);
880   if (is_nat != GNUNET_YES)
881     GNUNET_STATISTICS_update (plugin->env->stats,
882                               gettext_noop ("# TCP sessions active"),
883                               1,
884                               GNUNET_NO);
885   return ret;
886 }
887
888
889 /**
890  * If we have pending messages, ask the server to
891  * transmit them (schedule the respective tasks, etc.)
892  *
893  * @param session for which session should we do this
894  */
895 static void process_pending_messages (struct Session *session);
896
897
898 /**
899  * Function called to notify a client about the socket
900  * being ready to queue more data.  "buf" will be
901  * NULL and "size" zero if the socket was closed for
902  * writing in the meantime.
903  *
904  * @param cls closure
905  * @param size number of bytes available in buf
906  * @param buf where the callee should write the message
907  * @return number of bytes written to buf
908  */
909 static size_t
910 do_transmit (void *cls, size_t size, void *buf)
911 {
912   struct Session *session = cls;
913   struct GNUNET_PeerIdentity pid;
914   struct Plugin *plugin;
915   struct PendingMessage *pos;
916   struct PendingMessage *hd;
917   struct PendingMessage *tl;
918   struct GNUNET_TIME_Absolute now;
919   char *cbuf;
920   size_t ret;
921
922   session->transmit_handle = NULL;
923   plugin = session->plugin;
924   if (buf == NULL)
925     {
926 #if DEBUG_TCP
927       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
928                        "tcp",
929                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
930                        GNUNET_i2s (&session->target));
931 #endif
932       /* timeout; cancel all messages that have already expired */
933       hd = NULL;
934       tl = NULL;
935       ret = 0;
936       now = GNUNET_TIME_absolute_get ();
937       while ( (NULL != (pos = session->pending_messages_head)) &&
938               (pos->timeout.abs_value <= now.abs_value) )
939         {
940           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
941                                        session->pending_messages_tail,
942                                        pos);
943 #if DEBUG_TCP
944           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
945                            "tcp",
946                            "Failed to transmit %u byte message to `%4s'.\n",
947                            pos->message_size,
948                            GNUNET_i2s (&session->target));
949 #endif
950           ret += pos->message_size;
951           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
952         }
953       /* do this call before callbacks (so that if callbacks destroy
954          session, they have a chance to cancel actions done by this
955          call) */
956       process_pending_messages (session);
957       pid = session->target;
958       /* no do callbacks and do not use session again since
959          the callbacks may abort the session */
960       while (NULL != (pos = hd))
961         {
962           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
963           if (pos->transmit_cont != NULL)
964             pos->transmit_cont (pos->transmit_cont_cls,
965                                 &pid, GNUNET_SYSERR);
966           GNUNET_free (pos);
967         }
968       GNUNET_STATISTICS_update (plugin->env->stats,
969                                 gettext_noop ("# bytes currently in TCP buffers"),
970                                 - (int64_t) ret,
971                                 GNUNET_NO);
972       GNUNET_STATISTICS_update (plugin->env->stats,
973                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
974                                 ret,
975                                 GNUNET_NO);
976       return 0;
977     }
978   /* copy all pending messages that would fit */
979   ret = 0;
980   cbuf = buf;
981   hd = NULL;
982   tl = NULL;
983   while (NULL != (pos = session->pending_messages_head))
984     {
985       if (ret + pos->message_size > size)
986         break;
987       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
988                                    session->pending_messages_tail,
989                                    pos);
990       GNUNET_assert (size >= pos->message_size);
991       /* FIXME: this memcpy can be up to 7% of our total runtime */
992       memcpy (cbuf, pos->msg, pos->message_size);
993       cbuf += pos->message_size;
994       ret += pos->message_size;
995       size -= pos->message_size;
996       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
997     }
998   /* schedule 'continuation' before callbacks so that callbacks that
999      cancel everything don't cause us to use a session that no longer
1000      exists... */
1001   process_pending_messages (session);
1002   session->last_activity = GNUNET_TIME_absolute_get ();
1003   pid = session->target;
1004   /* we'll now call callbacks that may cancel the session; hence
1005      we should not use 'session' after this point */
1006   while (NULL != (pos = hd))
1007     {
1008       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
1009       if (pos->transmit_cont != NULL)
1010         pos->transmit_cont (pos->transmit_cont_cls,
1011                             &pid, GNUNET_OK);
1012       GNUNET_free (pos);
1013     }
1014   GNUNET_assert (hd == NULL);
1015   GNUNET_assert (tl == NULL);
1016 #if DEBUG_TCP > 1
1017   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1018                    "tcp",
1019                    "Transmitting %u bytes\n", 
1020                    ret);
1021 #endif
1022   GNUNET_STATISTICS_update (plugin->env->stats,
1023                             gettext_noop ("# bytes currently in TCP buffers"),
1024                             - (int64_t) ret,
1025                             GNUNET_NO);
1026   GNUNET_STATISTICS_update (plugin->env->stats,
1027                             gettext_noop ("# bytes transmitted via TCP"),
1028                             ret,
1029                             GNUNET_NO);
1030   return ret;
1031 }
1032
1033
1034 /**
1035  * If we have pending messages, ask the server to
1036  * transmit them (schedule the respective tasks, etc.)
1037  *
1038  * @param session for which session should we do this
1039  */
1040 static void
1041 process_pending_messages (struct Session *session)
1042 {
1043   struct PendingMessage *pm;
1044
1045   GNUNET_assert (session->client != NULL);
1046   if (session->transmit_handle != NULL)
1047     return;
1048   if (NULL == (pm = session->pending_messages_head))
1049     return;
1050
1051   session->transmit_handle
1052     = GNUNET_SERVER_notify_transmit_ready (session->client,
1053                                            pm->message_size,
1054                                            GNUNET_TIME_absolute_get_remaining
1055                                            (pm->timeout),
1056                                            &do_transmit, session);
1057 }
1058
1059
1060 /**
1061  * Functions with this signature are called whenever we need
1062  * to close a session due to a disconnect or failure to
1063  * establish a connection.
1064  *
1065  * @param session session to close down
1066  */
1067 static void
1068 disconnect_session (struct Session *session)
1069 {
1070   struct Session *prev;
1071   struct Session *pos;
1072   struct PendingMessage *pm;
1073
1074 #if DEBUG_TCP
1075   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1076                    "tcp",
1077                    "Disconnecting from `%4s' at %s.\n",
1078                    GNUNET_i2s (&session->target),
1079                    (session->connect_addr != NULL) ?
1080                    tcp_address_to_string (session->plugin,
1081                                           session->connect_addr,
1082                                           session->connect_alen) : "*");
1083 #endif
1084   /* remove from session list */
1085   prev = NULL;
1086   pos = session->plugin->sessions;
1087   while (pos != session)
1088     {
1089       prev = pos;
1090       pos = pos->next;
1091     }
1092   if (prev == NULL)
1093     session->plugin->sessions = session->next;
1094   else
1095     prev->next = session->next;
1096
1097   /* clean up state */
1098   if (session->transmit_handle != NULL)
1099     {
1100       GNUNET_CONNECTION_notify_transmit_ready_cancel
1101         (session->transmit_handle);
1102       session->transmit_handle = NULL;
1103     }
1104   while (NULL != (pm = session->pending_messages_head))
1105     {
1106 #if DEBUG_TCP
1107       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1108                        "tcp",
1109                        pm->transmit_cont != NULL
1110                        ? "Could not deliver message to `%4s'.\n"
1111                        : "Could not deliver message to `%4s', notifying.\n",
1112                        GNUNET_i2s (&session->target));
1113 #endif
1114       GNUNET_STATISTICS_update (session->plugin->env->stats,
1115                                 gettext_noop ("# bytes currently in TCP buffers"),
1116                                 - (int64_t) pm->message_size,
1117                                 GNUNET_NO);
1118       GNUNET_STATISTICS_update (session->plugin->env->stats,
1119                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
1120                                 pm->message_size,
1121                                 GNUNET_NO);
1122       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1123                                    session->pending_messages_tail,
1124                                    pm);
1125       if (NULL != pm->transmit_cont)
1126         pm->transmit_cont (pm->transmit_cont_cls,
1127                            &session->target, GNUNET_SYSERR);
1128       GNUNET_free (pm);
1129     }
1130   GNUNET_break (session->client != NULL);
1131   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
1132     {
1133       GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1134       if (session->client != NULL)
1135         GNUNET_SERVER_receive_done (session->client,
1136                                     GNUNET_SYSERR);     
1137     }
1138   else if (session->client != NULL)
1139     GNUNET_SERVER_client_drop (session->client);
1140   GNUNET_STATISTICS_update (session->plugin->env->stats,
1141                             gettext_noop ("# TCP sessions active"),
1142                             -1,
1143                             GNUNET_NO);
1144   GNUNET_free_non_null (session->connect_addr);
1145
1146   session->plugin->env->session_end (session->plugin->env->cls,
1147                                      &session->target,
1148                                      session);
1149
1150   GNUNET_free (session);
1151 }
1152
1153
1154 /**
1155  * Given two otherwise equivalent sessions, pick the better one.
1156  *
1157  * @param s1 one session (also default)
1158  * @param s2 other session
1159  * @return "better" session (more active)
1160  */
1161 static struct Session *
1162 select_better_session (struct Session *s1,
1163                        struct Session *s2)
1164 {
1165   if (s1 == NULL)
1166     return s2;
1167   if (s2 == NULL)
1168     return s1;
1169   if ( (s1->expecting_welcome == GNUNET_NO) &&
1170        (s2->expecting_welcome == GNUNET_YES) )
1171     return s1;
1172   if ( (s1->expecting_welcome == GNUNET_YES) &&
1173        (s2->expecting_welcome == GNUNET_NO) )
1174     return s2;
1175   if (s1->last_activity.abs_value < s2->last_activity.abs_value)
1176     return s2;
1177   if (s1->last_activity.abs_value > s2->last_activity.abs_value)
1178     return s1;
1179   if ( (GNUNET_YES == s1->inbound) &&
1180        (GNUNET_NO  == s2->inbound) )
1181     return s1;
1182   if ( (GNUNET_NO  == s1->inbound) &&
1183        (GNUNET_YES == s2->inbound) )
1184     return s2;
1185   return s1;
1186 }
1187
1188
1189 /**
1190  * We learned about a peer (possibly behind NAT) so run the
1191  * gnunet-nat-client to send dummy ICMP responses.
1192  *
1193  * @param plugin the plugin for this transport
1194  * @param sa the address of the peer (IPv4-only)
1195  */
1196 static void
1197 run_gnunet_nat_client (struct Plugin *plugin, 
1198                        const struct sockaddr_in *sa)
1199 {
1200   char inet4[INET_ADDRSTRLEN];
1201   char port_as_string[6];
1202   struct GNUNET_OS_Process *proc;
1203
1204   if (plugin->internal_address == NULL)
1205     {
1206       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1207                        "tcp",
1208                        _("Internal IP address not known, cannot use ICMP NAT traversal method\n"));
1209       return;
1210     }
1211   GNUNET_assert (sa->sin_family == AF_INET);
1212   if (NULL == inet_ntop (AF_INET,
1213                          &sa->sin_addr,
1214                          inet4, INET_ADDRSTRLEN))
1215     {
1216       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
1217       return;
1218     }
1219   GNUNET_snprintf(port_as_string, 
1220                   sizeof (port_as_string),
1221                   "%d", 
1222                   plugin->adv_port);
1223 #if DEBUG_TCP_NAT
1224   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1225                    "tcp",
1226                    _("Running gnunet-nat-client %s %s %u\n"), 
1227                    plugin->internal_address,
1228                    inet4,
1229                    (unsigned int) plugin->adv_port);
1230 #endif
1231   proc = GNUNET_OS_start_process (NULL, 
1232                                   NULL, 
1233                                   "gnunet-nat-client",
1234                                   "gnunet-nat-client",
1235                                   plugin->internal_address, 
1236                                   inet4,
1237                                   port_as_string, 
1238                                   NULL);
1239   if (NULL == proc)
1240     return;
1241   /* we know that the gnunet-nat-client will terminate virtually
1242      instantly */
1243   GNUNET_OS_process_wait (proc);
1244   GNUNET_OS_process_close (proc);
1245 }
1246
1247
1248 /**
1249  * Function that can be used by the transport service to transmit
1250  * a message using the plugin.   Note that in the case of a
1251  * peer disconnecting, the continuation MUST be called
1252  * prior to the disconnect notification itself.  This function
1253  * will be called with this peer's HELLO message to initiate
1254  * a fresh connection to another peer.
1255  *
1256  * @param cls closure
1257  * @param target who should receive this message
1258  * @param msg the message to transmit
1259  * @param msgbuf_size number of bytes in 'msg'
1260  * @param priority how important is the message (most plugins will
1261  *                 ignore message priority and just FIFO)
1262  * @param timeout how long to wait at most for the transmission (does not
1263  *                require plugins to discard the message after the timeout,
1264  *                just advisory for the desired delay; most plugins will ignore
1265  *                this as well)
1266  * @param session which session must be used (or NULL for "any")
1267  * @param addr the address to use (can be NULL if the plugin
1268  *                is "on its own" (i.e. re-use existing TCP connection))
1269  * @param addrlen length of the address in bytes
1270  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1271  *                GNUNET_NO means the plugin may use any other address and
1272  *                GNUNET_SYSERR means that only reliable existing
1273  *                bi-directional connections should be used (regardless
1274  *                of address)
1275  * @param cont continuation to call once the message has
1276  *        been transmitted (or if the transport is ready
1277  *        for the next transmission call; or if the
1278  *        peer disconnected...); can be NULL
1279  * @param cont_cls closure for cont
1280  * @return number of bytes used (on the physical network, with overheads);
1281  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1282  *         and does NOT mean that the message was not transmitted (DV and NAT)
1283  */
1284 static ssize_t
1285 tcp_plugin_send (void *cls,
1286                  const struct GNUNET_PeerIdentity *target,
1287                  const char *msg,
1288                  size_t msgbuf_size,
1289                  uint32_t priority,
1290                  struct GNUNET_TIME_Relative timeout,
1291                  struct Session *session,
1292                  const void *addr,
1293                  size_t addrlen,
1294                  int force_address,
1295                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1296 {
1297   struct Plugin *plugin = cls;
1298   struct Session *cand_session;
1299   struct Session *next;
1300   struct PendingMessage *pm;
1301   struct GNUNET_CONNECTION_Handle *sa;
1302   int af;
1303   const void *sb;
1304   size_t sbs;
1305   struct sockaddr_in a4;
1306   struct sockaddr_in6 a6;
1307   const struct IPv4TcpAddress *t4;
1308   const struct IPv6TcpAddress *t6;
1309   unsigned int is_natd;
1310
1311   GNUNET_STATISTICS_update (plugin->env->stats,
1312                             gettext_noop ("# bytes TCP was asked to transmit"),
1313                             msgbuf_size,
1314                             GNUNET_NO);
1315   /* FIXME: we could do this cheaper with a hash table
1316      where we could restrict the iteration to entries that match
1317      the target peer... */
1318   is_natd = GNUNET_NO;
1319   if (session == NULL)
1320     {
1321       cand_session = NULL;
1322       next = plugin->sessions;
1323       while (NULL != (session = next))
1324         {
1325           next = session->next;
1326           GNUNET_assert (session->client != NULL);
1327           if (0 != memcmp (target,
1328                            &session->target,
1329                            sizeof (struct GNUNET_PeerIdentity)))
1330             continue;
1331           if ( ( (GNUNET_SYSERR == force_address) &&
1332                  (session->expecting_welcome == GNUNET_NO) ) ||
1333                (GNUNET_NO == force_address) )
1334             {
1335               cand_session = select_better_session (cand_session,
1336                                                     session);
1337               continue;
1338             }
1339           if (GNUNET_SYSERR == force_address)
1340             continue;
1341           GNUNET_break (GNUNET_YES == force_address);
1342           if (addr == NULL)
1343             {
1344               GNUNET_break (0);
1345               break;
1346             }
1347           if ( (addrlen != session->connect_alen) && 
1348                (session->is_nat == GNUNET_NO) )
1349             continue;
1350           if ((0 != memcmp (session->connect_addr,
1351                            addr,
1352                            addrlen)) && (session->is_nat == GNUNET_NO))
1353             continue;
1354           cand_session = select_better_session (cand_session,
1355                                                 session);       
1356         }
1357       session = cand_session;
1358     }
1359   if ( (session == NULL) &&
1360        (addr == NULL) )
1361     {
1362 #if DEBUG_TCP
1363       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1364                        "tcp",
1365                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1366                        GNUNET_i2s (target));
1367 #endif
1368       GNUNET_STATISTICS_update (plugin->env->stats,
1369                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1370                                 msgbuf_size,
1371                                 GNUNET_NO);
1372       return -1;
1373     }
1374   if (session == NULL)
1375     {
1376       if (addrlen == sizeof (struct IPv6TcpAddress))
1377         {
1378           t6 = addr;
1379           af = AF_INET6;
1380           memset (&a6, 0, sizeof (a6));
1381 #if HAVE_SOCKADDR_IN_SIN_LEN
1382           a6.sin6_len = sizeof (a6);
1383 #endif
1384           a6.sin6_family = AF_INET6;
1385           a6.sin6_port = t6->t6_port;
1386           if (t6->t6_port == 0)
1387             is_natd = GNUNET_YES;
1388           memcpy (&a6.sin6_addr,
1389                   &t6->ipv6_addr,
1390                   sizeof (struct in6_addr));
1391           sb = &a6;
1392           sbs = sizeof (a6);
1393         }
1394       else if (addrlen == sizeof (struct IPv4TcpAddress))
1395         {
1396           t4 = addr;
1397           af = AF_INET;
1398           memset (&a4, 0, sizeof (a4));
1399 #if HAVE_SOCKADDR_IN_SIN_LEN
1400           a4.sin_len = sizeof (a4);
1401 #endif
1402           a4.sin_family = AF_INET;
1403           a4.sin_port = t4->t_port;
1404           if (t4->t_port == 0)
1405             is_natd = GNUNET_YES;
1406           a4.sin_addr.s_addr = t4->ipv4_addr;
1407           sb = &a4;
1408           sbs = sizeof (a4);
1409         }
1410       else
1411         {
1412           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1413                            "tcp",
1414                            _("Address of unexpected length: %u\n"),
1415                            addrlen);
1416           GNUNET_break (0);
1417           return -1;
1418         }
1419
1420       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1421         return -1; /* NAT client only works with IPv4 addresses */
1422       if (0 == plugin->max_connections)
1423         return -1; /* saturated */
1424
1425       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1426            (is_natd == GNUNET_YES) &&
1427            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns,
1428                                                                 &target->hashPubKey)) )
1429         {
1430 #if DEBUG_TCP_NAT
1431           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1432                            "tcp",
1433                            _("Found valid IPv4 NAT address (creating session)!\n"));
1434 #endif
1435           session = create_session (plugin,
1436                                     target,
1437                                     NULL, 
1438                                     GNUNET_YES);
1439
1440           /* create new message entry */
1441           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1442           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1443           pm->msg = (const char*) &pm[1];
1444           memcpy (&pm[1], msg, msgbuf_size);
1445           /* FIXME: this memcpy can be up to 7% of our total run-time
1446              (for transport service) */
1447           pm->message_size = msgbuf_size;
1448           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1449           pm->transmit_cont = cont;
1450           pm->transmit_cont_cls = cont_cls;
1451
1452           /* append pm to pending_messages list */
1453           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1454                                              session->pending_messages_tail,
1455                                              session->pending_messages_tail,
1456                                              pm);
1457
1458           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns,
1459                                                           &target->hashPubKey,
1460                                                           session, 
1461                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1462 #if DEBUG_TCP_NAT
1463           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1464                            "tcp",
1465                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1466                            GNUNET_i2s (target),
1467                            GNUNET_a2s (sb, sbs));
1468 #endif
1469           run_gnunet_nat_client (plugin, &a4);
1470           return 0;
1471         }
1472       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1473            (is_natd == GNUNET_YES) && 
1474            (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, 
1475                                                                  &target->hashPubKey)) )
1476         {
1477           /* Only do one NAT punch attempt per peer identity */
1478           return -1;
1479         }
1480       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1481       if (sa == NULL)
1482         {
1483 #if DEBUG_TCP
1484           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1485                            "tcp",
1486                            "Failed to create connection to `%4s' at `%s'\n",
1487                            GNUNET_i2s (target),
1488                            GNUNET_a2s (sb, sbs));
1489 #endif
1490           GNUNET_STATISTICS_update (plugin->env->stats,
1491                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1492                                     msgbuf_size,
1493                                     GNUNET_NO);
1494           return -1;
1495         }
1496       GNUNET_assert (0 != plugin->max_connections);
1497       plugin->max_connections--;
1498 #if DEBUG_TCP_NAT
1499       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1500                        "tcp",
1501                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1502                        GNUNET_i2s (target),
1503                        GNUNET_a2s (sb, sbs));
1504 #endif
1505       session = create_session (plugin,
1506                                 target,
1507                                 GNUNET_SERVER_connect_socket (plugin->server,
1508                                                               sa), 
1509                                 GNUNET_NO);
1510       session->connect_addr = GNUNET_malloc (addrlen);
1511       memcpy (session->connect_addr,
1512               addr,
1513               addrlen);
1514       session->connect_alen = addrlen;
1515     }
1516   GNUNET_assert (session != NULL);
1517   GNUNET_assert (session->client != NULL);
1518   GNUNET_STATISTICS_update (plugin->env->stats,
1519                             gettext_noop ("# bytes currently in TCP buffers"),
1520                             msgbuf_size,
1521                             GNUNET_NO);
1522   /* create new message entry */
1523   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1524   pm->msg = (const char*) &pm[1];
1525   memcpy (&pm[1], msg, msgbuf_size);
1526   pm->message_size = msgbuf_size;
1527   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1528   pm->transmit_cont = cont;
1529   pm->transmit_cont_cls = cont_cls;
1530
1531   /* append pm to pending_messages list */
1532   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1533                                      session->pending_messages_tail,
1534                                      session->pending_messages_tail,
1535                                      pm);
1536 #if DEBUG_TCP
1537   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1538                    "tcp",
1539                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1540                    msgbuf_size,
1541                    GNUNET_i2s (target));
1542 #endif
1543   process_pending_messages (session);
1544   return msgbuf_size;
1545 }
1546
1547
1548 /**
1549  * Function that can be called to force a disconnect from the
1550  * specified neighbour.  This should also cancel all previously
1551  * scheduled transmissions.  Obviously the transmission may have been
1552  * partially completed already, which is OK.  The plugin is supposed
1553  * to close the connection (if applicable) and no longer call the
1554  * transmit continuation(s).
1555  *
1556  * Finally, plugin MUST NOT call the services's receive function to
1557  * notify the service that the connection to the specified target was
1558  * closed after a getting this call.
1559  *
1560  * @param cls closure
1561  * @param target peer for which the last transmission is
1562  *        to be cancelled
1563  */
1564 static void
1565 tcp_plugin_disconnect (void *cls,
1566                        const struct GNUNET_PeerIdentity *target)
1567 {
1568   struct Plugin *plugin = cls;
1569   struct Session *session;
1570   struct Session *next;
1571   struct PendingMessage *pm;
1572
1573 #if DEBUG_TCP
1574   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1575                    "tcp",
1576                    "Asked to cancel session with `%4s'\n",
1577                    GNUNET_i2s (target));
1578 #endif
1579   next = plugin->sessions;
1580   while (NULL != (session = next))
1581     {
1582       next = session->next;
1583       if (0 != memcmp (target,
1584                        &session->target,
1585                        sizeof (struct GNUNET_PeerIdentity)))
1586         continue;
1587       pm = session->pending_messages_head;
1588       while (pm != NULL)
1589         {
1590           pm->transmit_cont = NULL;
1591           pm->transmit_cont_cls = NULL;
1592           pm = pm->next;
1593         }
1594       GNUNET_STATISTICS_update (session->plugin->env->stats,
1595                                 gettext_noop ("# transport-service disconnect requests for TCP"),
1596                                 1,
1597                                 GNUNET_NO);
1598       disconnect_session (session);
1599     }
1600 }
1601
1602
1603 /**
1604  * Context for address to string conversion.
1605  */
1606 struct PrettyPrinterContext
1607 {
1608   /**
1609    * Function to call with the result.
1610    */
1611   GNUNET_TRANSPORT_AddressStringCallback asc;
1612
1613   /**
1614    * Clsoure for 'asc'.
1615    */
1616   void *asc_cls;
1617
1618   /**
1619    * Port to add after the IP address.
1620    */
1621   uint16_t port;
1622 };
1623
1624
1625 /**
1626  * Append our port and forward the result.
1627  *
1628  * @param cls the 'struct PrettyPrinterContext*'
1629  * @param hostname hostname part of the address
1630  */
1631 static void
1632 append_port (void *cls, const char *hostname)
1633 {
1634   struct PrettyPrinterContext *ppc = cls;
1635   char *ret;
1636
1637   if (hostname == NULL)
1638     {
1639       ppc->asc (ppc->asc_cls, NULL);
1640       GNUNET_free (ppc);
1641       return;
1642     }
1643   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1644   ppc->asc (ppc->asc_cls, ret);
1645   GNUNET_free (ret);
1646 }
1647
1648
1649 /**
1650  * Convert the transports address to a nice, human-readable
1651  * format.
1652  *
1653  * @param cls closure
1654  * @param type name of the transport that generated the address
1655  * @param addr one of the addresses of the host, NULL for the last address
1656  *        the specific address format depends on the transport
1657  * @param addrlen length of the address
1658  * @param numeric should (IP) addresses be displayed in numeric form?
1659  * @param timeout after how long should we give up?
1660  * @param asc function to call on each string
1661  * @param asc_cls closure for asc
1662  */
1663 static void
1664 tcp_plugin_address_pretty_printer (void *cls,
1665                                    const char *type,
1666                                    const void *addr,
1667                                    size_t addrlen,
1668                                    int numeric,
1669                                    struct GNUNET_TIME_Relative timeout,
1670                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1671                                    void *asc_cls)
1672 {
1673   struct PrettyPrinterContext *ppc;
1674   const void *sb;
1675   size_t sbs;
1676   struct sockaddr_in a4;
1677   struct sockaddr_in6 a6;
1678   const struct IPv4TcpAddress *t4;
1679   const struct IPv6TcpAddress *t6;
1680   uint16_t port;
1681
1682   if (addrlen == sizeof (struct IPv6TcpAddress))
1683     {
1684       t6 = addr;
1685       memset (&a6, 0, sizeof (a6));
1686       a6.sin6_family = AF_INET6;
1687       a6.sin6_port = t6->t6_port;
1688       memcpy (&a6.sin6_addr,
1689               &t6->ipv6_addr,
1690               sizeof (struct in6_addr));
1691       port = ntohs (t6->t6_port);
1692       sb = &a6;
1693       sbs = sizeof (a6);
1694     }
1695   else if (addrlen == sizeof (struct IPv4TcpAddress))
1696     {
1697       t4 = addr;
1698       memset (&a4, 0, sizeof (a4));
1699       a4.sin_family = AF_INET;
1700       a4.sin_port = t4->t_port;
1701       a4.sin_addr.s_addr = t4->ipv4_addr;
1702       port = ntohs (t4->t_port);
1703       sb = &a4;
1704       sbs = sizeof (a4);
1705     }
1706   else
1707     {
1708       /* invalid address */
1709       GNUNET_break_op (0);
1710       asc (asc_cls, NULL);
1711       return;
1712     }
1713   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1714   ppc->asc = asc;
1715   ppc->asc_cls = asc_cls;
1716   ppc->port = port;
1717   GNUNET_RESOLVER_hostname_get (sb,
1718                                 sbs,
1719                                 !numeric, timeout, &append_port, ppc);
1720 }
1721
1722
1723 /**
1724  * Check if the given port is plausible (must be either our listen
1725  * port or our advertised port), or any port if we are behind NAT
1726  * and do not have a port open.  If it is neither, we return
1727  * GNUNET_SYSERR.
1728  *
1729  * @param plugin global variables
1730  * @param in_port port number to check
1731  * @return GNUNET_OK if port is either open_port or adv_port
1732  */
1733 static int
1734 check_port (struct Plugin *plugin, 
1735             uint16_t in_port)
1736 {
1737   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1738     return GNUNET_OK;
1739   return GNUNET_SYSERR;
1740 }
1741
1742
1743 /**
1744  * Function that will be called to check if a binary address for this
1745  * plugin is well-formed and corresponds to an address for THIS peer
1746  * (as per our configuration).  Naturally, if absolutely necessary,
1747  * plugins can be a bit conservative in their answer, but in general
1748  * plugins should make sure that the address does not redirect
1749  * traffic to a 3rd party that might try to man-in-the-middle our
1750  * traffic.
1751  *
1752  * @param cls closure, our 'struct Plugin*'
1753  * @param addr pointer to the address
1754  * @param addrlen length of addr
1755  * @return GNUNET_OK if this is a plausible address for this peer
1756  *         and transport, GNUNET_SYSERR if not
1757  */
1758 static int
1759 tcp_plugin_check_address (void *cls,
1760                           const void *addr,
1761                           size_t addrlen)
1762 {
1763   struct Plugin *plugin = cls;
1764   struct IPv4TcpAddress *v4;
1765   struct IPv6TcpAddress *v6;
1766
1767   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1768       (addrlen != sizeof (struct IPv6TcpAddress)))
1769     {
1770       GNUNET_break_op (0);
1771       return GNUNET_SYSERR;
1772     }
1773   if (addrlen == sizeof (struct IPv4TcpAddress))
1774     {
1775       v4 = (struct IPv4TcpAddress *) addr;
1776       if (GNUNET_OK ==
1777           check_mapped_addr (plugin, v4, sizeof (struct IPv4TcpAddress)))
1778         return GNUNET_OK;
1779       if (GNUNET_OK !=
1780           check_port (plugin, ntohs (v4->t_port)))
1781         return GNUNET_SYSERR;
1782       if (GNUNET_OK !=
1783           check_local_addr (plugin, &v4->ipv4_addr, sizeof (struct in_addr)))
1784         return GNUNET_SYSERR;   
1785     }
1786   else
1787     {
1788       v6 = (struct IPv6TcpAddress *) addr;
1789       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1790         {
1791           GNUNET_break_op (0);
1792           return GNUNET_SYSERR;
1793         }
1794       if (GNUNET_OK ==
1795           check_mapped_addr (plugin, v6, sizeof (struct IPv6TcpAddress)))
1796         return GNUNET_OK;
1797       if (GNUNET_OK !=
1798           check_port (plugin, ntohs (v6->t6_port)))
1799         return GNUNET_SYSERR;
1800       if (GNUNET_OK !=
1801           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1802         return GNUNET_SYSERR;
1803     }
1804   return GNUNET_OK;
1805 }
1806
1807
1808 /**
1809  * We've received a nat probe from this peer via TCP.  Finish
1810  * creating the client session and resume sending of queued
1811  * messages.
1812  *
1813  * @param cls closure
1814  * @param client identification of the client
1815  * @param message the actual message
1816  */
1817 static void
1818 handle_tcp_nat_probe (void *cls,
1819                       struct GNUNET_SERVER_Client *client,
1820                       const struct GNUNET_MessageHeader *message)
1821 {
1822   struct Plugin *plugin = cls;
1823   struct Session *session;
1824   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1825   size_t alen;
1826   void *vaddr;
1827   struct IPv4TcpAddress *t4;
1828   struct IPv6TcpAddress *t6;
1829   const struct sockaddr_in *s4;
1830   const struct sockaddr_in6 *s6;
1831
1832 #if DEBUG_TCP_NAT
1833   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1834                    "tcp",
1835                    "received NAT probe\n");
1836 #endif
1837   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1838    * a connection to this peer by running gnunet-nat-client.  This peer
1839    * received the punch message and now wants us to use the new connection
1840    * as the default for that peer.  Do so and then send a WELCOME message
1841    * so we can really be connected!
1842    */
1843   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1844     {
1845       GNUNET_break_op(0);
1846       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1847       return;
1848     }
1849
1850   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *)message;
1851
1852   if (0 == memcmp (&tcp_nat_probe->clientIdentity,
1853                    plugin->env->my_identity,
1854                    sizeof (struct GNUNET_PeerIdentity)))
1855     {
1856       /* refuse connections from ourselves */
1857       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1858       return;
1859     }
1860
1861   session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, 
1862                                               &tcp_nat_probe->clientIdentity.hashPubKey);
1863   if (session == NULL)
1864     {
1865 #if DEBUG_TCP_NAT
1866       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1867                        "tcp",
1868                        "Did NOT find session for NAT probe!\n");
1869 #endif
1870       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1871       return;
1872     }
1873 #if DEBUG_TCP_NAT
1874   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1875                    "tcp",
1876                    "Found session for NAT probe!\n");
1877 #endif
1878   GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, 
1879                                                      &tcp_nat_probe->clientIdentity.hashPubKey,
1880                                                      session) == GNUNET_YES);
1881   if (GNUNET_OK !=
1882       GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1883     {
1884       GNUNET_break (0);
1885       GNUNET_free (session);
1886       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1887       return;
1888     }
1889
1890   GNUNET_SERVER_client_keep (client);
1891   session->client = client;
1892   session->last_activity = GNUNET_TIME_absolute_get ();
1893   session->inbound = GNUNET_NO;
1894
1895 #if DEBUG_TCP_NAT
1896   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1897                    "tcp",
1898                    "Found address `%s' for incoming connection\n",
1899                    GNUNET_a2s (vaddr, alen));
1900 #endif
1901   switch (((const struct sockaddr *)vaddr)->sa_family)
1902     {
1903     case AF_INET:
1904       s4 = vaddr;
1905       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1906       t4->t_port = s4->sin_port;
1907       t4->ipv4_addr = s4->sin_addr.s_addr;
1908       session->connect_addr = t4;
1909       session->connect_alen = sizeof (struct IPv4TcpAddress);
1910       break;
1911     case AF_INET6:    
1912       s6 = vaddr;
1913       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1914       t6->t6_port = s6->sin6_port;
1915       memcpy (&t6->ipv6_addr,
1916               &s6->sin6_addr,
1917               sizeof (struct in6_addr));
1918       session->connect_addr = t6;
1919       session->connect_alen = sizeof (struct IPv6TcpAddress);
1920       break;
1921     default:
1922       GNUNET_break_op (0);
1923 #if DEBUG_TCP_NAT
1924       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1925                        "tcp",
1926                        "Bad address for incoming connection!\n");
1927 #endif
1928       GNUNET_free (vaddr);
1929       GNUNET_SERVER_client_drop (client);
1930       GNUNET_free (session);
1931       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1932       return;
1933     }
1934   GNUNET_free (vaddr);
1935   
1936   session->next = plugin->sessions;
1937   plugin->sessions = session;
1938   GNUNET_STATISTICS_update (plugin->env->stats,
1939                             gettext_noop ("# TCP sessions active"),
1940                             1,
1941                             GNUNET_NO);
1942   process_pending_messages (session);
1943   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1944 }
1945
1946
1947 /**
1948  * We've received a welcome from this peer via TCP.  Possibly create a
1949  * fresh client record and send back our welcome.
1950  *
1951  * @param cls closure
1952  * @param client identification of the client
1953  * @param message the actual message
1954  */
1955 static void
1956 handle_tcp_welcome (void *cls,
1957                     struct GNUNET_SERVER_Client *client,
1958                     const struct GNUNET_MessageHeader *message)
1959 {
1960   struct Plugin *plugin = cls;
1961   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1962   struct Session *session;
1963   size_t alen;
1964   void *vaddr;
1965   struct IPv4TcpAddress *t4;
1966   struct IPv6TcpAddress *t6;
1967   const struct sockaddr_in *s4;
1968   const struct sockaddr_in6 *s6;
1969   
1970   if (0 == memcmp (&wm->clientIdentity,
1971                    plugin->env->my_identity,
1972                    sizeof (struct GNUNET_PeerIdentity)))
1973     {
1974       /* refuse connections from ourselves */
1975       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1976       return;
1977     }
1978 #if DEBUG_TCP
1979   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1980                    "tcp",
1981                    "Received %s message from `%4s'.\n",
1982                    "WELCOME",
1983                    GNUNET_i2s (&wm->clientIdentity));
1984 #endif
1985   GNUNET_STATISTICS_update (plugin->env->stats,
1986                             gettext_noop ("# TCP WELCOME messages received"),
1987                             1,
1988                             GNUNET_NO);
1989   session = find_session_by_client (plugin, client);
1990
1991   if (session == NULL)
1992     {
1993 #if DEBUG_TCP_NAT
1994       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1995                        "tcp",
1996                        "Received %s message from a `%4s', creating new session\n",
1997                        "WELCOME",
1998                        GNUNET_i2s (&wm->clientIdentity));
1999 #endif
2000       GNUNET_SERVER_client_keep (client);
2001       session = create_session (plugin,
2002                                 &wm->clientIdentity,
2003                                 client,
2004                                 GNUNET_NO);
2005       session->inbound = GNUNET_YES;
2006       if (GNUNET_OK ==
2007           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2008         {
2009 #if DEBUG_TCP_NAT
2010           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2011                            "tcp",
2012                            "Found address `%s' for incoming connection\n",
2013                            GNUNET_a2s (vaddr, alen));
2014 #endif
2015           if (alen == sizeof (struct sockaddr_in))
2016             {
2017               s4 = vaddr;
2018               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
2019               t4->t_port = s4->sin_port;
2020               t4->ipv4_addr = s4->sin_addr.s_addr;
2021               session->connect_addr = t4;
2022               session->connect_alen = sizeof (struct IPv4TcpAddress);
2023             }
2024           else if (alen == sizeof (struct sockaddr_in6))
2025             {
2026               s6 = vaddr;
2027               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
2028               t6->t6_port = s6->sin6_port;
2029               memcpy (&t6->ipv6_addr,
2030                       &s6->sin6_addr,
2031                       sizeof (struct in6_addr));
2032               session->connect_addr = t6;
2033               session->connect_alen = sizeof (struct IPv6TcpAddress);
2034             }
2035
2036           GNUNET_free (vaddr);
2037         }
2038       else
2039         {
2040 #if DEBUG_TCP
2041           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2042                            "tcp",
2043                            "Did not obtain TCP socket address for incoming connection\n");
2044 #endif
2045         }
2046       process_pending_messages (session);
2047     }
2048   else
2049     {
2050 #if DEBUG_TCP_NAT
2051     if (GNUNET_OK ==
2052         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
2053       {
2054         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2055                          "tcp",
2056                          "Found address `%s' (already have session)\n",
2057                          GNUNET_a2s (vaddr, alen));
2058         GNUNET_free (vaddr);
2059       }
2060 #endif
2061     }
2062
2063   if (session->expecting_welcome != GNUNET_YES)
2064     {
2065       GNUNET_break_op (0);
2066       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2067       return;
2068     }
2069   session->last_activity = GNUNET_TIME_absolute_get ();
2070   session->expecting_welcome = GNUNET_NO;
2071   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2072 }
2073
2074
2075 /**
2076  * Task to signal the server that we can continue
2077  * receiving from the TCP client now.
2078  *
2079  * @param cls the 'struct Session*'
2080  * @param tc task context (unused)
2081  */
2082 static void
2083 delayed_done (void *cls, 
2084               const struct GNUNET_SCHEDULER_TaskContext *tc)
2085 {
2086   struct Session *session = cls;
2087   struct GNUNET_TIME_Relative delay;
2088
2089   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2090   delay = session->plugin->env->receive (session->plugin->env->cls,
2091                                          &session->target,
2092                                          NULL,
2093                                          NULL, 0,
2094                                          session,
2095                                          NULL, 0);
2096   if (delay.rel_value == 0)
2097     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2098   else
2099     session->receive_delay_task =
2100       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2101 }
2102
2103
2104 /**
2105  * We've received data for this peer via TCP.  Unbox,
2106  * compute latency and forward.
2107  *
2108  * @param cls closure
2109  * @param client identification of the client
2110  * @param message the actual message
2111  */
2112 static void
2113 handle_tcp_data (void *cls,
2114                  struct GNUNET_SERVER_Client *client,
2115                  const struct GNUNET_MessageHeader *message)
2116 {
2117   struct Plugin *plugin = cls;
2118   struct Session *session;
2119   struct GNUNET_TIME_Relative delay;
2120   uint16_t type;
2121
2122   type = ntohs (message->type);
2123   if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) || 
2124        (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
2125     {
2126       /* We don't want to propagate WELCOME and NAT Probe messages up! */
2127       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2128       return;
2129     }
2130   session = find_session_by_client (plugin, client);
2131   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome) )
2132     {
2133       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2134       return;
2135     }
2136   session->last_activity = GNUNET_TIME_absolute_get ();
2137 #if DEBUG_TCP > 1
2138   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2139                    "tcp",
2140                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2141                    (unsigned int) ntohs (message->size),
2142                    (unsigned int) ntohs (message->type),
2143                    GNUNET_i2s (&session->target));
2144 #endif
2145   GNUNET_STATISTICS_update (plugin->env->stats,
2146                             gettext_noop ("# bytes received via TCP"),
2147                             ntohs (message->size),
2148                             GNUNET_NO);
2149   struct GNUNET_TRANSPORT_ATS_Information distance[2];
2150   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2151   distance[0].value = htonl (1);
2152   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2153   distance[1].value = htonl (0);
2154   delay = plugin->env->receive (plugin->env->cls, &session->target, message,
2155                                 (const struct GNUNET_TRANSPORT_ATS_Information *) &distance,
2156                                 2,
2157                                 session,
2158                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
2159                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
2160   if (delay.rel_value == 0)
2161     {
2162       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2163     }
2164   else
2165     {
2166 #if DEBUG_TCP 
2167       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2168                        "tcp",
2169                        "Throttling receiving from `%s' for %llu ms\n",
2170                        GNUNET_i2s (&session->target),
2171                        (unsigned long long) delay.rel_value);
2172 #endif
2173       GNUNET_SERVER_disable_receive_done_warning (client);
2174       session->receive_delay_task =
2175         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2176     }
2177 }
2178
2179
2180 /**
2181  * Functions with this signature are called whenever a peer
2182  * is disconnected on the network level.
2183  *
2184  * @param cls closure
2185  * @param client identification of the client
2186  */
2187 static void
2188 disconnect_notify (void *cls,
2189                    struct GNUNET_SERVER_Client *client)
2190 {
2191   struct Plugin *plugin = cls;
2192   struct Session *session;
2193
2194   if (client == NULL)
2195     return;
2196   plugin->max_connections++;
2197   session = find_session_by_client (plugin, client);
2198   if (session == NULL)
2199     return;                     /* unknown, nothing to do */
2200 #if DEBUG_TCP
2201   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2202                    "tcp",
2203                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2204                    GNUNET_i2s (&session->target),
2205                    (session->connect_addr != NULL) ?
2206                    tcp_address_to_string (session->plugin,
2207                                           session->connect_addr,
2208                                           session->connect_alen) : "*");
2209 #endif
2210   GNUNET_STATISTICS_update (session->plugin->env->stats,
2211                             gettext_noop ("# network-level TCP disconnect events"),
2212                             1,
2213                             GNUNET_NO);
2214   disconnect_session (session);
2215 }
2216
2217
2218 static int check_localaddress (const struct sockaddr *addr, socklen_t addrlen)
2219 {
2220         uint32_t res = 0;
2221         int local = GNUNET_NO;
2222         int af = addr->sa_family;
2223     switch (af)
2224     {
2225       case AF_INET:
2226       {
2227           uint32_t netmask = 0x7F000000;
2228           uint32_t address = ntohl (((struct sockaddr_in *) addr)->sin_addr.s_addr);
2229           res = (address >> 24) ^ (netmask >> 24);
2230           if (res != 0)
2231                   local = GNUNET_NO;
2232           else
2233                   local = GNUNET_YES;
2234 #if DEBUG_TCP
2235             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236                           "Checking IPv4 address `%s': %s\n", GNUNET_a2s (addr, addrlen), (local==GNUNET_YES) ? "local" : "global");
2237 #endif
2238             break;
2239       }
2240       case AF_INET6:
2241       {
2242            if (IN6_IS_ADDR_LOOPBACK  (&((struct sockaddr_in6 *) addr)->sin6_addr) ||
2243                    IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
2244                    local = GNUNET_YES;
2245            else
2246                    local = GNUNET_NO;
2247 #if DEBUG_TCP
2248            GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2249                           "Checking IPv6 address `%s' : %s\n", GNUNET_a2s (addr, addrlen), (local==GNUNET_YES) ? "local" : "global");
2250 #endif
2251            break;
2252       }
2253     }
2254         return local;
2255 }
2256
2257 /**
2258  * Add the IP of our network interface to the list of
2259  * our internal IP addresses.
2260  *
2261  * @param cls the 'struct Plugin*'
2262  * @param name name of the interface
2263  * @param isDefault do we think this may be our default interface
2264  * @param addr address of the interface
2265  * @param addrlen number of bytes in addr
2266  * @return GNUNET_OK to continue iterating
2267  */
2268 static int
2269 process_interfaces (void *cls,
2270                     const char *name,
2271                     int isDefault,
2272                     const struct sockaddr *addr, socklen_t addrlen)
2273 {
2274   struct Plugin *plugin = cls;
2275   int af;
2276   struct IPv4TcpAddress t4;
2277   struct IPv6TcpAddress t6;
2278   struct IPv4TcpAddress t4_nat;
2279   struct IPv6TcpAddress t6_nat;
2280   void *arg;
2281   uint16_t args;
2282   void *arg_nat;
2283   char buf[INET6_ADDRSTRLEN];
2284
2285   af = addr->sa_family;
2286   arg_nat = NULL;
2287
2288   if (plugin->use_localaddresses == GNUNET_NO)
2289   {
2290           if (GNUNET_YES == check_localaddress (addr, addrlen))
2291           {
2292 #if DEBUG_TCP
2293           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2294                            "tcp",
2295                            "Not notifying transport of address `%s' (local address)\n",
2296                            GNUNET_a2s (addr, addrlen));
2297 #endif
2298                   return GNUNET_OK;
2299           }
2300   }
2301
2302   switch (af)
2303     {
2304     case AF_INET:
2305       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2306       GNUNET_assert (NULL != inet_ntop(AF_INET, 
2307                                        &t4.ipv4_addr, 
2308                                        buf, 
2309                                        sizeof (buf)));
2310       if ( (plugin->bind_address != NULL) && 
2311            (0 != strcmp(buf, plugin->bind_address)) )
2312         {
2313 #if DEBUG_TCP
2314           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2315                            "tcp",
2316                            "Not notifying transport of address `%s' (does not match bind address)\n",
2317                            GNUNET_a2s (addr, addrlen));
2318 #endif
2319           return GNUNET_OK;
2320         }
2321       if ( (plugin->internal_address == NULL) &&
2322            (isDefault) )        
2323         plugin->internal_address = GNUNET_strdup (buf); 
2324       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (struct in_addr));
2325       if (plugin->behind_nat == GNUNET_YES) 
2326         {
2327           /* Also advertise as NAT (with port 0) */
2328           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2329           t4_nat.t_port = htons(0);
2330           arg_nat = &t4_nat;
2331         }       
2332       t4.t_port = htons (plugin->adv_port);     
2333       arg = &t4;
2334       args = sizeof (t4);
2335       break;
2336     case AF_INET6:      
2337       if ( (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || 
2338            (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, 
2339                                                                "nat", 
2340                                                                "DISABLEV6")) )
2341         {
2342           /* skip link local addresses */
2343           return GNUNET_OK;
2344         }
2345       memcpy (&t6.ipv6_addr,
2346               &((struct sockaddr_in6 *) addr)->sin6_addr,
2347               sizeof (struct in6_addr));
2348
2349       /* check bind address */
2350       GNUNET_assert (NULL != inet_ntop(AF_INET6,
2351                                        &t6.ipv6_addr,
2352                                        buf,
2353                                        sizeof (buf)));
2354
2355       if ( (plugin->bind_address != NULL) &&
2356            (0 != strcmp(buf, plugin->bind_address)) )
2357         {
2358 #if DEBUG_TCP
2359           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2360                            "tcp",
2361                            "Not notifying transport of address `%s' (does not match bind address)\n",
2362                            GNUNET_a2s (addr, addrlen));
2363 #endif
2364           return GNUNET_OK;
2365         }
2366
2367       add_to_address_list (plugin, 
2368                            &t6.ipv6_addr, 
2369                            sizeof (struct in6_addr));
2370       if (plugin->behind_nat == GNUNET_YES)
2371         {
2372           /* Also advertise as NAT (with port 0) */
2373           memcpy (&t6_nat.ipv6_addr,
2374                   &((struct sockaddr_in6 *) addr)->sin6_addr,
2375                   sizeof (struct in6_addr));
2376           t6_nat.t6_port = htons(0);
2377           arg_nat = &t6;
2378         }
2379       t6.t6_port = htons (plugin->adv_port);
2380       arg = &t6;
2381       args = sizeof (t6);
2382       break;
2383     default:
2384       GNUNET_break (0);
2385       return GNUNET_OK;
2386     }
2387   if (plugin->adv_port != 0)
2388   {
2389 #if DEBUG_TCP
2390   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2391                    "tcp",
2392                    "Found address `%s' (%s) len %d\n",
2393                    GNUNET_a2s (addr, addrlen), name, args);
2394 #endif
2395   plugin->env->notify_address (plugin->env->cls,
2396                                "tcp",
2397                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
2398   }
2399
2400   if (arg_nat != NULL)
2401     {
2402       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2403                        "tcp",
2404                        _("Found address `%s' (%s) len %d\n"),
2405                        GNUNET_a2s (addr, addrlen), name, args);
2406       plugin->env->notify_address (plugin->env->cls,
2407                                    "tcp",
2408                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
2409     }
2410
2411   return GNUNET_OK;
2412 }
2413
2414
2415 /**
2416  * Function called by the resolver for each address obtained from DNS
2417  * for our own hostname.  Add the addresses to the list of our
2418  * external IP addresses.
2419  *
2420  * @param cls closure
2421  * @param addr one of the addresses of the host, NULL for the last address
2422  * @param addrlen length of the address
2423  */
2424 static void
2425 process_hostname_ips (void *cls,
2426                       const struct sockaddr *addr, socklen_t addrlen)
2427 {
2428   struct Plugin *plugin = cls;
2429
2430   if (addr == NULL)
2431     {
2432       plugin->hostname_dns = NULL;
2433       return;
2434     }
2435   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
2436   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
2437 }
2438
2439
2440 /**
2441  * We can now send a probe message, copy into buffer to really send.
2442  *
2443  * @param cls closure, a struct TCPProbeContext
2444  * @param size max size to copy
2445  * @param buf buffer to copy message to
2446  * @return number of bytes copied into buf
2447  */
2448 static size_t
2449 notify_send_probe (void *cls,
2450                    size_t size,
2451                    void *buf)
2452 {
2453   struct TCPProbeContext *tcp_probe_ctx = cls;
2454   struct Plugin *plugin = tcp_probe_ctx->plugin;
2455   size_t ret;
2456
2457   tcp_probe_ctx->transmit_handle = NULL;
2458   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2459                                plugin->probe_tail,
2460                                tcp_probe_ctx);
2461   if (buf == NULL)
2462     {
2463       GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2464       GNUNET_free(tcp_probe_ctx);
2465       return 0;    
2466     }
2467   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2468   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2469   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2470                                 tcp_probe_ctx->sock);
2471   ret = sizeof(tcp_probe_ctx->message);
2472   GNUNET_free(tcp_probe_ctx);
2473   return ret;
2474 }
2475
2476
2477 /**
2478  * We have been notified that gnunet-nat-server has written something to stdout.
2479  * Handle the output, then reschedule this function to be called again once
2480  * more is available.
2481  *
2482  * @param cls the plugin handle
2483  * @param tc the scheduling context
2484  */
2485 static void
2486 tcp_plugin_server_read (void *cls, 
2487                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2488 {
2489   struct Plugin *plugin = cls;
2490   char mybuf[40];
2491   ssize_t bytes;
2492   size_t i;
2493   int port;
2494   const char *port_start;
2495   struct sockaddr_in sin_addr;
2496   struct TCPProbeContext *tcp_probe_ctx;
2497   struct GNUNET_CONNECTION_Handle *sock;
2498
2499   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
2500     return;
2501   memset (mybuf, 0, sizeof(mybuf));
2502   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, 
2503                                 mybuf,
2504                                 sizeof(mybuf));
2505   if (bytes < 1)
2506     {
2507 #if DEBUG_TCP_NAT
2508       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2509                        "tcp",
2510                        "Finished reading from server stdout with code: %d\n", 
2511                        bytes);
2512 #endif
2513       /* FIXME: consider process_wait here? */
2514       return;
2515     }
2516
2517   port_start = NULL;
2518   for (i = 0; i < sizeof(mybuf); i++)
2519     {
2520       if (mybuf[i] == '\n')
2521         {
2522           mybuf[i] = '\0';
2523           break;
2524         }
2525       if ( (mybuf[i] == ':') && (i + 1 < sizeof(mybuf)) )
2526         {
2527           mybuf[i] = '\0';
2528           port_start = &mybuf[i + 1];
2529         }
2530     }
2531
2532   /* construct socket address of sender */
2533   memset (&sin_addr, 0, sizeof (sin_addr));
2534   sin_addr.sin_family = AF_INET;
2535 #if HAVE_SOCKADDR_IN_SIN_LEN
2536   sin_addr.sin_len = sizeof (sin_addr);
2537 #endif
2538   if ( (NULL == port_start) ||
2539        (1 != sscanf (port_start, "%d", &port)) ||
2540        (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr)) )
2541     {
2542       /* should we restart gnunet-nat-server? */
2543       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2544                        "tcp",
2545                        _("gnunet-nat-server generated malformed address `%s'\n"),
2546                        mybuf);
2547       plugin->server_read_task 
2548         = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2549                                           plugin->server_stdout_handle,
2550                                           &tcp_plugin_server_read, 
2551                                           plugin);
2552       return;
2553     }
2554   sin_addr.sin_port = htons((uint16_t) port);
2555 #if DEBUG_TCP_NAT
2556   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2557                    "tcp",
2558                    "gnunet-nat-server read: %s:%d\n", 
2559                    mybuf, port);
2560 #endif
2561
2562   /**
2563    * We have received an ICMP response, ostensibly from a peer
2564    * that wants to connect to us! Send a message to establish a connection.
2565    */
2566   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, 
2567                                                  (const struct sockaddr *)&sin_addr,
2568                                                  sizeof (sin_addr));
2569   if (sock == NULL)
2570     {
2571       /* failed for some odd reason (out of sockets?); ignore attempt */
2572       plugin->server_read_task =
2573           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2574                                           plugin->server_stdout_handle, 
2575                                           &tcp_plugin_server_read, 
2576                                           plugin);
2577       return;
2578     }
2579
2580   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2581                    "Sending TCP probe message to `%s:%u'!\n", 
2582                    mybuf,
2583                    (unsigned int) port);  
2584   /* FIXME: do we need to track these probe context objects so that
2585      we can clean them up on plugin unload? */
2586   tcp_probe_ctx
2587     = GNUNET_malloc(sizeof(struct TCPProbeContext));
2588   tcp_probe_ctx->message.header.size
2589     = htons(sizeof(struct TCP_NAT_ProbeMessage));
2590   tcp_probe_ctx->message.header.type
2591     = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2592   memcpy (&tcp_probe_ctx->message.clientIdentity,
2593           plugin->env->my_identity,
2594           sizeof(struct GNUNET_PeerIdentity));
2595   tcp_probe_ctx->plugin = plugin;
2596   tcp_probe_ctx->sock = sock;
2597   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2598                                plugin->probe_tail,
2599                                tcp_probe_ctx);
2600   tcp_probe_ctx->transmit_handle 
2601     = GNUNET_CONNECTION_notify_transmit_ready (sock,
2602                                                ntohs (tcp_probe_ctx->message.header.size),
2603                                                GNUNET_TIME_UNIT_FOREVER_REL,
2604                                                &notify_send_probe, tcp_probe_ctx);
2605   
2606   plugin->server_read_task =
2607       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2608                                       plugin->server_stdout_handle,
2609                                       &tcp_plugin_server_read,
2610                                       plugin);
2611 }
2612
2613
2614 /**
2615  * Start the gnunet-nat-server process for users behind NAT.
2616  *
2617  * @param plugin the transport plugin
2618  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2619  */
2620 static int
2621 tcp_transport_start_nat_server (struct Plugin *plugin)
2622 {
2623   if (plugin->internal_address == NULL)
2624     return GNUNET_SYSERR;
2625   plugin->server_stdout = GNUNET_DISK_pipe (GNUNET_YES,
2626                                             GNUNET_NO,
2627                                             GNUNET_YES);
2628   if (plugin->server_stdout == NULL)
2629     return GNUNET_SYSERR;
2630 #if DEBUG_TCP_NAT
2631   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2632                    "tcp"
2633                    "Starting %s %s\n", "gnunet-nat-server", plugin->internal_address);
2634 #endif
2635   /* Start the server process */
2636   plugin->server_proc = GNUNET_OS_start_process (NULL,
2637                                                  plugin->server_stdout,
2638                                                  "gnunet-nat-server", 
2639                                                  "gnunet-nat-server", 
2640                                                  plugin->internal_address, 
2641                                                  NULL);
2642   if (plugin->server_proc == NULL)
2643     {
2644       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2645                        "tcp",
2646                        _("Failed to start %s\n"),
2647                        "gnunet-nat-server");
2648       GNUNET_DISK_pipe_close (plugin->server_stdout);
2649       plugin->server_stdout = NULL;    
2650       return GNUNET_SYSERR;
2651     }
2652   /* Close the write end of the read pipe */
2653   GNUNET_DISK_pipe_close_end(plugin->server_stdout, 
2654                              GNUNET_DISK_PIPE_END_WRITE);
2655   plugin->server_stdout_handle 
2656     = GNUNET_DISK_pipe_handle (plugin->server_stdout, 
2657                                GNUNET_DISK_PIPE_END_READ);
2658   plugin->server_read_task 
2659     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2660                                       plugin->server_stdout_handle,
2661                                       &tcp_plugin_server_read, 
2662                                       plugin);
2663   return GNUNET_YES;
2664 }
2665
2666
2667 /**
2668  * Return the actual path to a file found in the current
2669  * PATH environment variable.
2670  *
2671  * @param binary the name of the file to find
2672  * @return path to binary, NULL if not found
2673  */
2674 static char *
2675 get_path_from_PATH (const char *binary)
2676 {
2677   char *path;
2678   char *pos;
2679   char *end;
2680   char *buf;
2681   const char *p;
2682
2683   p = getenv ("PATH");
2684   if (p == NULL)
2685     {
2686       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2687                        "tcp",
2688                        _("PATH environment variable is unset.\n"));
2689       return NULL;
2690     }
2691   path = GNUNET_strdup (p);     /* because we write on it */
2692   buf = GNUNET_malloc (strlen (path) + 20);
2693   pos = path;
2694
2695   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
2696     {
2697       *end = '\0';
2698       sprintf (buf, "%s/%s", pos, binary);
2699       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2700         {
2701           GNUNET_free (path);
2702           return buf;
2703         }
2704       pos = end + 1;
2705     }
2706   sprintf (buf, "%s/%s", pos, binary);
2707   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2708     {
2709       GNUNET_free (path);
2710       return buf;
2711     }
2712   GNUNET_free (buf);
2713   GNUNET_free (path);
2714   return NULL;
2715 }
2716
2717
2718 /**
2719  * Check whether the suid bit is set on a file.
2720  * Attempts to find the file using the current
2721  * PATH environment variable as a search path.
2722  *
2723  * @param binary the name of the file to check
2724  * @return GNUNET_YES if the file is SUID, 
2725  *         GNUNET_NO if not, 
2726  *         GNUNET_SYSERR on error
2727  */
2728 static int
2729 check_gnunet_nat_binary (const char *binary)
2730 {
2731   struct stat statbuf;
2732   char *p;
2733 #ifdef MINGW
2734   SOCKET rawsock;
2735   char *binaryexe;
2736
2737   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
2738   p = get_path_from_PATH (binaryexe);
2739   free (binaryexe);
2740 #else
2741   p = get_path_from_PATH (binary);
2742 #endif
2743   if (p == NULL)
2744     {
2745       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2746                        "tcp",
2747                        _("Could not find binary `%s' in PATH!\n"),
2748                        binary);
2749       return GNUNET_NO;
2750     }
2751   if (0 != STAT (p, &statbuf))
2752     {
2753       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
2754                   _("stat (%s) failed: %s\n"), 
2755                   p,
2756                   STRERROR (errno));
2757       GNUNET_free (p);
2758       return GNUNET_SYSERR;
2759     }
2760   GNUNET_free (p);
2761 #ifndef MINGW
2762   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2763        (statbuf.st_uid == 0) )
2764     return GNUNET_YES;
2765   return GNUNET_NO;
2766 #else
2767   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
2768   if (INVALID_SOCKET == rawsock)
2769     {
2770       DWORD err = GetLastError ();
2771       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
2772                        "tcp",
2773                        "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
2774       return GNUNET_NO; /* not running as administrator */
2775     }
2776   closesocket (rawsock);
2777   return GNUNET_YES;
2778 #endif
2779 }
2780
2781
2782 /**
2783  * Our (external) hostname was resolved.
2784  *
2785  * @param cls the 'struct Plugin'
2786  * @param addr NULL on error, otherwise result of DNS lookup
2787  * @param addrlen number of bytes in addr
2788  */
2789 static void
2790 process_external_ip (void *cls,
2791                      const struct sockaddr *addr,
2792                      socklen_t addrlen)
2793 {
2794   struct Plugin *plugin = cls;
2795   const struct sockaddr_in *s;
2796   struct IPv4TcpAddress t4;
2797   char buf[INET_ADDRSTRLEN];
2798
2799   plugin->ext_dns = NULL;
2800   if (addr == NULL)
2801     return;
2802   GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2803   s = (const struct sockaddr_in *) addr;
2804   t4.ipv4_addr = s->sin_addr.s_addr;
2805   if ( (plugin->behind_nat == GNUNET_YES) &&
2806        (plugin->enable_nat_server == GNUNET_YES) )
2807     {
2808       t4.t_port = htons(0);
2809       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2810                        "tcp",
2811                        "Notifying transport of address %s:%d\n",
2812                        plugin->external_address,
2813                        0);
2814     }
2815   else
2816     {
2817       t4.t_port = htons(plugin->adv_port);
2818       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2819                        "tcp",
2820                        "Notifying transport of address %s:%d\n",
2821                        plugin->external_address, 
2822                        (int) plugin->adv_port);
2823     }
2824
2825   if ((plugin->bind_address != NULL) && (plugin->behind_nat == GNUNET_NO))
2826   {
2827       GNUNET_assert (NULL != inet_ntop(AF_INET,
2828                                        &t4.ipv4_addr,
2829                                        buf,
2830                                        sizeof (buf)));
2831       if (0 != strcmp (plugin->bind_address, buf))
2832       {
2833       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2834                        "tcp",
2835                        "NAT is not enabled and specific bind address `%s' differs from external address `%s'! Not notifying about external address `%s'\n",
2836                        plugin->bind_address,
2837                        plugin->external_address,
2838                        plugin->external_address);
2839       return;
2840       }
2841   }
2842
2843   add_to_address_list (plugin, 
2844                        &t4.ipv4_addr, 
2845                        sizeof (struct in_addr));
2846
2847   plugin->env->notify_address (plugin->env->cls,
2848                                "tcp",
2849                                &t4, sizeof(t4),
2850                                GNUNET_TIME_UNIT_FOREVER_REL);
2851 }
2852
2853
2854 /**
2855  * Entry point for the plugin.
2856  *
2857  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2858  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2859  */
2860 void *
2861 libgnunet_plugin_transport_tcp_init (void *cls)
2862 {
2863   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2864     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2865      sizeof (struct WelcomeMessage)},
2866     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2867     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2868     {NULL, NULL, 0, 0}
2869   };
2870   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2871   struct GNUNET_TRANSPORT_PluginFunctions *api;
2872   struct Plugin *plugin;
2873   struct GNUNET_SERVICE_Context *service;
2874   unsigned long long aport;
2875   unsigned long long bport;
2876   unsigned long long max_connections;
2877   unsigned int i;
2878   int behind_nat;
2879   int nat_punched;
2880   int enable_nat_client;
2881   int enable_nat_server;
2882   int enable_upnp;
2883   int use_localaddresses;
2884   char *internal_address;
2885   char *external_address;
2886   char *bind_address;
2887   struct sockaddr_in in_addr;
2888   struct GNUNET_TIME_Relative idle_timeout;
2889
2890   behind_nat = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2891                                                      "nat",
2892                                                      "BEHIND_NAT");
2893   nat_punched = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2894                                                       "nat",
2895                                                       "NAT_PUNCHED");
2896   enable_nat_client = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2897                                                             "nat",
2898                                                             "ENABLE_NAT_CLIENT");
2899   enable_nat_server = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2900                                                             "nat",
2901                                                             "ENABLE_NAT_SERVER");
2902   enable_upnp = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2903                                                       "nat",
2904                                                       "ENABLE_UPNP");
2905   
2906   if ( (GNUNET_YES == enable_nat_server) &&
2907        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-server")) )
2908     {
2909       enable_nat_server = GNUNET_NO;
2910       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2911                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2912                   "gnunet-nat-server");        
2913     }
2914
2915   if ( (GNUNET_YES == enable_nat_client) &&
2916        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-client")) )
2917     {
2918       enable_nat_client = GNUNET_NO;
2919       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2920                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2921                   "gnunet-nat-client"); 
2922     }
2923   
2924   external_address = NULL;
2925   if (GNUNET_OK ==
2926       GNUNET_CONFIGURATION_have_value (env->cfg,
2927                                        "nat",
2928                                        "EXTERNAL_ADDRESS"))
2929     {
2930       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2931                                                     "nat",
2932                                                     "EXTERNAL_ADDRESS",
2933                                                     &external_address);
2934     }
2935
2936   if ( (external_address != NULL) && 
2937        (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1) ) 
2938     {
2939       
2940       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2941                        "tcp",
2942                        _("Malformed %s `%s' given in configuration!\n"), 
2943                        "EXTERNAL_ADDRESS",
2944                        external_address);
2945       return NULL;   
2946     }
2947   if ( (external_address == NULL) &&
2948        (nat_punched == GNUNET_YES) )
2949     {
2950       nat_punched = GNUNET_NO;
2951       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2952                   _("Configuration says NAT was punched, but `%s' is not given.  Option ignored.\n"),
2953                   "EXTERNAL_ADDRESS");  
2954     }
2955
2956   if (GNUNET_YES == nat_punched)
2957     {
2958       enable_nat_server = GNUNET_NO;
2959       enable_upnp = GNUNET_NO;
2960     }
2961
2962   bind_address = NULL;
2963   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2964                                                            "nat",
2965                                                            "BINDTO",
2966                                                            &bind_address))
2967         {
2968           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2969                            "tcp",
2970                            _("Binding TCP plugin to specific address: `%s'\n"),
2971                            bind_address);
2972         }
2973
2974   internal_address = NULL;
2975   if (GNUNET_OK ==
2976       GNUNET_CONFIGURATION_have_value (env->cfg,
2977                                        "nat",
2978                                        "INTERNAL_ADDRESS"))
2979     {
2980       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2981                                                     "nat",
2982                                                     "INTERNAL_ADDRESS",
2983                                                     &internal_address);
2984     }
2985
2986   if ( (internal_address != NULL) && 
2987        (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1) )
2988     {
2989       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2990                        "tcp",
2991                        _("Malformed %s `%s' given in configuration!\n"), 
2992                        "INTERNAL_ADDRESS",
2993                        internal_address);      
2994       GNUNET_free_non_null(internal_address);
2995       GNUNET_free_non_null(external_address);
2996       return NULL;
2997     }
2998
2999   if ((bind_address != NULL) && (internal_address != NULL))
3000     {
3001       if (0 != strcmp(internal_address, bind_address ))
3002         {
3003           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3004                            "tcp",
3005                            "Specific bind address `%s' and internal address `%s' must not differ, forcing internal address to bind address!\n", 
3006                            bind_address, internal_address);
3007           GNUNET_free (internal_address);
3008           internal_address = bind_address;
3009           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3010                            "tcp","New internal address `%s'\n", internal_address);
3011         }
3012     }
3013   if (GNUNET_OK !=
3014       GNUNET_CONFIGURATION_get_value_number (env->cfg,
3015                                              "transport-tcp",
3016                                              "MAX_CONNECTIONS",
3017                                              &max_connections))
3018     max_connections = 128;
3019   
3020   aport = 0;
3021   if ( (GNUNET_OK !=
3022         GNUNET_CONFIGURATION_get_value_number (env->cfg,
3023                                                "transport-tcp",
3024                                                "PORT",
3025                                                &bport)) ||
3026        (bport > 65535) ||
3027        ((GNUNET_OK ==
3028          GNUNET_CONFIGURATION_get_value_number (env->cfg,
3029                                                 "transport-tcp",
3030                                                 "ADVERTISED-PORT",
3031                                                 &aport)) && 
3032         (aport > 65535)) )
3033     {
3034       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3035                        "tcp",
3036                        _("Require valid port number for service `%s' in configuration!\n"),
3037                        "transport-tcp");
3038       GNUNET_free_non_null(external_address);
3039       GNUNET_free_non_null(internal_address);
3040       return NULL;
3041     }
3042
3043   use_localaddresses = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3044                                                              "transport-tcp",
3045                                                              "USE_LOCALADDR");
3046   if (use_localaddresses == GNUNET_SYSERR)
3047     use_localaddresses = GNUNET_NO;
3048   
3049   if (aport == 0)
3050     aport = bport;
3051   if (bport == 0)
3052     aport = 0;
3053
3054   if (bport != 0)
3055     {
3056       service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
3057       if (service == NULL)
3058         {
3059           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
3060                            "tcp",
3061                            _("Failed to start service.\n"));
3062           return NULL;
3063         }
3064     }
3065   else
3066     service = NULL;
3067
3068   plugin = GNUNET_malloc (sizeof (struct Plugin));
3069   plugin->max_connections = max_connections;
3070   plugin->open_port = bport;
3071   plugin->adv_port = aport;
3072   plugin->bind_address = bind_address;
3073   plugin->external_address = external_address;
3074   plugin->internal_address = GNUNET_strdup(internal_address);
3075   plugin->behind_nat = behind_nat;
3076   plugin->nat_punched = nat_punched;
3077   plugin->enable_nat_client = enable_nat_client;
3078   plugin->enable_nat_server = enable_nat_server;
3079   plugin->enable_upnp = enable_upnp;
3080   plugin->use_localaddresses = use_localaddresses;
3081   plugin->env = env;
3082   plugin->lsock = NULL;
3083   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3084   api->cls = plugin;
3085   api->send = &tcp_plugin_send;
3086   api->disconnect = &tcp_plugin_disconnect;
3087   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
3088   api->check_address = &tcp_plugin_check_address;
3089   api->address_to_string = &tcp_address_to_string;
3090   plugin->service = service;
3091   if (service != NULL)   
3092     {
3093       plugin->server = GNUNET_SERVICE_get_server (service);
3094     }
3095   else
3096     {
3097       if (GNUNET_OK !=
3098           GNUNET_CONFIGURATION_get_value_time (env->cfg,
3099                                                "transport-tcp",
3100                                                "TIMEOUT",
3101                                                &idle_timeout))
3102         {
3103           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3104                            "tcp",
3105                            _("Failed to find option %s in section %s!\n"),
3106                            "TIMEOUT",
3107                            "transport-tcp");
3108           GNUNET_free_non_null(external_address);
3109           GNUNET_free_non_null(internal_address);
3110           GNUNET_free (api);
3111           return NULL;
3112         }
3113       plugin->server = GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin, NULL,
3114                                                           idle_timeout, GNUNET_YES);
3115     }
3116   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
3117   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
3118   for (i = 0;
3119        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
3120        i++)
3121     plugin->handlers[i].callback_cls = plugin;
3122   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
3123   GNUNET_SERVER_disconnect_notify (plugin->server,
3124                                    &disconnect_notify,
3125                                    plugin);    
3126   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
3127
3128   if ( (plugin->behind_nat == GNUNET_YES) &&
3129        (plugin->enable_nat_server == GNUNET_YES) &&
3130        (GNUNET_YES != tcp_transport_start_nat_server(plugin)) )
3131     {
3132       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
3133                        "tcp",
3134                        _("Failed to start %s required for NAT in %s!\n"),
3135                        "gnunet-nat-server"
3136                        "transport-tcp");
3137       GNUNET_free_non_null(external_address);
3138       GNUNET_free_non_null(internal_address);
3139       if (service != NULL)
3140         GNUNET_SERVICE_stop (service);
3141       else
3142         GNUNET_SERVER_destroy (plugin->server);
3143       GNUNET_free (api);
3144       return NULL;
3145     }
3146
3147   if (enable_nat_client == GNUNET_YES)
3148     {
3149       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(16);
3150       GNUNET_assert (plugin->nat_wait_conns != NULL);
3151     }
3152
3153   if (bport != 0)
3154     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3155                      "tcp",
3156                      _("TCP transport listening on port %llu\n"), 
3157                      bport);
3158   else
3159     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3160                      "tcp",
3161                      _("TCP transport not listening on any port (client only)\n"));
3162   if (aport != bport)
3163     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
3164                      "tcp",
3165                      _("TCP transport advertises itself as being on port %llu\n"),
3166                      aport);
3167
3168   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC,
3169                                                            HOSTNAME_RESOLVE_TIMEOUT,
3170                                                            &process_hostname_ips,
3171                                                            plugin);
3172
3173   if (plugin->external_address != NULL) 
3174     {
3175       plugin->ext_dns = GNUNET_RESOLVER_ip_get (plugin->external_address,
3176                                                 AF_INET,
3177                                                 GNUNET_TIME_UNIT_MINUTES,
3178                                                 &process_external_ip,
3179                                                 plugin);
3180     }
3181   return api;
3182 }
3183
3184
3185 /**
3186  * Exit point from the plugin.
3187  */
3188 void *
3189 libgnunet_plugin_transport_tcp_done (void *cls)
3190 {
3191   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3192   struct Plugin *plugin = api->cls;
3193   struct Session *session;
3194   struct LocalAddrList *lal;
3195   struct TCPProbeContext *tcp_probe;
3196
3197   if (plugin->ext_dns != NULL)
3198     {
3199       GNUNET_RESOLVER_request_cancel (plugin->ext_dns);
3200       plugin->ext_dns = NULL;
3201     }
3202   while (NULL != (session = plugin->sessions))
3203     disconnect_session (session);
3204   if (NULL != plugin->hostname_dns)
3205     {
3206       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
3207       plugin->hostname_dns = NULL;
3208     }
3209   if (plugin->service != NULL)
3210     GNUNET_SERVICE_stop (plugin->service);
3211   else
3212     GNUNET_SERVER_destroy (plugin->server);
3213   GNUNET_free (plugin->handlers);
3214   while (NULL != (lal = plugin->lal_head))
3215     {
3216       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
3217                                    plugin->lal_tail,
3218                                    lal);
3219       if (lal->nat != NULL)
3220         GNUNET_NAT_unregister (lal->nat);
3221       GNUNET_free_non_null (lal->external_nat_address);
3222       GNUNET_free (lal);
3223     }
3224   while (NULL != (tcp_probe = plugin->probe_head))
3225     {
3226       GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
3227                                    plugin->probe_tail,
3228                                    tcp_probe);
3229       GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
3230       GNUNET_free (tcp_probe);
3231     }
3232
3233   if ((plugin->behind_nat == GNUNET_YES) &&
3234       (plugin->enable_nat_server == GNUNET_YES))
3235     {
3236       if (0 != GNUNET_OS_process_kill (plugin->server_proc, SIGTERM))
3237         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
3238       GNUNET_OS_process_wait (plugin->server_proc);
3239       GNUNET_OS_process_close (plugin->server_proc);
3240       plugin->server_proc = NULL;
3241     }
3242   GNUNET_free_non_null(plugin->bind_address);
3243   GNUNET_free_non_null(plugin->internal_address);
3244   GNUNET_free (plugin);
3245   GNUNET_free (api);
3246   return NULL;
3247 }
3248
3249 /* end of plugin_transport_tcp.c */