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