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