Another fix for specific bind addresses
[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_YES
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   else 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 sa 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   if (NULL == proc)
1199     return;
1200   /* we know that the gnunet-nat-client will terminate virtually
1201      instantly */
1202   GNUNET_OS_process_wait (proc);
1203   GNUNET_OS_process_close (proc);
1204 }
1205
1206
1207 /**
1208  * Function that can be used by the transport service to transmit
1209  * a message using the plugin.   Note that in the case of a
1210  * peer disconnecting, the continuation MUST be called
1211  * prior to the disconnect notification itself.  This function
1212  * will be called with this peer's HELLO message to initiate
1213  * a fresh connection to another peer.
1214  *
1215  * @param cls closure
1216  * @param target who should receive this message
1217  * @param msg the message to transmit
1218  * @param msgbuf_size number of bytes in 'msg'
1219  * @param priority how important is the message (most plugins will
1220  *                 ignore message priority and just FIFO)
1221  * @param timeout how long to wait at most for the transmission (does not
1222  *                require plugins to discard the message after the timeout,
1223  *                just advisory for the desired delay; most plugins will ignore
1224  *                this as well)
1225  * @param session which session must be used (or NULL for "any")
1226  * @param addr the address to use (can be NULL if the plugin
1227  *                is "on its own" (i.e. re-use existing TCP connection))
1228  * @param addrlen length of the address in bytes
1229  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1230  *                GNUNET_NO means the plugin may use any other address and
1231  *                GNUNET_SYSERR means that only reliable existing
1232  *                bi-directional connections should be used (regardless
1233  *                of address)
1234  * @param cont continuation to call once the message has
1235  *        been transmitted (or if the transport is ready
1236  *        for the next transmission call; or if the
1237  *        peer disconnected...); can be NULL
1238  * @param cont_cls closure for cont
1239  * @return number of bytes used (on the physical network, with overheads);
1240  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1241  *         and does NOT mean that the message was not transmitted (DV and NAT)
1242  */
1243 static ssize_t
1244 tcp_plugin_send (void *cls,
1245                  const struct GNUNET_PeerIdentity *target,
1246                  const char *msg,
1247                  size_t msgbuf_size,
1248                  uint32_t priority,
1249                  struct GNUNET_TIME_Relative timeout,
1250                  struct Session *session,
1251                  const void *addr,
1252                  size_t addrlen,
1253                  int force_address,
1254                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1255 {
1256   struct Plugin *plugin = cls;
1257   struct Session *cand_session;
1258   struct Session *next;
1259   struct PendingMessage *pm;
1260   struct GNUNET_CONNECTION_Handle *sa;
1261   int af;
1262   const void *sb;
1263   size_t sbs;
1264   struct sockaddr_in a4;
1265   struct sockaddr_in6 a6;
1266   const struct IPv4TcpAddress *t4;
1267   const struct IPv6TcpAddress *t6;
1268   unsigned int is_natd;
1269
1270   GNUNET_STATISTICS_update (plugin->env->stats,
1271                             gettext_noop ("# bytes TCP was asked to transmit"),
1272                             msgbuf_size,
1273                             GNUNET_NO);
1274   /* FIXME: we could do this cheaper with a hash table
1275      where we could restrict the iteration to entries that match
1276      the target peer... */
1277   is_natd = GNUNET_NO;
1278   if (session == NULL)
1279     {
1280       cand_session = NULL;
1281       next = plugin->sessions;
1282       while (NULL != (session = next))
1283         {
1284           next = session->next;
1285           GNUNET_assert (session->client != NULL);
1286           if (0 != memcmp (target,
1287                            &session->target,
1288                            sizeof (struct GNUNET_PeerIdentity)))
1289             continue;
1290           if ( ( (GNUNET_SYSERR == force_address) &&
1291                  (session->expecting_welcome == GNUNET_NO) ) ||
1292                (GNUNET_NO == force_address) )
1293             {
1294               cand_session = select_better_session (cand_session,
1295                                                     session);
1296               continue;
1297             }
1298           if (GNUNET_SYSERR == force_address)
1299             continue;
1300           GNUNET_break (GNUNET_YES == force_address);
1301           if (addr == NULL)
1302             {
1303               GNUNET_break (0);
1304               break;
1305             }
1306           if ( (addrlen != session->connect_alen) && 
1307                (session->is_nat == GNUNET_NO) )
1308             continue;
1309           if ((0 != memcmp (session->connect_addr,
1310                            addr,
1311                            addrlen)) && (session->is_nat == GNUNET_NO))
1312             continue;
1313           cand_session = select_better_session (cand_session,
1314                                                 session);       
1315         }
1316       session = cand_session;
1317     }
1318   if ( (session == NULL) &&
1319        (addr == NULL) )
1320     {
1321 #if DEBUG_TCP
1322       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1323                        "tcp",
1324                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1325                        GNUNET_i2s (target));
1326 #endif
1327       GNUNET_STATISTICS_update (plugin->env->stats,
1328                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1329                                 msgbuf_size,
1330                                 GNUNET_NO);
1331       return -1;
1332     }
1333   if (session == NULL)
1334     {
1335       if (addrlen == sizeof (struct IPv6TcpAddress))
1336         {
1337           t6 = addr;
1338           af = AF_INET6;
1339           memset (&a6, 0, sizeof (a6));
1340 #if HAVE_SOCKADDR_IN_SIN_LEN
1341           a6.sin6_len = sizeof (a6);
1342 #endif
1343           a6.sin6_family = AF_INET6;
1344           a6.sin6_port = t6->t6_port;
1345           if (t6->t6_port == 0)
1346             is_natd = GNUNET_YES;
1347           memcpy (&a6.sin6_addr,
1348                   &t6->ipv6_addr,
1349                   sizeof (struct in6_addr));
1350           sb = &a6;
1351           sbs = sizeof (a6);
1352         }
1353       else if (addrlen == sizeof (struct IPv4TcpAddress))
1354         {
1355           t4 = addr;
1356           af = AF_INET;
1357           memset (&a4, 0, sizeof (a4));
1358 #if HAVE_SOCKADDR_IN_SIN_LEN
1359           a4.sin_len = sizeof (a4);
1360 #endif
1361           a4.sin_family = AF_INET;
1362           a4.sin_port = t4->t_port;
1363           if (t4->t_port == 0)
1364             is_natd = GNUNET_YES;
1365           a4.sin_addr.s_addr = t4->ipv4_addr;
1366           sb = &a4;
1367           sbs = sizeof (a4);
1368         }
1369       else
1370         {
1371           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1372                            "tcp",
1373                            _("Address of unexpected length: %u\n"),
1374                            addrlen);
1375           GNUNET_break (0);
1376           return -1;
1377         }
1378
1379       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1380         return -1; /* NAT client only works with IPv4 addresses */
1381
1382
1383       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1384            (is_natd == GNUNET_YES) &&
1385            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns,
1386                                                                 &target->hashPubKey)) )
1387         {
1388 #if DEBUG_TCP_NAT
1389           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1390                            "tcp",
1391                            _("Found valid IPv4 NAT address (creating session)!\n"));
1392 #endif
1393           session = create_session (plugin,
1394                                     target,
1395                                     NULL, 
1396                                     GNUNET_YES);
1397
1398           /* create new message entry */
1399           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1400           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1401           pm->msg = (const char*) &pm[1];
1402           memcpy (&pm[1], msg, msgbuf_size);
1403           /* FIXME: this memcpy can be up to 7% of our total run-time
1404              (for transport service) */
1405           pm->message_size = msgbuf_size;
1406           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1407           pm->transmit_cont = cont;
1408           pm->transmit_cont_cls = cont_cls;
1409
1410           /* append pm to pending_messages list */
1411           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1412                                              session->pending_messages_tail,
1413                                              session->pending_messages_tail,
1414                                              pm);
1415
1416           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns,
1417                                                           &target->hashPubKey,
1418                                                           session, 
1419                                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1420 #if DEBUG_TCP_NAT
1421           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1422                            "tcp",
1423                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1424                            GNUNET_i2s (target),
1425                            GNUNET_a2s (sb, sbs));
1426 #endif
1427           run_gnunet_nat_client (plugin, &a4);
1428           return 0;
1429         }
1430       if ( (plugin->enable_nat_client == GNUNET_YES) && 
1431            (is_natd == GNUNET_YES) && 
1432            (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, 
1433                                                                  &target->hashPubKey)) )
1434         {
1435           /* Only do one NAT punch attempt per peer identity */
1436           return -1;
1437         }
1438       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1439       if (sa == NULL)
1440         {
1441 #if DEBUG_TCP
1442           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1443                            "tcp",
1444                            "Failed to create connection to `%4s' at `%s'\n",
1445                            GNUNET_i2s (target),
1446                            GNUNET_a2s (sb, sbs));
1447 #endif
1448           GNUNET_STATISTICS_update (plugin->env->stats,
1449                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1450                                     msgbuf_size,
1451                                     GNUNET_NO);
1452           return -1;
1453         }
1454 #if DEBUG_TCP_NAT
1455       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1456                        "tcp",
1457                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1458                        GNUNET_i2s (target),
1459                        GNUNET_a2s (sb, sbs));
1460 #endif
1461       session = create_session (plugin,
1462                                 target,
1463                                 GNUNET_SERVER_connect_socket (plugin->server,
1464                                                               sa), 
1465                                 GNUNET_NO);
1466       session->connect_addr = GNUNET_malloc (addrlen);
1467       memcpy (session->connect_addr,
1468               addr,
1469               addrlen);
1470       session->connect_alen = addrlen;
1471     }
1472   GNUNET_assert (session != NULL);
1473   GNUNET_assert (session->client != NULL);
1474   GNUNET_STATISTICS_update (plugin->env->stats,
1475                             gettext_noop ("# bytes currently in TCP buffers"),
1476                             msgbuf_size,
1477                             GNUNET_NO);
1478   /* create new message entry */
1479   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1480   pm->msg = (const char*) &pm[1];
1481   memcpy (&pm[1], msg, msgbuf_size);
1482   pm->message_size = msgbuf_size;
1483   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1484   pm->transmit_cont = cont;
1485   pm->transmit_cont_cls = cont_cls;
1486
1487   /* append pm to pending_messages list */
1488   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1489                                      session->pending_messages_tail,
1490                                      session->pending_messages_tail,
1491                                      pm);
1492 #if DEBUG_TCP
1493   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1494                    "tcp",
1495                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1496                    msgbuf_size,
1497                    GNUNET_i2s (target));
1498 #endif
1499   process_pending_messages (session);
1500   return msgbuf_size;
1501 }
1502
1503
1504 /**
1505  * Function that can be called to force a disconnect from the
1506  * specified neighbour.  This should also cancel all previously
1507  * scheduled transmissions.  Obviously the transmission may have been
1508  * partially completed already, which is OK.  The plugin is supposed
1509  * to close the connection (if applicable) and no longer call the
1510  * transmit continuation(s).
1511  *
1512  * Finally, plugin MUST NOT call the services's receive function to
1513  * notify the service that the connection to the specified target was
1514  * closed after a getting this call.
1515  *
1516  * @param cls closure
1517  * @param target peer for which the last transmission is
1518  *        to be cancelled
1519  */
1520 static void
1521 tcp_plugin_disconnect (void *cls,
1522                        const struct GNUNET_PeerIdentity *target)
1523 {
1524   struct Plugin *plugin = cls;
1525   struct Session *session;
1526   struct Session *next;
1527   struct PendingMessage *pm;
1528
1529 #if DEBUG_TCP
1530   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1531                    "tcp",
1532                    "Asked to cancel session with `%4s'\n",
1533                    GNUNET_i2s (target));
1534 #endif
1535   next = plugin->sessions;
1536   while (NULL != (session = next))
1537     {
1538       next = session->next;
1539       if (0 != memcmp (target,
1540                        &session->target,
1541                        sizeof (struct GNUNET_PeerIdentity)))
1542         continue;
1543       pm = session->pending_messages_head;
1544       while (pm != NULL)
1545         {
1546           pm->transmit_cont = NULL;
1547           pm->transmit_cont_cls = NULL;
1548           pm = pm->next;
1549         }
1550       GNUNET_STATISTICS_update (session->plugin->env->stats,
1551                                 gettext_noop ("# transport-service disconnect requests for TCP"),
1552                                 1,
1553                                 GNUNET_NO);
1554       disconnect_session (session);
1555     }
1556 }
1557
1558
1559 /**
1560  * Context for address to string conversion.
1561  */
1562 struct PrettyPrinterContext
1563 {
1564   /**
1565    * Function to call with the result.
1566    */
1567   GNUNET_TRANSPORT_AddressStringCallback asc;
1568
1569   /**
1570    * Clsoure for 'asc'.
1571    */
1572   void *asc_cls;
1573
1574   /**
1575    * Port to add after the IP address.
1576    */
1577   uint16_t port;
1578 };
1579
1580
1581 /**
1582  * Append our port and forward the result.
1583  *
1584  * @param cls the 'struct PrettyPrinterContext*'
1585  * @param hostname hostname part of the address
1586  */
1587 static void
1588 append_port (void *cls, const char *hostname)
1589 {
1590   struct PrettyPrinterContext *ppc = cls;
1591   char *ret;
1592
1593   if (hostname == NULL)
1594     {
1595       ppc->asc (ppc->asc_cls, NULL);
1596       GNUNET_free (ppc);
1597       return;
1598     }
1599   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1600   ppc->asc (ppc->asc_cls, ret);
1601   GNUNET_free (ret);
1602 }
1603
1604
1605 /**
1606  * Convert the transports address to a nice, human-readable
1607  * format.
1608  *
1609  * @param cls closure
1610  * @param type name of the transport that generated the address
1611  * @param addr one of the addresses of the host, NULL for the last address
1612  *        the specific address format depends on the transport
1613  * @param addrlen length of the address
1614  * @param numeric should (IP) addresses be displayed in numeric form?
1615  * @param timeout after how long should we give up?
1616  * @param asc function to call on each string
1617  * @param asc_cls closure for asc
1618  */
1619 static void
1620 tcp_plugin_address_pretty_printer (void *cls,
1621                                    const char *type,
1622                                    const void *addr,
1623                                    size_t addrlen,
1624                                    int numeric,
1625                                    struct GNUNET_TIME_Relative timeout,
1626                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1627                                    void *asc_cls)
1628 {
1629   struct Plugin *plugin = cls;
1630   struct PrettyPrinterContext *ppc;
1631   const void *sb;
1632   size_t sbs;
1633   struct sockaddr_in a4;
1634   struct sockaddr_in6 a6;
1635   const struct IPv4TcpAddress *t4;
1636   const struct IPv6TcpAddress *t6;
1637   uint16_t port;
1638
1639   if (addrlen == sizeof (struct IPv6TcpAddress))
1640     {
1641       t6 = addr;
1642       memset (&a6, 0, sizeof (a6));
1643       a6.sin6_family = AF_INET6;
1644       a6.sin6_port = t6->t6_port;
1645       memcpy (&a6.sin6_addr,
1646               &t6->ipv6_addr,
1647               sizeof (struct in6_addr));
1648       port = ntohs (t6->t6_port);
1649       sb = &a6;
1650       sbs = sizeof (a6);
1651     }
1652   else if (addrlen == sizeof (struct IPv4TcpAddress))
1653     {
1654       t4 = addr;
1655       memset (&a4, 0, sizeof (a4));
1656       a4.sin_family = AF_INET;
1657       a4.sin_port = t4->t_port;
1658       a4.sin_addr.s_addr = t4->ipv4_addr;
1659       port = ntohs (t4->t_port);
1660       sb = &a4;
1661       sbs = sizeof (a4);
1662     }
1663   else
1664     {
1665       /* invalid address */
1666       GNUNET_break_op (0);
1667       asc (asc_cls, NULL);
1668       return;
1669     }
1670   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1671   ppc->asc = asc;
1672   ppc->asc_cls = asc_cls;
1673   ppc->port = port;
1674   GNUNET_RESOLVER_hostname_get (plugin->env->cfg,
1675                                 sb,
1676                                 sbs,
1677                                 !numeric, timeout, &append_port, ppc);
1678 }
1679
1680
1681 /**
1682  * Check if the given port is plausible (must be either our listen
1683  * port or our advertised port), or any port if we are behind NAT
1684  * and do not have a port open.  If it is neither, we return
1685  * GNUNET_SYSERR.
1686  *
1687  * @param plugin global variables
1688  * @param in_port port number to check
1689  * @return GNUNET_OK if port is either open_port or adv_port
1690  */
1691 static int
1692 check_port (struct Plugin *plugin, 
1693             uint16_t in_port)
1694 {
1695   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1696     return GNUNET_OK;
1697   return GNUNET_SYSERR;
1698 }
1699
1700
1701 /**
1702  * Function that will be called to check if a binary address for this
1703  * plugin is well-formed and corresponds to an address for THIS peer
1704  * (as per our configuration).  Naturally, if absolutely necessary,
1705  * plugins can be a bit conservative in their answer, but in general
1706  * plugins should make sure that the address does not redirect
1707  * traffic to a 3rd party that might try to man-in-the-middle our
1708  * traffic.
1709  *
1710  * @param cls closure, our 'struct Plugin*'
1711  * @param addr pointer to the address
1712  * @param addrlen length of addr
1713  * @return GNUNET_OK if this is a plausible address for this peer
1714  *         and transport, GNUNET_SYSERR if not
1715  */
1716 static int
1717 tcp_plugin_check_address (void *cls,
1718                           const void *addr,
1719                           size_t addrlen)
1720 {
1721   struct Plugin *plugin = cls;
1722   struct IPv4TcpAddress *v4;
1723   struct IPv6TcpAddress *v6;
1724
1725   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1726       (addrlen != sizeof (struct IPv6TcpAddress)))
1727     {
1728       GNUNET_break_op (0);
1729       return GNUNET_SYSERR;
1730     }
1731   if (addrlen == sizeof (struct IPv4TcpAddress))
1732     {
1733       v4 = (struct IPv4TcpAddress *) addr;
1734       if (GNUNET_OK ==
1735           check_mapped_addr (plugin, v4, sizeof (struct IPv4TcpAddress)))
1736         return GNUNET_OK;
1737       if (GNUNET_OK !=
1738           check_port (plugin, ntohs (v4->t_port)))
1739         return GNUNET_SYSERR;
1740       if (GNUNET_OK !=
1741           check_local_addr (plugin, &v4->ipv4_addr, sizeof (struct in_addr)))
1742         return GNUNET_SYSERR;   
1743     }
1744   else
1745     {
1746       v6 = (struct IPv6TcpAddress *) addr;
1747       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1748         {
1749           GNUNET_break_op (0);
1750           return GNUNET_SYSERR;
1751         }
1752       if (GNUNET_OK ==
1753           check_mapped_addr (plugin, v6, sizeof (struct IPv6TcpAddress)))
1754         return GNUNET_OK;
1755       if (GNUNET_OK !=
1756           check_port (plugin, ntohs (v6->t6_port)))
1757         return GNUNET_SYSERR;
1758       if (GNUNET_OK !=
1759           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1760         return GNUNET_SYSERR;
1761     }
1762   return GNUNET_OK;
1763 }
1764
1765
1766 /**
1767  * We've received a nat probe from this peer via TCP.  Finish
1768  * creating the client session and resume sending of queued
1769  * messages.
1770  *
1771  * @param cls closure
1772  * @param client identification of the client
1773  * @param message the actual message
1774  */
1775 static void
1776 handle_tcp_nat_probe (void *cls,
1777                       struct GNUNET_SERVER_Client *client,
1778                       const struct GNUNET_MessageHeader *message)
1779 {
1780   struct Plugin *plugin = cls;
1781   struct Session *session;
1782   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1783   size_t alen;
1784   void *vaddr;
1785   struct IPv4TcpAddress *t4;
1786   struct IPv6TcpAddress *t6;
1787   const struct sockaddr_in *s4;
1788   const struct sockaddr_in6 *s6;
1789
1790 #if DEBUG_TCP_NAT
1791   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1792                    "tcp",
1793                    "received tcp NAT probe\n");
1794 #endif
1795   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1796    * a connection to this peer by running gnunet-nat-client.  This peer
1797    * received the punch message and now wants us to use the new connection
1798    * as the default for that peer.  Do so and then send a WELCOME message
1799    * so we can really be connected!
1800    */
1801   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1802     {
1803       GNUNET_break_op(0);
1804       return;
1805     }
1806   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *)message;
1807   session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, 
1808                                               &tcp_nat_probe->clientIdentity.hashPubKey);
1809   if (session == NULL)
1810     {
1811 #if DEBUG_TCP_NAT
1812       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1813                        "tcp",
1814                        "Did NOT find session for NAT probe!\n");
1815 #endif
1816       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1817       return;
1818     }
1819 #if DEBUG_TCP_NAT
1820   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
1821                    "tcp",
1822                    "Found session for NAT probe!\n");
1823 #endif
1824   GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, 
1825                                                      &tcp_nat_probe->clientIdentity.hashPubKey,
1826                                                      session) == GNUNET_YES);
1827   if (GNUNET_OK !=
1828       GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1829     {
1830       GNUNET_break (0);
1831       GNUNET_free (session);
1832       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1833       return;
1834     }
1835
1836   GNUNET_SERVER_client_keep (client);
1837   session->client = client;
1838   session->last_activity = GNUNET_TIME_absolute_get ();
1839   session->inbound = GNUNET_NO;
1840
1841 #if DEBUG_TCP_NAT
1842   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1843                    "tcp",
1844                    "Found address `%s' for incoming connection\n",
1845                    GNUNET_a2s (vaddr, alen));
1846 #endif
1847   switch (((const struct sockaddr *)vaddr)->sa_family)
1848     {
1849     case AF_INET:
1850       s4 = vaddr;
1851       t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1852       t4->t_port = s4->sin_port;
1853       t4->ipv4_addr = s4->sin_addr.s_addr;
1854       session->connect_addr = t4;
1855       session->connect_alen = sizeof (struct IPv4TcpAddress);
1856       break;
1857     case AF_INET6:    
1858       s6 = vaddr;
1859       t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1860       t6->t6_port = s6->sin6_port;
1861       memcpy (&t6->ipv6_addr,
1862               &s6->sin6_addr,
1863               sizeof (struct in6_addr));
1864       session->connect_addr = t6;
1865       session->connect_alen = sizeof (struct IPv6TcpAddress);
1866       break;
1867     default:
1868       GNUNET_break_op (0);
1869 #if DEBUG_TCP_NAT
1870       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1871                        "tcp",
1872                        "Bad address for incoming connection!\n");
1873 #endif
1874       GNUNET_free (vaddr);
1875       GNUNET_SERVER_client_drop (client);
1876       GNUNET_free (session);
1877       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1878       return;
1879     }
1880   GNUNET_free (vaddr);
1881   
1882   session->next = plugin->sessions;
1883   plugin->sessions = session;
1884   GNUNET_STATISTICS_update (plugin->env->stats,
1885                             gettext_noop ("# TCP sessions active"),
1886                             1,
1887                             GNUNET_NO);
1888   process_pending_messages (session);
1889   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1890 }
1891
1892
1893 /**
1894  * We've received a welcome from this peer via TCP.  Possibly create a
1895  * fresh client record and send back our welcome.
1896  *
1897  * @param cls closure
1898  * @param client identification of the client
1899  * @param message the actual message
1900  */
1901 static void
1902 handle_tcp_welcome (void *cls,
1903                     struct GNUNET_SERVER_Client *client,
1904                     const struct GNUNET_MessageHeader *message)
1905 {
1906   struct Plugin *plugin = cls;
1907   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1908   struct Session *session;
1909   size_t alen;
1910   void *vaddr;
1911   struct IPv4TcpAddress *t4;
1912   struct IPv6TcpAddress *t6;
1913   const struct sockaddr_in *s4;
1914   const struct sockaddr_in6 *s6;
1915
1916 #if DEBUG_TCP
1917   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1918                    "tcp",
1919                    "Received %s message from `%4s'.\n",
1920                    "WELCOME",
1921                    GNUNET_i2s (&wm->clientIdentity));
1922 #endif
1923   GNUNET_STATISTICS_update (plugin->env->stats,
1924                             gettext_noop ("# TCP WELCOME messages received"),
1925                             1,
1926                             GNUNET_NO);
1927   session = find_session_by_client (plugin, client);
1928
1929   if (session == NULL)
1930     {
1931 #if DEBUG_TCP_NAT
1932       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1933                        "tcp",
1934                        "Received %s message from a `%4s', creating new session\n",
1935                        "WELCOME",
1936                        GNUNET_i2s (&wm->clientIdentity));
1937 #endif
1938       GNUNET_SERVER_client_keep (client);
1939       session = create_session (plugin,
1940                                 &wm->clientIdentity,
1941                                 client,
1942                                 GNUNET_NO);
1943       session->inbound = GNUNET_YES;
1944       if (GNUNET_OK ==
1945           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1946         {
1947 #if DEBUG_TCP_NAT
1948           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1949                            "tcp",
1950                            "Found address `%s' for incoming connection\n",
1951                            GNUNET_a2s (vaddr, alen));
1952 #endif
1953           if (alen == sizeof (struct sockaddr_in))
1954             {
1955               s4 = vaddr;
1956               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1957               t4->t_port = s4->sin_port;
1958               t4->ipv4_addr = s4->sin_addr.s_addr;
1959               session->connect_addr = t4;
1960               session->connect_alen = sizeof (struct IPv4TcpAddress);
1961             }
1962           else if (alen == sizeof (struct sockaddr_in6))
1963             {
1964               s6 = vaddr;
1965               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1966               t6->t6_port = s6->sin6_port;
1967               memcpy (&t6->ipv6_addr,
1968                       &s6->sin6_addr,
1969                       sizeof (struct in6_addr));
1970               session->connect_addr = t6;
1971               session->connect_alen = sizeof (struct IPv6TcpAddress);
1972             }
1973
1974           GNUNET_free (vaddr);
1975         }
1976       else
1977         {
1978 #if DEBUG_TCP
1979           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1980                            "tcp",
1981                            "Did not obtain TCP socket address for incoming connection\n");
1982 #endif
1983         }
1984       process_pending_messages (session);
1985     }
1986   else
1987     {
1988 #if DEBUG_TCP_NAT
1989     if (GNUNET_OK ==
1990         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1991       {
1992         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1993                          "tcp",
1994                          "Found address `%s' (already have session)\n",
1995                          GNUNET_a2s (vaddr, alen));
1996       }
1997 #endif
1998     }
1999
2000   if (session->expecting_welcome != GNUNET_YES)
2001     {
2002       GNUNET_break_op (0);
2003       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2004       return;
2005     }
2006   session->last_activity = GNUNET_TIME_absolute_get ();
2007   session->expecting_welcome = GNUNET_NO;
2008   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2009 }
2010
2011
2012 /**
2013  * Task to signal the server that we can continue
2014  * receiving from the TCP client now.
2015  *
2016  * @param cls the 'struct Session*'
2017  * @param tc task context (unused)
2018  */
2019 static void
2020 delayed_done (void *cls, 
2021               const struct GNUNET_SCHEDULER_TaskContext *tc)
2022 {
2023   struct Session *session = cls;
2024   struct GNUNET_TIME_Relative delay;
2025
2026   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
2027   delay = session->plugin->env->receive (session->plugin->env->cls,
2028                                          &session->target,
2029                                          NULL,
2030                                          NULL, 0,
2031                                          session,
2032                                          NULL, 0);
2033   if (delay.rel_value == 0)
2034     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
2035   else
2036     session->receive_delay_task =
2037       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2038 }
2039
2040
2041 /**
2042  * We've received data for this peer via TCP.  Unbox,
2043  * compute latency and forward.
2044  *
2045  * @param cls closure
2046  * @param client identification of the client
2047  * @param message the actual message
2048  */
2049 static void
2050 handle_tcp_data (void *cls,
2051                  struct GNUNET_SERVER_Client *client,
2052                  const struct GNUNET_MessageHeader *message)
2053 {
2054   struct Plugin *plugin = cls;
2055   struct Session *session;
2056   struct GNUNET_TIME_Relative delay;
2057   uint16_t type;
2058
2059   type = ntohs (message->type);
2060   if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) || 
2061        (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
2062     {
2063       /* We don't want to propagate WELCOME and NAT Probe messages up! */
2064       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2065       return;
2066     }
2067   session = find_session_by_client (plugin, client);
2068   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome) )
2069     {
2070       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2071       return;
2072     }
2073   session->last_activity = GNUNET_TIME_absolute_get ();
2074 #if DEBUG_TCP > 1
2075   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2076                    "tcp",
2077                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
2078                    (unsigned int) ntohs (message->size),
2079                    (unsigned int) ntohs (message->type),
2080                    GNUNET_i2s (&session->target));
2081 #endif
2082   GNUNET_STATISTICS_update (plugin->env->stats,
2083                             gettext_noop ("# bytes received via TCP"),
2084                             ntohs (message->size),
2085                             GNUNET_NO);
2086   struct GNUNET_TRANSPORT_ATS_Information distance[2];
2087   distance[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DISTANCE);
2088   distance[0].value = htonl (1);
2089   distance[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
2090   distance[1].value = htonl (0);
2091   delay = plugin->env->receive (plugin->env->cls, &session->target, message,
2092                                 (const struct GNUNET_TRANSPORT_ATS_Information *) &distance,
2093                                 2,
2094                                 session,
2095                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
2096                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
2097   if (delay.rel_value == 0)
2098     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2099   else
2100     session->receive_delay_task =
2101       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
2102 }
2103
2104
2105 /**
2106  * Functions with this signature are called whenever a peer
2107  * is disconnected on the network level.
2108  *
2109  * @param cls closure
2110  * @param client identification of the client
2111  */
2112 static void
2113 disconnect_notify (void *cls,
2114                    struct GNUNET_SERVER_Client *client)
2115 {
2116   struct Plugin *plugin = cls;
2117   struct Session *session;
2118
2119   if (client == NULL)
2120     return;
2121   session = find_session_by_client (plugin, client);
2122   if (session == NULL)
2123     return;                     /* unknown, nothing to do */
2124 #if DEBUG_TCP
2125   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2126                    "tcp",
2127                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2128                    GNUNET_i2s (&session->target),
2129                    (session->connect_addr != NULL) ?
2130                    tcp_address_to_string (session->plugin,
2131                                           session->connect_addr,
2132                                           session->connect_alen) : "*");
2133 #endif
2134   GNUNET_STATISTICS_update (session->plugin->env->stats,
2135                             gettext_noop ("# network-level TCP disconnect events"),
2136                             1,
2137                             GNUNET_NO);
2138   disconnect_session (session);
2139 }
2140
2141
2142 /**
2143  * Add the IP of our network interface to the list of
2144  * our internal IP addresses.
2145  *
2146  * @param cls the 'struct Plugin*'
2147  * @param name name of the interface
2148  * @param isDefault do we think this may be our default interface
2149  * @param addr address of the interface
2150  * @param addrlen number of bytes in addr
2151  * @return GNUNET_OK to continue iterating
2152  */
2153 static int
2154 process_interfaces (void *cls,
2155                     const char *name,
2156                     int isDefault,
2157                     const struct sockaddr *addr, socklen_t addrlen)
2158 {
2159   struct Plugin *plugin = cls;
2160   int af;
2161   struct IPv4TcpAddress t4;
2162   struct IPv6TcpAddress t6;
2163   struct IPv4TcpAddress t4_nat;
2164   struct IPv6TcpAddress t6_nat;
2165   void *arg;
2166   uint16_t args;
2167   void *arg_nat;
2168   char buf[INET6_ADDRSTRLEN];
2169
2170   af = addr->sa_family;
2171   arg_nat = NULL;
2172   switch (af)
2173     {
2174     case AF_INET:
2175       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2176       GNUNET_assert (NULL != inet_ntop(AF_INET, 
2177                                        &t4.ipv4_addr, 
2178                                        buf, 
2179                                        sizeof (buf)));
2180       if ( (plugin->bind_address != NULL) && 
2181            (0 != strcmp(buf, plugin->bind_address)) )
2182         {
2183 #if DEBUG_TCP
2184           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2185                            "tcp",
2186                            "Not notifying transport of address `%s' (does not match bind address)\n",
2187                            GNUNET_a2s (addr, addrlen));
2188 #endif
2189           return GNUNET_OK;
2190         }
2191       if ( (plugin->internal_address == NULL) &&
2192            (isDefault) )        
2193         plugin->internal_address = GNUNET_strdup (buf); 
2194       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (struct in_addr));
2195       if (plugin->behind_nat == GNUNET_YES) 
2196         {
2197           /* Also advertise as NAT (with port 0) */
2198           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
2199           t4_nat.t_port = htons(0);
2200           arg_nat = &t4_nat;
2201         }       
2202       t4.t_port = htons (plugin->adv_port);     
2203       arg = &t4;
2204       args = sizeof (t4);
2205       break;
2206     case AF_INET6:      
2207       if ( (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || 
2208            (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, 
2209                                                                "transport-tcp", 
2210                                                                "DISABLEV6")) )
2211         {
2212           /* skip link local addresses */
2213           return GNUNET_OK;
2214         }
2215       memcpy (&t6.ipv6_addr,
2216               &((struct sockaddr_in6 *) addr)->sin6_addr,
2217               sizeof (struct in6_addr));
2218
2219       /* check bind address */
2220       GNUNET_assert (NULL != inet_ntop(AF_INET6,
2221                                        &t6.ipv6_addr,
2222                                        buf,
2223                                        sizeof (buf)));
2224
2225       if ( (plugin->bind_address != NULL) &&
2226            (0 != strcmp(buf, plugin->bind_address)) )
2227         {
2228 #if DEBUG_TCP
2229           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2230                            "tcp",
2231                            "Not notifying transport of address `%s' (does not match bind address)\n",
2232                            GNUNET_a2s (addr, addrlen));
2233 #endif
2234           return GNUNET_OK;
2235         }
2236
2237       add_to_address_list (plugin, 
2238                            &t6.ipv6_addr, 
2239                            sizeof (struct in6_addr));
2240       if (plugin->behind_nat == GNUNET_YES)
2241         {
2242           /* Also advertise as NAT (with port 0) */
2243           memcpy (&t6_nat.ipv6_addr,
2244                   &((struct sockaddr_in6 *) addr)->sin6_addr,
2245                   sizeof (struct in6_addr));
2246           t6_nat.t6_port = htons(0);
2247           arg_nat = &t6;
2248         }
2249       t6.t6_port = htons (plugin->adv_port);
2250       arg = &t6;
2251       args = sizeof (t6);
2252       break;
2253     default:
2254       GNUNET_break (0);
2255       return GNUNET_OK;
2256     }
2257 #if DEBUG_TCP
2258   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2259                    "tcp",
2260                    "Found address `%s' (%s) len %d\n",
2261                    GNUNET_a2s (addr, addrlen), name, args);
2262 #endif
2263   plugin->env->notify_address (plugin->env->cls,
2264                                "tcp",
2265                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
2266
2267   if (arg_nat != NULL)
2268     {
2269       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2270                        "tcp",
2271                        _("Found address `%s' (%s) len %d\n"),
2272                        GNUNET_a2s (addr, addrlen), name, args);
2273       plugin->env->notify_address (plugin->env->cls,
2274                                    "tcp",
2275                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
2276     }
2277
2278   return GNUNET_OK;
2279 }
2280
2281
2282 /**
2283  * Function called by the resolver for each address obtained from DNS
2284  * for our own hostname.  Add the addresses to the list of our
2285  * external IP addresses.
2286  *
2287  * @param cls closure
2288  * @param addr one of the addresses of the host, NULL for the last address
2289  * @param addrlen length of the address
2290  */
2291 static void
2292 process_hostname_ips (void *cls,
2293                       const struct sockaddr *addr, socklen_t addrlen)
2294 {
2295   struct Plugin *plugin = cls;
2296
2297   if (addr == NULL)
2298     {
2299       plugin->hostname_dns = NULL;
2300       return;
2301     }
2302   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
2303   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
2304 }
2305
2306
2307 /**
2308  * We can now send a probe message, copy into buffer to really send.
2309  *
2310  * @param cls closure, a struct TCPProbeContext
2311  * @param size max size to copy
2312  * @param buf buffer to copy message to
2313  * @return number of bytes copied into buf
2314  */
2315 static size_t
2316 notify_send_probe (void *cls,
2317                    size_t size,
2318                    void *buf)
2319 {
2320   struct TCPProbeContext *tcp_probe_ctx = cls;
2321   struct Plugin *plugin = tcp_probe_ctx->plugin;
2322   size_t ret;
2323
2324   tcp_probe_ctx->transmit_handle = NULL;
2325   GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
2326                                plugin->probe_tail,
2327                                tcp_probe_ctx);
2328   if (buf == NULL)
2329     {
2330       GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock, GNUNET_NO);
2331       GNUNET_free(tcp_probe_ctx);
2332       return 0;    
2333     }
2334   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2335   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2336   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2337                                 tcp_probe_ctx->sock);
2338   ret = sizeof(tcp_probe_ctx->message);
2339   GNUNET_free(tcp_probe_ctx);
2340   return ret;
2341 }
2342
2343
2344 /**
2345  * We have been notified that gnunet-nat-server has written something to stdout.
2346  * Handle the output, then reschedule this function to be called again once
2347  * more is available.
2348  *
2349  * @param cls the plugin handle
2350  * @param tc the scheduling context
2351  */
2352 static void
2353 tcp_plugin_server_read (void *cls, 
2354                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2355 {
2356   struct Plugin *plugin = cls;
2357   char mybuf[40];
2358   ssize_t bytes;
2359   size_t i;
2360   int port;
2361   const char *port_start;
2362   struct sockaddr_in sin_addr;
2363   struct TCPProbeContext *tcp_probe_ctx;
2364   struct GNUNET_CONNECTION_Handle *sock;
2365
2366   if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
2367     return;
2368   memset (mybuf, 0, sizeof(mybuf));
2369   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, 
2370                                 mybuf,
2371                                 sizeof(mybuf));
2372   if (bytes < 1)
2373     {
2374 #if DEBUG_TCP_NAT
2375       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2376                        "tcp",
2377                        "Finished reading from server stdout with code: %d\n", 
2378                        bytes);
2379 #endif
2380       /* FIXME: consider process_wait here? */
2381       return;
2382     }
2383
2384   port_start = NULL;
2385   for (i = 0; i < sizeof(mybuf); i++)
2386     {
2387       if (mybuf[i] == '\n')
2388         {
2389           mybuf[i] = '\0';
2390           break;
2391         }
2392       if ( (mybuf[i] == ':') && (i + 1 < sizeof(mybuf)) )
2393         {
2394           mybuf[i] = '\0';
2395           port_start = &mybuf[i + 1];
2396         }
2397     }
2398
2399   /* construct socket address of sender */
2400   memset (&sin_addr, 0, sizeof (sin_addr));
2401   sin_addr.sin_family = AF_INET;
2402 #if HAVE_SOCKADDR_IN_SIN_LEN
2403   sin_addr.sin_len = sizeof (sin_addr);
2404 #endif
2405   if ( (NULL == port_start) ||
2406        (1 != sscanf (port_start, "%d", &port)) ||
2407        (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr)) )
2408     {
2409       /* should we restart gnunet-nat-server? */
2410       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2411                        "tcp",
2412                        _("gnunet-nat-server generated malformed address `%s'\n"),
2413                        mybuf);
2414       plugin->server_read_task 
2415         = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2416                                           plugin->server_stdout_handle,
2417                                           &tcp_plugin_server_read, 
2418                                           plugin);
2419       return;
2420     }
2421   sin_addr.sin_port = htons((uint16_t) port);
2422 #if DEBUG_TCP_NAT
2423   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2424                    "tcp",
2425                    "gnunet-nat-server read: %s:%d\n", 
2426                    mybuf, port);
2427 #endif
2428
2429   /**
2430    * We have received an ICMP response, ostensibly from a peer
2431    * that wants to connect to us! Send a message to establish a connection.
2432    */
2433   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, 
2434                                                  (const struct sockaddr *)&sin_addr,
2435                                                  sizeof (sin_addr));
2436   if (sock == NULL)
2437     {
2438       /* failed for some odd reason (out of sockets?); ignore attempt */
2439       plugin->server_read_task =
2440           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2441                                           plugin->server_stdout_handle, 
2442                                           &tcp_plugin_server_read, 
2443                                           plugin);
2444       return;
2445     }
2446
2447   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2448                    "Sending TCP probe message to `%s:%u'!\n", 
2449                    mybuf,
2450                    (unsigned int) port);  
2451   /* FIXME: do we need to track these probe context objects so that
2452      we can clean them up on plugin unload? */
2453   tcp_probe_ctx
2454     = GNUNET_malloc(sizeof(struct TCPProbeContext));
2455   tcp_probe_ctx->message.header.size
2456     = htons(sizeof(struct TCP_NAT_ProbeMessage));
2457   tcp_probe_ctx->message.header.type
2458     = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2459   memcpy (&tcp_probe_ctx->message.clientIdentity,
2460           plugin->env->my_identity,
2461           sizeof(struct GNUNET_PeerIdentity));
2462   tcp_probe_ctx->plugin = plugin;
2463   tcp_probe_ctx->sock = sock;
2464   GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
2465                                plugin->probe_tail,
2466                                tcp_probe_ctx);
2467   tcp_probe_ctx->transmit_handle 
2468     = GNUNET_CONNECTION_notify_transmit_ready (sock,
2469                                                ntohs (tcp_probe_ctx->message.header.size),
2470                                                GNUNET_TIME_UNIT_FOREVER_REL,
2471                                                &notify_send_probe, tcp_probe_ctx);
2472   
2473   plugin->server_read_task =
2474       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2475                                       plugin->server_stdout_handle,
2476                                       &tcp_plugin_server_read,
2477                                       plugin);
2478 }
2479
2480
2481 /**
2482  * Start the gnunet-nat-server process for users behind NAT.
2483  *
2484  * @param plugin the transport plugin
2485  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2486  */
2487 static int
2488 tcp_transport_start_nat_server (struct Plugin *plugin)
2489 {
2490   if (plugin->internal_address == NULL)
2491     return GNUNET_SYSERR;
2492   plugin->server_stdout = GNUNET_DISK_pipe (GNUNET_YES,
2493                                             GNUNET_NO,
2494                                             GNUNET_YES);
2495   if (plugin->server_stdout == NULL)
2496     return GNUNET_SYSERR;
2497 #if DEBUG_TCP_NAT
2498   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
2499                    "tcp"
2500                    "Starting %s %s\n", 
2501                    "gnunet-nat-server", 
2502                    plugin->internal_address);
2503 #endif
2504   /* Start the server process */
2505   plugin->server_proc = GNUNET_OS_start_process (NULL,
2506                                                  plugin->server_stdout,
2507                                                  "gnunet-nat-server", 
2508                                                  "gnunet-nat-server", 
2509                                                  plugin->internal_address, 
2510                                                  NULL);
2511   if (plugin->server_proc == NULL)
2512     {
2513       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2514                        "tcp",
2515                        _("Failed to start %s\n"),
2516                        "gnunet-nat-server");
2517       GNUNET_DISK_pipe_close (plugin->server_stdout);
2518       plugin->server_stdout = NULL;    
2519       return GNUNET_SYSERR;
2520     }
2521   /* Close the write end of the read pipe */
2522   GNUNET_DISK_pipe_close_end(plugin->server_stdout, 
2523                              GNUNET_DISK_PIPE_END_WRITE);
2524   plugin->server_stdout_handle 
2525     = GNUNET_DISK_pipe_handle (plugin->server_stdout, 
2526                                GNUNET_DISK_PIPE_END_READ);
2527   plugin->server_read_task 
2528     = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2529                                       plugin->server_stdout_handle,
2530                                       &tcp_plugin_server_read, 
2531                                       plugin);
2532   return GNUNET_YES;
2533 }
2534
2535
2536 /**
2537  * Return the actual path to a file found in the current
2538  * PATH environment variable.
2539  *
2540  * @param binary the name of the file to find
2541  * @return path to binary, NULL if not found
2542  */
2543 static char *
2544 get_path_from_PATH (const char *binary)
2545 {
2546   char *path;
2547   char *pos;
2548   char *end;
2549   char *buf;
2550   const char *p;
2551
2552   p = getenv ("PATH");
2553   if (p == NULL)
2554     {
2555       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2556                        "tcp",
2557                        _("PATH environment variable is unset.\n"));
2558       return NULL;
2559     }
2560   path = GNUNET_strdup (p);     /* because we write on it */
2561   buf = GNUNET_malloc (strlen (path) + 20);
2562   pos = path;
2563
2564   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
2565     {
2566       *end = '\0';
2567       sprintf (buf, "%s/%s", pos, binary);
2568       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2569         {
2570           GNUNET_free (path);
2571           return buf;
2572         }
2573       pos = end + 1;
2574     }
2575   sprintf (buf, "%s/%s", pos, binary);
2576   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2577     {
2578       GNUNET_free (path);
2579       return buf;
2580     }
2581   GNUNET_free (buf);
2582   GNUNET_free (path);
2583   return NULL;
2584 }
2585
2586
2587 /**
2588  * Check whether the suid bit is set on a file.
2589  * Attempts to find the file using the current
2590  * PATH environment variable as a search path.
2591  *
2592  * @param binary the name of the file to check
2593  * @return GNUNET_YES if the file is SUID, 
2594  *         GNUNET_NO if not, 
2595  *         GNUNET_SYSERR on error
2596  */
2597 static int
2598 check_gnunet_nat_binary (const char *binary)
2599 {
2600   struct stat statbuf;
2601   char *p;
2602 #ifdef MINGW
2603   SOCKET rawsock;
2604   char *binaryexe;
2605
2606   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
2607   p = get_path_from_PATH (binaryexe);
2608   free (binaryexe);
2609 #else
2610   p = get_path_from_PATH (binary);
2611 #endif
2612   if (p == NULL)
2613     {
2614       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2615                        "tcp",
2616                        _("Could not find binary `%s' in PATH!\n"),
2617                        binary);
2618       return GNUNET_NO;
2619     }
2620   if (0 != STAT (p, &statbuf))
2621     {
2622       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
2623                   _("stat (%s) failed: %s\n"), 
2624                   p,
2625                   STRERROR (errno));
2626       GNUNET_free (p);
2627       return GNUNET_SYSERR;
2628     }
2629   GNUNET_free (p);
2630 #ifndef MINGW
2631   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2632        (statbuf.st_uid == 0) )
2633     return GNUNET_YES;
2634   return GNUNET_NO;
2635 #else
2636   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
2637   if (INVALID_SOCKET == rawsock)
2638     {
2639       DWORD err = GetLastError ();
2640       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
2641                        "tcp",
2642                        "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) failed! GLE = %d\n", err);
2643       return GNUNET_NO; /* not running as administrator */
2644     }
2645   closesocket (rawsock);
2646   return GNUNET_YES;
2647 #endif
2648 }
2649
2650
2651 /**
2652  * Our (external) hostname was resolved.
2653  *
2654  * @param cls the 'struct Plugin'
2655  * @param addr NULL on error, otherwise result of DNS lookup
2656  * @param addrlen number of bytes in addr
2657  */
2658 static void
2659 process_external_ip (void *cls,
2660                      const struct sockaddr *addr,
2661                      socklen_t addrlen)
2662 {
2663   struct Plugin *plugin = cls;
2664   const struct sockaddr_in *s;
2665   struct IPv4TcpAddress t4;
2666   char buf[INET_ADDRSTRLEN];
2667
2668   plugin->ext_dns = NULL;
2669   if (addr == NULL)
2670     return;
2671   GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2672   s = (const struct sockaddr_in *) addr;
2673   t4.ipv4_addr = s->sin_addr.s_addr;
2674   if ( (plugin->behind_nat == GNUNET_YES) &&
2675        (plugin->enable_nat_server == GNUNET_YES) )
2676     {
2677       t4.t_port = htons(0);
2678       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2679                        "tcp",
2680                        "Notifying transport of address %s:%d\n", 
2681                        plugin->external_address,
2682                        0);
2683     }
2684   else
2685     {
2686       t4.t_port = htons(plugin->adv_port);
2687       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, 
2688                        "tcp",
2689                        "Notifying transport of address %s:%d\n",
2690                        plugin->external_address, 
2691                        (int) plugin->adv_port);
2692     }
2693
2694   if ((plugin->bind_address != NULL) && (plugin->behind_nat == GNUNET_NO))
2695   {
2696       GNUNET_assert (NULL != inet_ntop(AF_INET,
2697                                        &t4.ipv4_addr,
2698                                        buf,
2699                                        sizeof (buf)));
2700       if (0 != strcmp (plugin->bind_address, buf))
2701       {
2702       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2703                        "tcp",
2704                        "NAT is not enabled and specific bind address `%s' differs from external address `%s'! Not notifying about external address `%s'\n",
2705                        plugin->bind_address,
2706                        plugin->external_address,
2707                        plugin->external_address);
2708       return;
2709       }
2710   }
2711
2712   add_to_address_list (plugin, 
2713                        &t4.ipv4_addr, 
2714                        sizeof (struct in_addr));
2715
2716   plugin->env->notify_address (plugin->env->cls,
2717                                "tcp",
2718                                &t4, sizeof(t4),
2719                                GNUNET_TIME_UNIT_FOREVER_REL);
2720 }
2721
2722
2723 /**
2724  * Entry point for the plugin.
2725  *
2726  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2727  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2728  */
2729 void *
2730 libgnunet_plugin_transport_tcp_init (void *cls)
2731 {
2732   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2733     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2734      sizeof (struct WelcomeMessage)},
2735     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2736     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2737     {NULL, NULL, 0, 0}
2738   };
2739   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2740   struct GNUNET_TRANSPORT_PluginFunctions *api;
2741   struct Plugin *plugin;
2742   struct GNUNET_SERVICE_Context *service;
2743   unsigned long long aport;
2744   unsigned long long bport;
2745   unsigned int i;
2746   int behind_nat;
2747   int nat_punched;
2748   int enable_nat_client;
2749   int enable_nat_server;
2750   int enable_upnp;
2751   char *internal_address;
2752   char *external_address;
2753   char *bind_address;
2754   struct sockaddr_in in_addr;
2755   struct GNUNET_TIME_Relative idle_timeout;
2756
2757   behind_nat = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2758                                                      "transport-tcp",
2759                                                      "BEHIND_NAT");
2760   nat_punched = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2761                                                       "transport-tcp",
2762                                                       "NAT_PUNCHED");
2763   enable_nat_client = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2764                                                             "transport-tcp",
2765                                                             "ENABLE_NAT_CLIENT");
2766   enable_nat_server = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2767                                                             "transport-tcp",
2768                                                             "ENABLE_NAT_SERVER");
2769   enable_upnp = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2770                                                       "transport-tcp",
2771                                                       "ENABLE_UPNP");
2772   
2773   if ( (GNUNET_YES == enable_nat_server) &&
2774        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-server")) )
2775     {
2776       enable_nat_server = GNUNET_NO;
2777       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2778                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2779                   "gnunet-nat-server");        
2780     }
2781
2782   if ( (GNUNET_YES == enable_nat_client) &&
2783        (GNUNET_YES != check_gnunet_nat_binary("gnunet-nat-client")) )
2784     {
2785       enable_nat_client = GNUNET_NO;
2786       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2787                   _("Configuration requires `%s', but binary is not installed properly (SUID bit not set).  Option disabled.\n"),
2788                   "gnunet-nat-client"); 
2789     }
2790   
2791   external_address = NULL;
2792   if (GNUNET_OK ==
2793       GNUNET_CONFIGURATION_have_value (env->cfg,
2794                                        "transport-tcp",
2795                                        "EXTERNAL_ADDRESS"))
2796     {
2797       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2798                                                     "transport-tcp",
2799                                                     "EXTERNAL_ADDRESS",
2800                                                     &external_address);
2801     }
2802
2803   if ( (external_address != NULL) && 
2804        (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1) ) 
2805     {
2806       
2807       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2808                        "tcp",
2809                        _("Malformed %s `%s' given in configuration!\n"), 
2810                        "EXTERNAL_ADDRESS",
2811                        external_address);
2812       return NULL;   
2813     }
2814   if ( (external_address == NULL) &&
2815        (nat_punched == GNUNET_YES) )
2816     {
2817       nat_punched = GNUNET_NO;
2818       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2819                   _("Configuration says NAT was punched, but `%s' is not given.  Option ignored.\n"),
2820                   "EXTERNAL_ADDRESS");  
2821     }
2822
2823   if (GNUNET_YES == nat_punched)
2824     {
2825       enable_nat_server = GNUNET_NO;
2826       enable_upnp = GNUNET_NO;
2827     }
2828
2829   bind_address = NULL;
2830   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2831                                                            "transport-tcp",
2832                                                            "BINDTO",
2833                                                            &bind_address))
2834         {
2835           GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2836                            "tcp",
2837                            _("Binding TCP plugin to specific address: `%s'\n"),
2838                            bind_address);
2839         }
2840
2841   internal_address = NULL;
2842   if (GNUNET_OK ==
2843       GNUNET_CONFIGURATION_have_value (env->cfg,
2844                                        "transport-tcp",
2845                                        "INTERNAL_ADDRESS"))
2846     {
2847       (void) GNUNET_CONFIGURATION_get_value_string (env->cfg,
2848                                                     "transport-tcp",
2849                                                     "INTERNAL_ADDRESS",
2850                                                     &internal_address);
2851     }
2852
2853   if ( (internal_address != NULL) && 
2854        (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1) )
2855     {
2856       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2857                        "tcp",
2858                        _("Malformed %s `%s' given in configuration!\n"), 
2859                        "INTERNAL_ADDRESS",
2860                        internal_address);      
2861       GNUNET_free_non_null(internal_address);
2862       GNUNET_free_non_null(external_address);
2863       return NULL;
2864     }
2865
2866   if ((bind_address != NULL) && (internal_address != NULL))
2867   {
2868           if (0 != strcmp(internal_address, bind_address ))
2869           {
2870                           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2871                                           "tcp","Specific bind address `%s' and internal address `%s' must not differ, forcing internal address to bind address!\n", bind_address, internal_address);
2872                           GNUNET_free (internal_address);
2873                           internal_address = bind_address;
2874                           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2875                                           "tcp","New internal address `%s'\n", internal_address);
2876           }
2877   }
2878
2879   aport = 0;
2880   if ( (GNUNET_OK !=
2881         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2882                                                "transport-tcp",
2883                                                "PORT",
2884                                                &bport)) ||
2885        (bport > 65535) ||
2886        ((GNUNET_OK ==
2887          GNUNET_CONFIGURATION_get_value_number (env->cfg,
2888                                                 "transport-tcp",
2889                                                 "ADVERTISED-PORT",
2890                                                 &aport)) && 
2891         (aport > 65535)) )
2892     {
2893       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2894                        "tcp",
2895                        _("Require valid port number for service `%s' in configuration!\n"),
2896                        "transport-tcp");
2897       GNUNET_free_non_null(external_address);
2898       GNUNET_free_non_null(internal_address);
2899       return NULL;
2900     }
2901
2902   if (aport == 0)
2903     aport = bport;
2904   if (bport == 0)
2905     aport = 0;
2906
2907   if (bport != 0)
2908     {
2909       service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2910       if (service == NULL)
2911         {
2912           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2913                            "tcp",
2914                            _("Failed to start service.\n"));
2915           return NULL;
2916         }
2917     }
2918   else
2919     service = NULL;
2920
2921   plugin = GNUNET_malloc (sizeof (struct Plugin));
2922   plugin->open_port = bport;
2923   plugin->adv_port = aport;
2924   plugin->bind_address = bind_address;
2925   plugin->external_address = external_address;
2926   plugin->internal_address = internal_address;
2927   plugin->behind_nat = behind_nat;
2928   plugin->nat_punched = nat_punched;
2929   plugin->enable_nat_client = enable_nat_client;
2930   plugin->enable_nat_server = enable_nat_server;
2931   plugin->enable_upnp = enable_upnp;
2932   plugin->env = env;
2933   plugin->lsock = NULL;
2934   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2935   api->cls = plugin;
2936   api->send = &tcp_plugin_send;
2937   api->disconnect = &tcp_plugin_disconnect;
2938   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2939   api->check_address = &tcp_plugin_check_address;
2940   api->address_to_string = &tcp_address_to_string;
2941   plugin->service = service;
2942   if (service != NULL)   
2943     {
2944       plugin->server = GNUNET_SERVICE_get_server (service);
2945     }
2946   else
2947     {
2948       if (GNUNET_OK !=
2949           GNUNET_CONFIGURATION_get_value_time (env->cfg,
2950                                                "transport-tcp",
2951                                                "TIMEOUT",
2952                                                &idle_timeout))
2953         {
2954           GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2955                            "tcp",
2956                            _("Failed to find option %s in section %s!\n"),
2957                            "TIMEOUT",
2958                            "transport-tcp");
2959           GNUNET_free_non_null(external_address);
2960           GNUNET_free_non_null(internal_address);
2961           GNUNET_free (api);
2962           return NULL;
2963         }
2964       plugin->server = GNUNET_SERVER_create_with_sockets (NULL, NULL, NULL,
2965                                                           idle_timeout, GNUNET_YES);
2966     }
2967   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2968   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2969   for (i = 0;
2970        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2971        i++)
2972     plugin->handlers[i].callback_cls = plugin;
2973   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2974   GNUNET_SERVER_disconnect_notify (plugin->server,
2975                                    &disconnect_notify,
2976                                    plugin);    
2977   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2978
2979   if ( (plugin->behind_nat == GNUNET_YES) &&
2980        (plugin->enable_nat_server == GNUNET_YES) &&
2981        (GNUNET_YES != tcp_transport_start_nat_server(plugin)) )
2982     {
2983       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2984                        "tcp",
2985                        _("Failed to start %s required for NAT in %s!\n"),
2986                        "gnunet-nat-server"
2987                        "transport-tcp");
2988       GNUNET_free_non_null(external_address);
2989       GNUNET_free_non_null(internal_address);
2990       if (service != NULL)
2991         GNUNET_SERVICE_stop (service);
2992       else
2993         GNUNET_SERVER_destroy (plugin->server);
2994       GNUNET_free (api);
2995       return NULL;
2996     }
2997
2998   if (enable_nat_client == GNUNET_YES)
2999     {
3000       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(16);
3001       GNUNET_assert (plugin->nat_wait_conns != NULL);
3002     }
3003
3004   if (bport != 0)
3005     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3006                      "tcp",
3007                      _("TCP transport listening on port %llu\n"), 
3008                      bport);
3009   else
3010     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, 
3011                      "tcp",
3012                      _("TCP transport not listening on any port (client only)\n"));
3013   if (aport != bport)
3014     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
3015                      "tcp",
3016                      _("TCP transport advertises itself as being on port %llu\n"),
3017                      aport);
3018
3019   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->cfg,
3020                                                            AF_UNSPEC,
3021                                                            HOSTNAME_RESOLVE_TIMEOUT,
3022                                                            &process_hostname_ips,
3023                                                            plugin);
3024
3025   if (plugin->external_address != NULL) 
3026     {
3027       plugin->ext_dns = GNUNET_RESOLVER_ip_get (env->cfg,
3028                                                 plugin->external_address,
3029                                                 AF_INET,
3030                                                 GNUNET_TIME_UNIT_MINUTES,
3031                                                 &process_external_ip,
3032                                                 plugin);
3033     }
3034   return api;
3035 }
3036
3037
3038 /**
3039  * Exit point from the plugin.
3040  */
3041 void *
3042 libgnunet_plugin_transport_tcp_done (void *cls)
3043 {
3044   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3045   struct Plugin *plugin = api->cls;
3046   struct Session *session;
3047   struct LocalAddrList *lal;
3048   struct TCPProbeContext *tcp_probe;
3049
3050   if (plugin->ext_dns != NULL)
3051     {
3052       GNUNET_RESOLVER_request_cancel (plugin->ext_dns);
3053       plugin->ext_dns = NULL;
3054     }
3055   while (NULL != (session = plugin->sessions))
3056     disconnect_session (session);
3057   if (NULL != plugin->hostname_dns)
3058     {
3059       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
3060       plugin->hostname_dns = NULL;
3061     }
3062   if (plugin->service != NULL)
3063     GNUNET_SERVICE_stop (plugin->service);
3064   else
3065     GNUNET_SERVER_destroy (plugin->server);
3066   GNUNET_free (plugin->handlers);
3067   while (NULL != (lal = plugin->lal_head))
3068     {
3069       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
3070                                    plugin->lal_tail,
3071                                    lal);
3072       if (lal->nat != NULL)
3073         GNUNET_NAT_unregister (lal->nat);
3074       GNUNET_free_non_null (lal->external_nat_address);
3075       GNUNET_free (lal);
3076     }
3077   while (NULL != (tcp_probe = plugin->probe_head))
3078     {
3079       GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
3080                                    plugin->probe_tail,
3081                                    tcp_probe);
3082       GNUNET_CONNECTION_destroy (tcp_probe->sock, GNUNET_NO);
3083       GNUNET_free (tcp_probe);
3084     }
3085
3086   if ((plugin->behind_nat == GNUNET_YES) &&
3087       (plugin->enable_nat_server == GNUNET_YES))
3088     {
3089       if (0 != GNUNET_OS_process_kill (plugin->server_proc, SIGTERM))
3090         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
3091       GNUNET_OS_process_wait (plugin->server_proc);
3092       GNUNET_OS_process_close (plugin->server_proc);
3093       plugin->server_proc = NULL;
3094     }
3095   GNUNET_free_non_null(plugin->bind_address);
3096   GNUNET_free (plugin);
3097   GNUNET_free (api);
3098   return NULL;
3099 }
3100
3101 /* end of plugin_transport_tcp.c */