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