65aea96e01f087a7ace5e7cdb15b191c5fe71120
[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_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
39
40 #define DEBUG_TCP GNUNET_YES
41 #define DEBUG_TCP_NAT GNUNET_YES
42
43 /**
44  * How long until we give up on transmitting the welcome message?
45  */
46 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
47
48
49 /**
50  * Initial handshake message for a session.
51  */
52 struct WelcomeMessage
53 {
54   /**
55    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
56    */
57   struct GNUNET_MessageHeader header;
58
59   /**
60    * Identity of the node connecting (TCP client)
61    */
62   struct GNUNET_PeerIdentity clientIdentity;
63
64 };
65
66 /**
67  * Basically a WELCOME message, but with the purpose
68  * of giving the waiting peer a client handle to use
69  */
70 struct TCP_NAT_ProbeMessage
71 {
72   /**
73    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
74    */
75   struct GNUNET_MessageHeader header;
76
77   /**
78    * Identity of the sender of the message.
79    */
80   struct GNUNET_PeerIdentity clientIdentity;
81
82 };
83
84 /**
85  * Context for sending a NAT probe via TCP.
86  */
87 struct TCPProbeContext
88 {
89   /**
90    * Probe connection.
91    */
92   struct GNUNET_CONNECTION_Handle *sock;
93
94   /**
95    * Message to be sent.
96    */
97   struct TCP_NAT_ProbeMessage message;
98
99   /**
100    * Handle to the transmission.
101    */
102   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
103
104   /**
105    * Transport plugin handle.
106    */
107   struct Plugin *plugin;
108 };
109
110
111 /**
112  * Network format for IPv4 addresses.
113  */
114 struct IPv4TcpAddress
115 {
116   /**
117    * IPv4 address, in network byte order.
118    */
119   uint32_t ipv4_addr GNUNET_PACKED;
120
121   /**
122    * Port number, in network byte order.
123    */
124   uint16_t t_port GNUNET_PACKED;
125
126 };
127
128
129 /**
130  * Network format for IPv6 addresses.
131  */
132 struct IPv6TcpAddress
133 {
134   /**
135    * IPv6 address.
136    */
137   struct in6_addr ipv6_addr GNUNET_PACKED;
138
139   /**
140    * Port number, in network byte order.
141    */
142   uint16_t t6_port GNUNET_PACKED;
143
144 };
145
146 /**
147  * Encapsulation of all of the state of the plugin.
148  */
149 struct Plugin;
150
151
152 /**
153  * Local network addresses (actual IP address follows this struct).
154  * PORT is NOT included!
155  */
156 struct LocalAddrList
157 {
158
159   /**
160    * This is a doubly linked list.
161    */
162   struct LocalAddrList *next;
163
164   /**
165    * This is a doubly linked list.
166    */
167   struct LocalAddrList *prev;
168
169   /**
170    * Number of bytes of the address that follow
171    */
172   size_t size;
173
174 };
175
176
177 /**
178  * Information kept for each message that is yet to
179  * be transmitted.
180  */
181 struct PendingMessage
182 {
183
184   /**
185    * This is a doubly-linked list.
186    */
187   struct PendingMessage *next;
188
189   /**
190    * This is a doubly-linked list.
191    */
192   struct PendingMessage *prev;
193
194   /**
195    * The pending message
196    */
197   const char *msg;
198
199   /**
200    * Continuation function to call once the message
201    * has been sent.  Can be NULL if there is no
202    * continuation to call.
203    */
204   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
205
206   /**
207    * Closure for transmit_cont.
208    */
209   void *transmit_cont_cls;
210
211   /**
212    * Timeout value for the pending message.
213    */
214   struct GNUNET_TIME_Absolute timeout;
215
216   /**
217    * So that the gnunet-service-transport can group messages together,
218    * these pending messages need to accept a message buffer and size
219    * instead of just a GNUNET_MessageHeader.
220    */
221   size_t message_size;
222
223 };
224
225
226 /**
227  * Session handle for TCP connections.
228  */
229 struct Session
230 {
231
232   /**
233    * API requirement.
234    */
235   struct SessionHeader header;
236
237   /**
238    * Stored in a linked list.
239    */
240   struct Session *next;
241
242   /**
243    * Pointer to the global plugin struct.
244    */
245   struct Plugin *plugin;
246
247   /**
248    * The client (used to identify this connection)
249    */
250   struct GNUNET_SERVER_Client *client;
251
252   /**
253    * Messages currently pending for transmission
254    * to this peer, if any.
255    */
256   struct PendingMessage *pending_messages_head;
257
258   /**
259    * Messages currently pending for transmission
260    * to this peer, if any.
261    */
262   struct PendingMessage *pending_messages_tail;
263
264   /**
265    * Handle for pending transmission request.
266    */
267   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
268
269   /**
270    * To whom are we talking to (set to our identity
271    * if we are still waiting for the welcome message)
272    */
273   struct GNUNET_PeerIdentity target;
274
275   /**
276    * ID of task used to delay receiving more to throttle sender.
277    */
278   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
279
280   /**
281    * Address of the other peer (either based on our 'connect'
282    * call or on our 'accept' call).
283    */
284   void *connect_addr;
285
286   /**
287    * Last activity on this connection.  Used to select preferred
288    * connection.
289    */
290   struct GNUNET_TIME_Absolute last_activity;
291
292   /**
293    * Length of connect_addr.
294    */
295   size_t connect_alen;
296
297   /**
298    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
299    */
300   int expecting_welcome;
301
302   /**
303    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
304    */
305   int inbound;
306
307 };
308
309
310 /**
311  * Encapsulation of all of the state of the plugin.
312  */
313 struct Plugin
314 {
315   /**
316    * Our environment.
317    */
318   struct GNUNET_TRANSPORT_PluginEnvironment *env;
319
320   /**
321    * The listen socket.
322    */
323   struct GNUNET_CONNECTION_Handle *lsock;
324
325   /**
326    * stdout pipe handle for the gnunet-nat-server process
327    */
328   struct GNUNET_DISK_PipeHandle *server_stdout;
329
330   /**
331    * stdout file handle (for reading) for the gnunet-nat-server process
332    */
333   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
334
335   /**
336    * ID of select gnunet-nat-server stdout read task
337    */
338   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
339
340   /**
341    * The process id of the server process (if behind NAT)
342    */
343   pid_t server_pid;
344
345   /**
346    * List of open TCP sessions.
347    */
348   struct Session *sessions;
349
350   /**
351    * Handle to the network service.
352    */
353   struct GNUNET_SERVICE_Context *service;
354
355   /**
356    * Handle to the server for this service.
357    */
358   struct GNUNET_SERVER_Handle *server;
359
360   /**
361    * Copy of the handler array where the closures are
362    * set to this struct's instance.
363    */
364   struct GNUNET_SERVER_MessageHandler *handlers;
365
366   /**
367    * Handle for request of hostname resolution, non-NULL if pending.
368    */
369   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
370
371   /**
372    * Map of peers we have tried to contact behind a NAT
373    */
374   struct GNUNET_CONTAINER_MultiHashMap *nat_wait_conns;
375
376   /**
377    * The external address given to us by the user.  Must be actual
378    * outside visible address for NAT punching to work.
379    */
380   char *external_address;
381
382   /**
383    * The internal address given to us by the user (or discovered).
384    */
385   char *internal_address;
386
387   /**
388    * Address given for us to bind to (ONLY).
389    */
390   char *bind_address;
391
392   /**
393    * List of our IP addresses.
394    */
395   struct LocalAddrList *lal_head;
396
397   /**
398    * Tail of our IP address list.
399    */
400   struct LocalAddrList *lal_tail;
401
402   /**
403    * ID of task used to update our addresses when one expires.
404    */
405   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
406
407   /**
408    * Port that we are actually listening on.
409    */
410   uint16_t open_port;
411
412   /**
413    * Port that the user said we would have visible to the
414    * rest of the world.
415    */
416   uint16_t adv_port;
417
418   /**
419    * Is this transport configured to be behind a NAT?
420    */
421   int behind_nat;
422
423   /**
424    * Is this transport configured to allow connections to NAT'd peers?
425    */
426   int allow_nat;
427
428   /**
429    * Should this transport advertise only NAT addresses (port set to 0)?
430    * If not, all addresses will be duplicated for NAT punching and regular
431    * ports.
432    */
433   int only_nat_addresses;
434
435 };
436
437
438 static void
439 add_to_address_list (struct Plugin *plugin,
440                      const void *arg,
441                      size_t arg_size)
442 {
443   struct LocalAddrList *lal;
444
445   lal = plugin->lal_head;
446   while (NULL != lal)
447     {
448       if ( (lal->size == arg_size) &&
449            (0 == memcmp (&lal[1], arg, arg_size)) )
450         return;
451       lal = lal->next;
452     }
453   lal = GNUNET_malloc (sizeof (struct LocalAddrList) + arg_size);
454   lal->size = arg_size;
455   memcpy (&lal[1], arg, arg_size);
456   GNUNET_CONTAINER_DLL_insert (plugin->lal_head,
457                                plugin->lal_tail,
458                                lal);
459 }
460
461
462 static int
463 check_local_addr (struct Plugin *plugin,
464                   const void *arg,
465                   size_t arg_size)
466 {
467   struct LocalAddrList *lal;
468
469   lal = plugin->lal_head;
470   while (NULL != lal)
471     {
472       if ( (lal->size == arg_size) &&
473            (0 == memcmp (&lal[1], arg, arg_size)) )
474         return GNUNET_OK;
475       lal = lal->next;
476     }
477   return GNUNET_SYSERR;
478 }
479
480
481 /**
482  * Function called for a quick conversion of the binary address to
483  * a numeric address.  Note that the caller must not free the
484  * address and that the next call to this function is allowed
485  * to override the address again.
486  *
487  * @param cls closure ('struct Plugin*')
488  * @param addr binary address
489  * @param addrlen length of the address
490  * @return string representing the same address
491  */
492 static const char*
493 tcp_address_to_string (void *cls,
494                        const void *addr,
495                        size_t addrlen)
496 {
497   static char rbuf[INET6_ADDRSTRLEN + 12];
498   char buf[INET6_ADDRSTRLEN];
499   const void *sb;
500   struct in_addr a4;
501   struct in6_addr a6;
502   const struct IPv4TcpAddress *t4;
503   const struct IPv6TcpAddress *t6;
504   int af;
505   uint16_t port;
506
507   if (addrlen == sizeof (struct IPv6TcpAddress))
508     {
509       t6 = addr;
510       af = AF_INET6;
511       port = ntohs (t6->t6_port);
512       memcpy (&a6, &t6->ipv6_addr, sizeof (a6));
513       sb = &a6;
514     }
515   else if (addrlen == sizeof (struct IPv4TcpAddress))
516     {
517       t4 = addr;
518       af = AF_INET;
519       port = ntohs (t4->t_port);
520       memcpy (&a4, &t4->ipv4_addr, sizeof (a4));
521       sb = &a4;
522     }
523   else
524     {
525       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
526                   _("Unexpected address length: %u\n"),
527                   addrlen);
528       GNUNET_break (0);
529       return NULL;
530     }
531   if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
532     {
533       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
534       return NULL;
535     }
536   GNUNET_snprintf (rbuf,
537                    sizeof (rbuf),
538                    (af == AF_INET6) ? "[%s]:%u" : "%s:%u",
539                    buf,
540                    port);
541   return rbuf;
542 }
543
544
545 /**
546  * Find the session handle for the given client.
547  *
548  * @return NULL if no matching session exists
549  */
550 static struct Session *
551 find_session_by_client (struct Plugin *plugin,
552                         const struct GNUNET_SERVER_Client *client)
553 {
554   struct Session *ret;
555
556   ret = plugin->sessions;
557   while ((ret != NULL) && (client != ret->client))
558     ret = ret->next;
559   return ret;
560 }
561
562 /**
563  * Create a new session.  Also queues a welcome message.
564  *
565  * @param plugin us
566  * @param target peer to connect to
567  * @param client client to use
568  * @param is_nat this a NAT session, we should wait for a client to
569  *               connect to us from an address, then assign that to
570  *               the session
571  * @return new session object
572  */
573 static struct Session *
574 create_session (struct Plugin *plugin,
575                 const struct GNUNET_PeerIdentity *target,
576                 struct GNUNET_SERVER_Client *client, int is_nat)
577 {
578   struct Session *ret;
579   struct PendingMessage *pm;
580   struct WelcomeMessage welcome;
581
582   if (is_nat != GNUNET_YES)
583     GNUNET_assert (client != NULL);
584   else
585     GNUNET_assert (client == NULL);
586
587 #if DEBUG_TCP
588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
589                    "Creating new session for peer `%4s'\n",
590                    GNUNET_i2s (target));
591 #endif
592   ret = GNUNET_malloc (sizeof (struct Session));
593   ret->last_activity = GNUNET_TIME_absolute_get ();
594   ret->plugin = plugin;
595   if (is_nat != GNUNET_YES) /* If not a NAT WAIT conn, add it to global list */
596     {
597       ret->next = plugin->sessions;
598       plugin->sessions = ret;
599     }
600   ret->client = client;
601   ret->target = *target;
602   ret->expecting_welcome = GNUNET_YES;
603   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
604   pm->msg = (const char*) &pm[1];
605   pm->message_size = sizeof (struct WelcomeMessage);
606   welcome.header.size = htons (sizeof (struct WelcomeMessage));
607   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
608   welcome.clientIdentity = *plugin->env->my_identity;
609   memcpy (&pm[1], &welcome, sizeof (welcome));
610   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
611   GNUNET_STATISTICS_update (plugin->env->stats,
612                             gettext_noop ("# bytes currently in TCP buffers"),
613                             pm->message_size,
614                             GNUNET_NO);
615   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
616                                ret->pending_messages_tail,
617                                pm);
618   if (is_nat != GNUNET_YES)
619     GNUNET_STATISTICS_update (plugin->env->stats,
620                               gettext_noop ("# TCP sessions active"),
621                               1,
622                               GNUNET_NO);
623   return ret;
624 }
625
626
627 /**
628  * If we have pending messages, ask the server to
629  * transmit them (schedule the respective tasks, etc.)
630  *
631  * @param session for which session should we do this
632  */
633 static void process_pending_messages (struct Session *session);
634
635
636 /**
637  * Function called to notify a client about the socket
638  * being ready to queue more data.  "buf" will be
639  * NULL and "size" zero if the socket was closed for
640  * writing in the meantime.
641  *
642  * @param cls closure
643  * @param size number of bytes available in buf
644  * @param buf where the callee should write the message
645  * @return number of bytes written to buf
646  */
647 static size_t
648 do_transmit (void *cls, size_t size, void *buf)
649 {
650   struct Session *session = cls;
651   struct GNUNET_PeerIdentity pid;
652   struct Plugin *plugin;
653   struct PendingMessage *pos;
654   struct PendingMessage *hd;
655   struct PendingMessage *tl;
656   struct GNUNET_TIME_Absolute now;
657   char *cbuf;
658   size_t ret;
659
660   session->transmit_handle = NULL;
661   plugin = session->plugin;
662   if (buf == NULL)
663     {
664 #if DEBUG_TCP
665       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
667                        GNUNET_i2s (&session->target));
668 #endif
669       /* timeout; cancel all messages that have already expired */
670       hd = NULL;
671       tl = NULL;
672       ret = 0;
673       now = GNUNET_TIME_absolute_get ();
674       while ( (NULL != (pos = session->pending_messages_head)) &&
675               (pos->timeout.value <= now.value) )
676         {
677           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
678                                        session->pending_messages_tail,
679                                        pos);
680 #if DEBUG_TCP
681           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
682                            "Failed to transmit %u byte message to `%4s'.\n",
683                            pos->message_size,
684                            GNUNET_i2s (&session->target));
685 #endif
686           ret += pos->message_size;
687           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
688         }
689       /* do this call before callbacks (so that if callbacks destroy
690          session, they have a chance to cancel actions done by this
691          call) */
692       process_pending_messages (session);
693       pid = session->target;
694       /* no do callbacks and do not use session again since
695          the callbacks may abort the session */
696       while (NULL != (pos = hd))
697         {
698           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
699           if (pos->transmit_cont != NULL)
700             pos->transmit_cont (pos->transmit_cont_cls,
701                                 &pid, GNUNET_SYSERR);
702           GNUNET_free (pos);
703         }
704       GNUNET_STATISTICS_update (plugin->env->stats,
705                                 gettext_noop ("# bytes currently in TCP buffers"),
706                                 - (int64_t) ret,
707                                 GNUNET_NO);
708       GNUNET_STATISTICS_update (plugin->env->stats,
709                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
710                                 ret,
711                                 GNUNET_NO);
712       return 0;
713     }
714   /* copy all pending messages that would fit */
715   ret = 0;
716   cbuf = buf;
717   hd = NULL;
718   tl = NULL;
719   while (NULL != (pos = session->pending_messages_head))
720     {
721       if (ret + pos->message_size > size)
722         break;
723       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
724                                    session->pending_messages_tail,
725                                    pos);
726       GNUNET_assert (size >= pos->message_size);
727       /* FIXME: this memcpy can be up to 7% of our total runtime */
728       memcpy (cbuf, pos->msg, pos->message_size);
729       cbuf += pos->message_size;
730       ret += pos->message_size;
731       size -= pos->message_size;
732       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
733     }
734   /* schedule 'continuation' before callbacks so that callbacks that
735      cancel everything don't cause us to use a session that no longer
736      exists... */
737   process_pending_messages (session);
738   session->last_activity = GNUNET_TIME_absolute_get ();
739   pid = session->target;
740   /* we'll now call callbacks that may cancel the session; hence
741      we should not use 'session' after this point */
742   while (NULL != (pos = hd))
743     {
744       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
745       if (pos->transmit_cont != NULL)
746         pos->transmit_cont (pos->transmit_cont_cls,
747                             &pid, GNUNET_OK);
748       GNUNET_free (pos);
749     }
750   GNUNET_assert (hd == NULL);
751   GNUNET_assert (tl == NULL);
752 #if DEBUG_TCP > 1
753   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
754              "Transmitting %u bytes\n", ret);
755 #endif
756   GNUNET_STATISTICS_update (plugin->env->stats,
757                             gettext_noop ("# bytes currently in TCP buffers"),
758                             - (int64_t) ret,
759                             GNUNET_NO);
760   GNUNET_STATISTICS_update (plugin->env->stats,
761                             gettext_noop ("# bytes transmitted via TCP"),
762                             ret,
763                             GNUNET_NO);
764   return ret;
765 }
766
767
768 /**
769  * If we have pending messages, ask the server to
770  * transmit them (schedule the respective tasks, etc.)
771  *
772  * @param session for which session should we do this
773  */
774 static void
775 process_pending_messages (struct Session *session)
776 {
777   struct PendingMessage *pm;
778
779   GNUNET_assert (session->client != NULL);
780   if (session->transmit_handle != NULL)
781     return;
782   if (NULL == (pm = session->pending_messages_head))
783     return;
784
785   session->transmit_handle
786     = GNUNET_SERVER_notify_transmit_ready (session->client,
787                                            pm->message_size,
788                                            GNUNET_TIME_absolute_get_remaining
789                                            (pm->timeout),
790                                            &do_transmit, session);
791 }
792
793
794 /**
795  * Functions with this signature are called whenever we need
796  * to close a session due to a disconnect or failure to
797  * establish a connection.
798  *
799  * @param session session to close down
800  */
801 static void
802 disconnect_session (struct Session *session)
803 {
804   struct Session *prev;
805   struct Session *pos;
806   struct PendingMessage *pm;
807
808 #if DEBUG_TCP
809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810                    "Disconnecting from `%4s' at %s (session %p).\n",
811                    GNUNET_i2s (&session->target),
812                    (session->connect_addr != NULL) ?
813                    tcp_address_to_string (session->plugin,
814                                           session->connect_addr,
815                                           session->connect_alen) : "*",
816                    session);
817 #endif
818   /* remove from session list */
819   prev = NULL;
820   pos = session->plugin->sessions;
821   while (pos != session)
822     {
823       prev = pos;
824       pos = pos->next;
825     }
826   if (prev == NULL)
827     session->plugin->sessions = session->next;
828   else
829     prev->next = session->next;
830   session->plugin->env->session_end (session->plugin->env->cls,
831                                      &session->target,
832                                      session);
833   /* clean up state */
834   if (session->transmit_handle != NULL)
835     {
836       GNUNET_CONNECTION_notify_transmit_ready_cancel
837         (session->transmit_handle);
838       session->transmit_handle = NULL;
839     }
840   while (NULL != (pm = session->pending_messages_head))
841     {
842 #if DEBUG_TCP
843       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
844
845                        pm->transmit_cont != NULL
846                        ? "Could not deliver message to `%4s'.\n"
847                        :
848                        "Could not deliver message to `%4s', notifying.\n",
849                        GNUNET_i2s (&session->target));
850 #endif
851       GNUNET_STATISTICS_update (session->plugin->env->stats,
852                                 gettext_noop ("# bytes currently in TCP buffers"),
853                                 - (int64_t) pm->message_size,
854                                 GNUNET_NO);
855       GNUNET_STATISTICS_update (session->plugin->env->stats,
856                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
857                                 pm->message_size,
858                                 GNUNET_NO);
859       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
860                                    session->pending_messages_tail,
861                                    pm);
862       if (NULL != pm->transmit_cont)
863         pm->transmit_cont (pm->transmit_cont_cls,
864                            &session->target, GNUNET_SYSERR);
865       GNUNET_free (pm);
866     }
867   GNUNET_break (session->client != NULL);
868   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
869     {
870       GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
871                                session->receive_delay_task);
872       if (session->client != NULL)
873         GNUNET_SERVER_receive_done (session->client,
874                                     GNUNET_SYSERR);     
875     }
876   if (session->client != NULL)  
877     GNUNET_SERVER_client_drop (session->client);
878   GNUNET_STATISTICS_update (session->plugin->env->stats,
879                             gettext_noop ("# TCP sessions active"),
880                             -1,
881                             GNUNET_NO);
882   GNUNET_free_non_null (session->connect_addr);
883   GNUNET_free (session);
884 }
885
886
887 /**
888  * Given two otherwise equivalent sessions, pick the better one.
889  *
890  * @param s1 one session (also default)
891  * @param s2 other session
892  * @return "better" session (more active)
893  */
894 static struct Session *
895 select_better_session (struct Session *s1,
896                        struct Session *s2)
897 {
898   if (s1 == NULL)
899     return s2;
900   if (s2 == NULL)
901     return s1;
902   if ( (s1->expecting_welcome == GNUNET_NO) &&
903        (s2->expecting_welcome == GNUNET_YES) )
904     return s1;
905   if ( (s1->expecting_welcome == GNUNET_YES) &&
906        (s2->expecting_welcome == GNUNET_NO) )
907     return s2;
908   if (s1->last_activity.value < s2->last_activity.value)
909     return s2;
910   if (s1->last_activity.value > s2->last_activity.value)
911     return s1;
912   if ( (GNUNET_YES == s1->inbound) &&
913        (GNUNET_NO  == s2->inbound) )
914     return s1;
915   if ( (GNUNET_NO  == s1->inbound) &&
916        (GNUNET_YES == s2->inbound) )
917     return s2;
918   return s1;
919 }
920
921
922 /**
923  * We learned about a peer (possibly behind NAT) so run the
924  * gnunet-nat-client to send dummy ICMP responses
925  *
926  * @param plugin the plugin for this transport
927  * @param addr the address of the peer
928  * @param addrlen the length of the address
929  */
930 void
931 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
932 {
933   char inet4[INET_ADDRSTRLEN];
934   char *address_as_string;
935   char *port_as_string;
936   pid_t pid;
937   const struct sockaddr *sa = (const struct sockaddr *)addr;
938
939 #if DEBUG_TCP_NAT
940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941                   _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
942 #endif
943
944   if (addrlen < sizeof (struct sockaddr))
945     return;
946
947   switch (sa->sa_family)
948     {
949     case AF_INET:
950       if (addrlen != sizeof (struct sockaddr_in))
951         return;
952       if (NULL == inet_ntop (AF_INET,
953                              &((struct sockaddr_in *) sa)->sin_addr,
954                              inet4, INET_ADDRSTRLEN))
955         {
956           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
957           return;
958         }
959       address_as_string = GNUNET_strdup (inet4);
960       break;
961     case AF_INET6:
962     default:
963       return;
964     }
965
966   GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
967 #if DEBUG_TCP_NAT
968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
969                   _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
970 #endif
971
972   /* Start the client process */
973   pid = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
974   GNUNET_free(address_as_string);
975   GNUNET_free(port_as_string);
976   GNUNET_OS_process_wait (pid);
977 }
978
979
980 /**
981  * Function that can be used by the transport service to transmit
982  * a message using the plugin.   Note that in the case of a
983  * peer disconnecting, the continuation MUST be called
984  * prior to the disconnect notification itself.  This function
985  * will be called with this peer's HELLO message to initiate
986  * a fresh connection to another peer.
987  *
988  * @param cls closure
989  * @param target who should receive this message
990  * @param msg the message to transmit
991  * @param msgbuf_size number of bytes in 'msg'
992  * @param priority how important is the message (most plugins will
993  *                 ignore message priority and just FIFO)
994  * @param timeout how long to wait at most for the transmission (does not
995  *                require plugins to discard the message after the timeout,
996  *                just advisory for the desired delay; most plugins will ignore
997  *                this as well)
998  * @param session which session must be used (or NULL for "any")
999  * @param addr the address to use (can be NULL if the plugin
1000  *                is "on its own" (i.e. re-use existing TCP connection))
1001  * @param addrlen length of the address in bytes
1002  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1003  *                GNUNET_NO means the plugin may use any other address and
1004  *                GNUNET_SYSERR means that only reliable existing
1005  *                bi-directional connections should be used (regardless
1006  *                of address)
1007  * @param cont continuation to call once the message has
1008  *        been transmitted (or if the transport is ready
1009  *        for the next transmission call; or if the
1010  *        peer disconnected...); can be NULL
1011  * @param cont_cls closure for cont
1012  * @return number of bytes used (on the physical network, with overheads);
1013  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1014  *         and does NOT mean that the message was not transmitted (DV and NAT)
1015  */
1016 static ssize_t
1017 tcp_plugin_send (void *cls,
1018                  const struct GNUNET_PeerIdentity *target,
1019                  const char *msg,
1020                  size_t msgbuf_size,
1021                  uint32_t priority,
1022                  struct GNUNET_TIME_Relative timeout,
1023                  struct Session *session,
1024                  const void *addr,
1025                  size_t addrlen,
1026                  int force_address,
1027                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1028 {
1029   struct Plugin *plugin = cls;
1030   struct Session *cand_session;
1031   struct Session *next;
1032   struct PendingMessage *pm;
1033   struct GNUNET_CONNECTION_Handle *sa;
1034   int af;
1035   const void *sb;
1036   size_t sbs;
1037   struct sockaddr_in a4;
1038   struct sockaddr_in6 a6;
1039   const struct IPv4TcpAddress *t4;
1040   const struct IPv6TcpAddress *t6;
1041   unsigned int is_natd;
1042
1043   GNUNET_STATISTICS_update (plugin->env->stats,
1044                             gettext_noop ("# bytes TCP was asked to transmit"),
1045                             msgbuf_size,
1046                             GNUNET_NO);
1047   /* FIXME: we could do this cheaper with a hash table
1048      where we could restrict the iteration to entries that match
1049      the target peer... */
1050   is_natd = GNUNET_NO;
1051   if (session == NULL)
1052     {
1053       cand_session = NULL;
1054       next = plugin->sessions;
1055       while (NULL != (session = next))
1056         {
1057           next = session->next;
1058           GNUNET_assert (session->client != NULL);
1059           if (0 != memcmp (target,
1060                            &session->target,
1061                            sizeof (struct GNUNET_PeerIdentity)))
1062             continue;
1063           if ( ( (GNUNET_SYSERR == force_address) &&
1064                  (session->expecting_welcome == GNUNET_NO) ) ||
1065                (GNUNET_NO == force_address) )
1066             {
1067               cand_session = select_better_session (cand_session,
1068                                                     session);
1069               continue;
1070             }
1071           if (GNUNET_SYSERR == force_address)
1072             continue;
1073           GNUNET_break (GNUNET_YES == force_address);
1074           if (addr == NULL)
1075             {
1076               GNUNET_break (0);
1077               break;
1078             }
1079           if (session->inbound == GNUNET_YES)
1080             continue;
1081           if (addrlen != session->connect_alen)
1082             continue;
1083           if (0 != memcmp (session->connect_addr,
1084                            addr,
1085                            addrlen))
1086             continue;
1087           cand_session = select_better_session (cand_session,
1088                                                 session);       
1089         }
1090       session = cand_session;
1091     }
1092   if ( (session == NULL) &&
1093        (addr == NULL) )
1094     {
1095 #if DEBUG_TCP
1096       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1098                        GNUNET_i2s (target));
1099 #endif
1100       GNUNET_STATISTICS_update (plugin->env->stats,
1101                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1102                                 msgbuf_size,
1103                                 GNUNET_NO);
1104       return -1;
1105     }
1106   if (session == NULL)
1107     {
1108       if (addrlen == sizeof (struct IPv6TcpAddress))
1109         {
1110           t6 = addr;
1111           af = AF_INET6;
1112           memset (&a6, 0, sizeof (a6));
1113 #if HAVE_SOCKADDR_IN_SIN_LEN
1114           a6.sin6_len = sizeof (a6);
1115 #endif
1116           a6.sin6_family = AF_INET6;
1117           a6.sin6_port = t6->t6_port;
1118           if (t6->t6_port == 0)
1119             is_natd = GNUNET_YES;
1120           memcpy (&a6.sin6_addr,
1121                   &t6->ipv6_addr,
1122                   sizeof (struct in6_addr));
1123           sb = &a6;
1124           sbs = sizeof (a6);
1125         }
1126       else if (addrlen == sizeof (struct IPv4TcpAddress))
1127         {
1128           t4 = addr;
1129           af = AF_INET;
1130           memset (&a4, 0, sizeof (a4));
1131 #if HAVE_SOCKADDR_IN_SIN_LEN
1132           a4.sin_len = sizeof (a4);
1133 #endif
1134           a4.sin_family = AF_INET;
1135           a4.sin_port = t4->t_port;
1136           if (t4->t_port == 0)
1137             is_natd = GNUNET_YES;
1138           a4.sin_addr.s_addr = t4->ipv4_addr;
1139           sb = &a4;
1140           sbs = sizeof (a4);
1141         }
1142       else
1143         {
1144           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1145                            _("Address of unexpected length: %u\n"),
1146                            addrlen);
1147           GNUNET_break (0);
1148           return -1;
1149         }
1150
1151       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1152         return -1; /* NAT client only works with IPv4 addresses */
1153
1154
1155       if ( (plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1156            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1157         {
1158 #if DEBUG_TCP_NAT
1159           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1160                            _("Found valid IPv4 NAT address!\n"));
1161 #endif
1162           session = create_session (plugin,
1163                                     target,
1164                                     NULL, is_natd);
1165
1166           /* create new message entry */
1167           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1168           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1169           pm->msg = (const char*) &pm[1];
1170           memcpy (&pm[1], msg, msgbuf_size);
1171           /* FIXME: this memcpy can be up to 7% of our total run-time
1172              (for transport service) */
1173           pm->message_size = msgbuf_size;
1174           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1175           pm->transmit_cont = cont;
1176           pm->transmit_cont_cls = cont_cls;
1177
1178           /* append pm to pending_messages list */
1179           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1180                                              session->pending_messages_tail,
1181                                              session->pending_messages_tail,
1182                                              pm);
1183
1184           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1185 #if DEBUG_TCP_NAT
1186           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1188                            GNUNET_i2s (target),
1189                            GNUNET_a2s (sb, sbs));
1190 #endif
1191           run_gnunet_nat_client (plugin, sb, sbs);
1192           return 0;
1193         }
1194       else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1195         {
1196           /* Only do one NAT punch attempt per peer identity */
1197           return -1;
1198         }
1199       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
1200                                                    af, sb, sbs);
1201       if (sa == NULL)
1202         {
1203 #if DEBUG_TCP
1204           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1205                            "Failed to create connection to `%4s' at `%s'\n",
1206                            GNUNET_i2s (target),
1207                            GNUNET_a2s (sb, sbs));
1208 #endif
1209           GNUNET_STATISTICS_update (plugin->env->stats,
1210                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1211                                     msgbuf_size,
1212                                     GNUNET_NO);
1213           return -1;
1214         }
1215 #if DEBUG_TCP
1216       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1218                        GNUNET_i2s (target),
1219                        GNUNET_a2s (sb, sbs));
1220 #endif
1221       session = create_session (plugin,
1222                                 target,
1223                                 GNUNET_SERVER_connect_socket (plugin->server,
1224                                                               sa), is_natd);
1225       session->connect_addr = GNUNET_malloc (addrlen);
1226       memcpy (session->connect_addr,
1227               addr,
1228               addrlen);
1229       session->connect_alen = addrlen;
1230     }
1231   GNUNET_assert (session != NULL);
1232   GNUNET_assert (session->client != NULL);
1233   GNUNET_STATISTICS_update (plugin->env->stats,
1234                             gettext_noop ("# bytes currently in TCP buffers"),
1235                             msgbuf_size,
1236                             GNUNET_NO);
1237   /* create new message entry */
1238   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1239   pm->msg = (const char*) &pm[1];
1240   memcpy (&pm[1], msg, msgbuf_size);
1241   pm->message_size = msgbuf_size;
1242   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1243   pm->transmit_cont = cont;
1244   pm->transmit_cont_cls = cont_cls;
1245
1246   /* append pm to pending_messages list */
1247   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1248                                      session->pending_messages_tail,
1249                                      session->pending_messages_tail,
1250                                      pm);
1251 #if DEBUG_TCP
1252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1254                    msgbuf_size,
1255                    GNUNET_i2s (target));
1256 #endif
1257   process_pending_messages (session);
1258   return msgbuf_size;
1259 }
1260
1261
1262 /**
1263  * Function that can be called to force a disconnect from the
1264  * specified neighbour.  This should also cancel all previously
1265  * scheduled transmissions.  Obviously the transmission may have been
1266  * partially completed already, which is OK.  The plugin is supposed
1267  * to close the connection (if applicable) and no longer call the
1268  * transmit continuation(s).
1269  *
1270  * Finally, plugin MUST NOT call the services's receive function to
1271  * notify the service that the connection to the specified target was
1272  * closed after a getting this call.
1273  *
1274  * @param cls closure
1275  * @param target peer for which the last transmission is
1276  *        to be cancelled
1277  */
1278 static void
1279 tcp_plugin_disconnect (void *cls,
1280                        const struct GNUNET_PeerIdentity *target)
1281 {
1282   struct Plugin *plugin = cls;
1283   struct Session *session;
1284   struct Session *next;
1285   struct PendingMessage *pm;
1286
1287 #if DEBUG_TCP
1288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1289                    "Asked to cancel session with `%4s'\n",
1290                    GNUNET_i2s (target));
1291 #endif
1292   next = plugin->sessions;
1293   while (NULL != (session = next))
1294     {
1295       next = session->next;
1296       if (0 != memcmp (target,
1297                        &session->target,
1298                        sizeof (struct GNUNET_PeerIdentity)))
1299         continue;
1300       pm = session->pending_messages_head;
1301       while (pm != NULL)
1302         {
1303           pm->transmit_cont = NULL;
1304           pm->transmit_cont_cls = NULL;
1305           pm = pm->next;
1306         }
1307       disconnect_session (session);
1308     }
1309 }
1310
1311
1312 /**
1313  * Context for address to string conversion.
1314  */
1315 struct PrettyPrinterContext
1316 {
1317   /**
1318    * Function to call with the result.
1319    */
1320   GNUNET_TRANSPORT_AddressStringCallback asc;
1321
1322   /**
1323    * Clsoure for 'asc'.
1324    */
1325   void *asc_cls;
1326
1327   /**
1328    * Port to add after the IP address.
1329    */
1330   uint16_t port;
1331 };
1332
1333
1334 /**
1335  * Append our port and forward the result.
1336  *
1337  * @param cls the 'struct PrettyPrinterContext*'
1338  * @param hostname hostname part of the address
1339  */
1340 static void
1341 append_port (void *cls, const char *hostname)
1342 {
1343   struct PrettyPrinterContext *ppc = cls;
1344   char *ret;
1345
1346   if (hostname == NULL)
1347     {
1348       ppc->asc (ppc->asc_cls, NULL);
1349       GNUNET_free (ppc);
1350       return;
1351     }
1352   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1353   ppc->asc (ppc->asc_cls, ret);
1354   GNUNET_free (ret);
1355 }
1356
1357
1358 /**
1359  * Convert the transports address to a nice, human-readable
1360  * format.
1361  *
1362  * @param cls closure
1363  * @param type name of the transport that generated the address
1364  * @param addr one of the addresses of the host, NULL for the last address
1365  *        the specific address format depends on the transport
1366  * @param addrlen length of the address
1367  * @param numeric should (IP) addresses be displayed in numeric form?
1368  * @param timeout after how long should we give up?
1369  * @param asc function to call on each string
1370  * @param asc_cls closure for asc
1371  */
1372 static void
1373 tcp_plugin_address_pretty_printer (void *cls,
1374                                    const char *type,
1375                                    const void *addr,
1376                                    size_t addrlen,
1377                                    int numeric,
1378                                    struct GNUNET_TIME_Relative timeout,
1379                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1380                                    void *asc_cls)
1381 {
1382   struct Plugin *plugin = cls;
1383   struct PrettyPrinterContext *ppc;
1384   const void *sb;
1385   size_t sbs;
1386   struct sockaddr_in a4;
1387   struct sockaddr_in6 a6;
1388   const struct IPv4TcpAddress *t4;
1389   const struct IPv6TcpAddress *t6;
1390   uint16_t port;
1391
1392   if (addrlen == sizeof (struct IPv6TcpAddress))
1393     {
1394       t6 = addr;
1395       memset (&a6, 0, sizeof (a6));
1396       a6.sin6_family = AF_INET6;
1397       a6.sin6_port = t6->t6_port;
1398       memcpy (&a6.sin6_addr,
1399               &t6->ipv6_addr,
1400               sizeof (struct in6_addr));
1401       port = ntohs (t6->t6_port);
1402       sb = &a6;
1403       sbs = sizeof (a6);
1404     }
1405   else if (addrlen == sizeof (struct IPv4TcpAddress))
1406     {
1407       t4 = addr;
1408       memset (&a4, 0, sizeof (a4));
1409       a4.sin_family = AF_INET;
1410       a4.sin_port = t4->t_port;
1411       a4.sin_addr.s_addr = t4->ipv4_addr;
1412       port = ntohs (t4->t_port);
1413       sb = &a4;
1414       sbs = sizeof (a4);
1415     }
1416   else
1417     {
1418       /* invalid address */
1419       GNUNET_break_op (0);
1420       asc (asc_cls, NULL);
1421       return;
1422     }
1423   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1424   ppc->asc = asc;
1425   ppc->asc_cls = asc_cls;
1426   ppc->port = port;
1427   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1428                                 plugin->env->cfg,
1429                                 sb,
1430                                 sbs,
1431                                 !numeric, timeout, &append_port, ppc);
1432 }
1433
1434
1435 /**
1436  * Check if the given port is plausible (must be either
1437  * our listen port or our advertised port).  If it is
1438  * neither, we return GNUNET_SYSERR.
1439  *
1440  * @param plugin global variables
1441  * @param in_port port number to check
1442  * @return GNUNET_OK if port is either open_port or adv_port
1443  */
1444 static int
1445 check_port (struct Plugin *plugin, uint16_t in_port)
1446 {
1447   if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1448     return GNUNET_OK;
1449   if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1450        (plugin->behind_nat == GNUNET_YES) )
1451     {
1452       return GNUNET_SYSERR; /* odd case... */
1453     }
1454   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1455     return GNUNET_OK;
1456   return GNUNET_SYSERR;
1457 }
1458
1459
1460 /**
1461  * Function that will be called to check if a binary address for this
1462  * plugin is well-formed and corresponds to an address for THIS peer
1463  * (as per our configuration).  Naturally, if absolutely necessary,
1464  * plugins can be a bit conservative in their answer, but in general
1465  * plugins should make sure that the address does not redirect
1466  * traffic to a 3rd party that might try to man-in-the-middle our
1467  * traffic.
1468  *
1469  * @param cls closure, our 'struct Plugin*'
1470  * @param addr pointer to the address
1471  * @param addrlen length of addr
1472  * @return GNUNET_OK if this is a plausible address for this peer
1473  *         and transport, GNUNET_SYSERR if not
1474  */
1475 static int
1476 tcp_plugin_check_address (void *cls,
1477                           const void *addr,
1478                           size_t addrlen)
1479 {
1480   struct Plugin *plugin = cls;
1481   struct IPv4TcpAddress *v4;
1482   struct IPv6TcpAddress *v6;
1483
1484   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1485       (addrlen != sizeof (struct IPv6TcpAddress)))
1486     {
1487       GNUNET_break_op (0);
1488       return GNUNET_SYSERR;
1489     }
1490   if (addrlen == sizeof (struct IPv4TcpAddress))
1491     {
1492       v4 = (struct IPv4TcpAddress *) addr;
1493       if (GNUNET_OK !=
1494           check_port (plugin, ntohs (v4->t_port)))
1495         return GNUNET_SYSERR;
1496       if (GNUNET_OK !=
1497           check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1498         {
1499           return GNUNET_SYSERR;
1500         }
1501     }
1502   else
1503     {
1504       v6 = (struct IPv6TcpAddress *) addr;
1505       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1506         {
1507           GNUNET_break_op (0);
1508           return GNUNET_SYSERR;
1509         }
1510       if (GNUNET_OK !=
1511           check_port (plugin, ntohs (v6->t6_port)))
1512         return GNUNET_SYSERR;
1513       if (GNUNET_OK !=
1514           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1515         {
1516           return GNUNET_SYSERR;
1517         }
1518     }
1519   return GNUNET_OK;
1520 }
1521
1522 /**
1523  * We've received a nat probe from this peer via TCP.  Finish
1524  * creating the client session and resume sending of queued
1525  * messages.
1526  *
1527  * @param cls closure
1528  * @param client identification of the client
1529  * @param message the actual message
1530  */
1531 static void
1532 handle_tcp_nat_probe (void *cls,
1533                      struct GNUNET_SERVER_Client *client,
1534                      const struct GNUNET_MessageHeader *message)
1535 {
1536   struct Plugin *plugin = cls;
1537   struct Session *session;
1538   struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1539   size_t alen;
1540   void *vaddr;
1541   struct IPv4TcpAddress *t4;
1542   struct IPv6TcpAddress *t6;
1543   const struct sockaddr_in *s4;
1544   const struct sockaddr_in6 *s6;
1545
1546 #if DEBUG_TCP_NAT
1547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received tcp NAT probe\n");
1548 #endif
1549   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1550    * a connection to this peer by running gnunet-nat-client.  This peer
1551    * received the punch message and now wants us to use the new connection
1552    * as the default for that peer.  Do so and then send a WELCOME message
1553    * so we can really be connected!
1554    */
1555   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1556     {
1557 #if DEBUG_TCP_NAT
1558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bad size for tcp NAT probe, expected %d got %d.\n", sizeof(struct TCP_NAT_ProbeMessage), ntohs(message->size));
1559 #endif
1560       GNUNET_break_op(0);
1561       return;
1562     }
1563   tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1564
1565   if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1566     {
1567 #if DEBUG_TCP_NAT
1568       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1569 #endif
1570       session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1571       GNUNET_assert(session != NULL);
1572       GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1573       GNUNET_SERVER_client_keep (client);
1574       session->client = client;
1575       session->last_activity = GNUNET_TIME_absolute_get ();
1576       session->inbound = GNUNET_NO;
1577
1578       if (GNUNET_OK ==
1579           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1580         {
1581 #if DEBUG_TCP_NAT
1582           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583                            "Found address `%s' for incoming connection %p\n",
1584                            GNUNET_a2s (vaddr, alen),
1585                            client);
1586 #endif
1587           if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1588             {
1589               s4 = vaddr;
1590               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1591               t4->t_port = s4->sin_port;
1592               t4->ipv4_addr = s4->sin_addr.s_addr;
1593               session->connect_addr = t4;
1594               session->connect_alen = sizeof (struct IPv4TcpAddress);
1595             }
1596           else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1597             {
1598               s6 = vaddr;
1599               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1600               t6->t6_port = s6->sin6_port;
1601               memcpy (&t6->ipv6_addr,
1602                       &s6->sin6_addr,
1603                       sizeof (struct in6_addr));
1604               session->connect_addr = t6;
1605               session->connect_alen = sizeof (struct IPv6TcpAddress);
1606             }
1607           else
1608             {
1609 #if DEBUG_TCP_NAT
1610               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1611                           "Bad address for incoming connection!\n");
1612 #endif
1613             }
1614           GNUNET_free (vaddr);
1615         }
1616
1617       session->next = plugin->sessions;
1618       plugin->sessions = session;
1619       GNUNET_STATISTICS_update (plugin->env->stats,
1620                                 gettext_noop ("# TCP sessions active"),
1621                                 1,
1622                                 GNUNET_NO);
1623       process_pending_messages (session);
1624     }
1625   else
1626     {
1627 #if DEBUG_TCP_NAT
1628       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1629 #endif
1630     }
1631
1632   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1633 }
1634
1635 /**
1636  * We've received a welcome from this peer via TCP.  Possibly create a
1637  * fresh client record and send back our welcome.
1638  *
1639  * @param cls closure
1640  * @param client identification of the client
1641  * @param message the actual message
1642  */
1643 static void
1644 handle_tcp_welcome (void *cls,
1645                     struct GNUNET_SERVER_Client *client,
1646                     const struct GNUNET_MessageHeader *message)
1647 {
1648   struct Plugin *plugin = cls;
1649   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1650   struct Session *session;
1651   size_t alen;
1652   void *vaddr;
1653   struct IPv4TcpAddress *t4;
1654   struct IPv6TcpAddress *t6;
1655   const struct sockaddr_in *s4;
1656   const struct sockaddr_in6 *s6;
1657
1658 #if DEBUG_TCP
1659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1660                    "Received %s message from a `%4s/%p'.\n",
1661                    "WELCOME",
1662                    GNUNET_i2s (&wm->clientIdentity), client);
1663 #endif
1664   GNUNET_STATISTICS_update (plugin->env->stats,
1665                             gettext_noop ("# TCP WELCOME messages received"),
1666                             1,
1667                             GNUNET_NO);
1668   session = find_session_by_client (plugin, client);
1669   if (session == NULL)
1670     {
1671       GNUNET_SERVER_client_keep (client);
1672       session = create_session (plugin,
1673                                 &wm->clientIdentity, client, GNUNET_NO);
1674       session->inbound = GNUNET_YES;
1675       if (GNUNET_OK ==
1676           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1677         {
1678 #if DEBUG_TCP
1679           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1680                            "Found address `%s' for incoming connection %p\n",
1681                            GNUNET_a2s (vaddr, alen),
1682                            client);
1683 #endif
1684           if (alen == sizeof (struct sockaddr_in))
1685             {
1686               s4 = vaddr;
1687               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1688               t4->t_port = s4->sin_port;
1689               t4->ipv4_addr = s4->sin_addr.s_addr;
1690               session->connect_addr = t4;
1691               session->connect_alen = sizeof (struct IPv4TcpAddress);
1692             }
1693           else if (alen == sizeof (struct sockaddr_in6))
1694             {
1695               s6 = vaddr;
1696               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1697               t6->t6_port = s6->sin6_port;
1698               memcpy (&t6->ipv6_addr,
1699                       &s6->sin6_addr,
1700                       sizeof (struct in6_addr));
1701               session->connect_addr = t6;
1702               session->connect_alen = sizeof (struct IPv6TcpAddress);
1703             }
1704           GNUNET_free (vaddr);
1705         }
1706       else
1707         {
1708 #if DEBUG_TCP
1709           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710                            "Did not obtain TCP socket address for incoming connection\n");
1711 #endif
1712         }
1713 #if DEBUG_TCP
1714       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1715                        "Creating new session %p for connection %p\n",
1716                        session, client);
1717 #endif
1718       process_pending_messages (session);
1719     }
1720   if (session->expecting_welcome != GNUNET_YES)
1721     {
1722       GNUNET_break_op (0);
1723       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1724       return;
1725     }
1726   session->last_activity = GNUNET_TIME_absolute_get ();
1727   session->expecting_welcome = GNUNET_NO;
1728   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1729 }
1730
1731
1732 /**
1733  * Task to signal the server that we can continue
1734  * receiving from the TCP client now.
1735  *
1736  * @param cls the 'struct Session*'
1737  * @param tc task context (unused)
1738  */
1739 static void
1740 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1741 {
1742   struct Session *session = cls;
1743   struct GNUNET_TIME_Relative delay;
1744
1745   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1746   delay = session->plugin->env->receive (session->plugin->env->cls,
1747                                          &session->target,
1748                                          NULL, 0,
1749                                          session,
1750                                          NULL, 0);
1751   if (delay.value == 0)
1752     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1753   else
1754     session->receive_delay_task =
1755       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1756                                     delay, &delayed_done, session);
1757 }
1758
1759
1760 /**
1761  * We've received data for this peer via TCP.  Unbox,
1762  * compute latency and forward.
1763  *
1764  * @param cls closure
1765  * @param client identification of the client
1766  * @param message the actual message
1767  */
1768 static void
1769 handle_tcp_data (void *cls,
1770                  struct GNUNET_SERVER_Client *client,
1771                  const struct GNUNET_MessageHeader *message)
1772 {
1773   struct Plugin *plugin = cls;
1774   struct Session *session;
1775   struct GNUNET_TIME_Relative delay;
1776
1777   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1778     {
1779       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1780       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1781       return;
1782     }
1783   session = find_session_by_client (plugin, client);
1784   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1785     {
1786       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1787       return;
1788     }
1789   session->last_activity = GNUNET_TIME_absolute_get ();
1790 #if DEBUG_TCP
1791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1792                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1793                    (unsigned int) ntohs (message->size),
1794                    (unsigned int) ntohs (message->type),
1795                    GNUNET_i2s (&session->target));
1796 #endif
1797   GNUNET_STATISTICS_update (plugin->env->stats,
1798                             gettext_noop ("# bytes received via TCP"),
1799                             ntohs (message->size),
1800                             GNUNET_NO);
1801   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1802                                 session,
1803                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1804                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1805   if (delay.value == 0)
1806     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1807   else
1808     session->receive_delay_task =
1809       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1810                                     delay, &delayed_done, session);
1811 }
1812
1813
1814 /**
1815  * Functions with this signature are called whenever a peer
1816  * is disconnected on the network level.
1817  *
1818  * @param cls closure
1819  * @param client identification of the client
1820  */
1821 static void
1822 disconnect_notify (void *cls,
1823                    struct GNUNET_SERVER_Client *client)
1824 {
1825   struct Plugin *plugin = cls;
1826   struct Session *session;
1827
1828   if (client == NULL)
1829     return;
1830   session = find_session_by_client (plugin, client);
1831   if (session == NULL)
1832     return;                     /* unknown, nothing to do */
1833 #if DEBUG_TCP
1834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1836                    GNUNET_i2s (&session->target),
1837                    (session->connect_addr != NULL) ?
1838                    tcp_address_to_string (session->plugin,
1839                                           session->connect_addr,
1840                                           session->connect_alen) : "*",
1841                    client);
1842 #endif
1843   disconnect_session (session);
1844 }
1845
1846
1847 /**
1848  * Add the IP of our network interface to the list of
1849  * our external IP addresses.
1850  *
1851  * @param cls the 'struct Plugin*'
1852  * @param name name of the interface
1853  * @param isDefault do we think this may be our default interface
1854  * @param addr address of the interface
1855  * @param addrlen number of bytes in addr
1856  * @return GNUNET_OK to continue iterating
1857  */
1858 static int
1859 process_interfaces (void *cls,
1860                     const char *name,
1861                     int isDefault,
1862                     const struct sockaddr *addr, socklen_t addrlen)
1863 {
1864   struct Plugin *plugin = cls;
1865   int af;
1866   struct IPv4TcpAddress t4;
1867   struct IPv6TcpAddress t6;
1868   struct IPv4TcpAddress t4_nat;
1869   struct IPv6TcpAddress t6_nat;
1870   void *arg;
1871   uint16_t args;
1872   void *arg_nat;
1873   char buf[INET_ADDRSTRLEN];
1874
1875   af = addr->sa_family;
1876   arg_nat = NULL;
1877   if (af == AF_INET)
1878     {
1879       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1880       GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1881       if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1882         {
1883           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1884           return GNUNET_OK;
1885         }
1886       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1887       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1888         t4.t_port = htons(0);
1889       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1890         {
1891           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1892           t4_nat.t_port = htons(plugin->adv_port);
1893           arg_nat = &t4_nat;
1894         }
1895       else
1896         t4.t_port = htons (plugin->adv_port);
1897       arg = &t4;
1898       args = sizeof (t4);
1899     }
1900   else if (af == AF_INET6)
1901     {
1902       if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1903         {
1904           /* skip link local addresses */
1905           return GNUNET_OK;
1906         }
1907       memcpy (&t6.ipv6_addr,
1908               &((struct sockaddr_in6 *) addr)->sin6_addr,
1909               sizeof (struct in6_addr));
1910       add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1911       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1912         t6.t6_port = htons(0);
1913       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1914         {
1915           memcpy (&t6_nat.ipv6_addr,
1916                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1917                   sizeof (struct in6_addr));
1918           t6_nat.t6_port = htons(plugin->adv_port);
1919           arg_nat = &t6;
1920         }
1921       else
1922         t6.t6_port = htons (plugin->adv_port);
1923       arg = &t6;
1924       args = sizeof (t6);
1925     }
1926   else
1927     {
1928       GNUNET_break (0);
1929       return GNUNET_OK;
1930     }
1931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1932                    _("Found address `%s' (%s) len %d\n"),
1933                    GNUNET_a2s (addr, addrlen), name, args);
1934
1935   plugin->env->notify_address (plugin->env->cls,
1936                                "tcp",
1937                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1938
1939   if (arg_nat != NULL)
1940     {
1941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942                       _("Found address `%s' (%s) len %d\n"),
1943                       GNUNET_a2s (addr, addrlen), name, args);
1944       plugin->env->notify_address (plugin->env->cls,
1945                                    "tcp",
1946                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1947     }
1948
1949   return GNUNET_OK;
1950 }
1951
1952
1953 /**
1954  * Function called by the resolver for each address obtained from DNS
1955  * for our own hostname.  Add the addresses to the list of our
1956  * external IP addresses.
1957  *
1958  * @param cls closure
1959  * @param addr one of the addresses of the host, NULL for the last address
1960  * @param addrlen length of the address
1961  */
1962 static void
1963 process_hostname_ips (void *cls,
1964                       const struct sockaddr *addr, socklen_t addrlen)
1965 {
1966   struct Plugin *plugin = cls;
1967
1968   if (addr == NULL)
1969     {
1970       plugin->hostname_dns = NULL;
1971       return;
1972     }
1973   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1974   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1975 }
1976
1977 /**
1978  * We can now send a probe message, copy into buffer to really send.
1979  *
1980  * @param cls closure, a struct TCPProbeContext
1981  * @param size max size to copy
1982  * @param buf buffer to copy message to
1983  */
1984 static size_t notify_send_probe (void *cls,
1985                                  size_t size, void *buf)
1986 {
1987   struct TCPProbeContext *tcp_probe_ctx = cls;
1988
1989   if (buf == NULL)
1990     {
1991       return 0;
1992     }
1993
1994   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
1995   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
1996   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
1997                                 tcp_probe_ctx->sock);
1998
1999   GNUNET_free(tcp_probe_ctx);
2000   return sizeof(tcp_probe_ctx->message);
2001 }
2002
2003 /*
2004  * @param cls the plugin handle
2005  * @param tc the scheduling context (for rescheduling this function again)
2006  *
2007  * We have been notified that gnunet-nat-server has written something to stdout.
2008  * Handle the output, then reschedule this function to be called again once
2009  * more is available.
2010  *
2011  */
2012 static void
2013 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2014 {
2015   struct Plugin *plugin = cls;
2016   char mybuf[40];
2017   ssize_t bytes;
2018   memset(&mybuf, 0, sizeof(mybuf));
2019   int i;
2020   int port;
2021   char *port_start;
2022   struct sockaddr_in in_addr;
2023   struct TCPProbeContext *tcp_probe_ctx;
2024   struct GNUNET_CONNECTION_Handle *sock;
2025
2026   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2027     return;
2028
2029   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2030
2031   if (bytes < 1)
2032     {
2033 #if DEBUG_TCP_NAT
2034       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2035                       _("Finished reading from server stdout with code: %d\n"), bytes);
2036 #endif
2037       return;
2038     }
2039
2040   port_start = NULL;
2041   for (i = 0; i < sizeof(mybuf); i++)
2042     {
2043       if (mybuf[i] == '\n')
2044         mybuf[i] = '\0';
2045
2046       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2047         {
2048           mybuf[i] = '\0';
2049           port_start = &mybuf[i + 1];
2050         }
2051     }
2052
2053   if (port_start != NULL)
2054     port = atoi(port_start);
2055   else
2056     {
2057       plugin->server_read_task =
2058            GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2059                                            GNUNET_TIME_UNIT_FOREVER_REL,
2060                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2061       return;
2062     }
2063
2064 #if DEBUG_TCP_NAT
2065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
2067 #endif
2068
2069
2070   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2071     {
2072
2073       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2074                   _("nat-server-read malformed address\n"), &mybuf, port);
2075
2076       plugin->server_read_task =
2077           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2078                                           GNUNET_TIME_UNIT_FOREVER_REL,
2079                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2080       return;
2081     }
2082
2083   in_addr.sin_family = AF_INET;
2084   in_addr.sin_port = htons(port);
2085   /**
2086    * We have received an ICMP response, ostensibly from a non-NAT'd peer
2087    *  that wants to connect to us! Send a message to establish a connection.
2088    */
2089   sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2090                                                  sizeof(in_addr));
2091
2092
2093   if (sock == NULL)
2094     {
2095       plugin->server_read_task =
2096           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2097                                           GNUNET_TIME_UNIT_FOREVER_REL,
2098                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2099       return;
2100     }
2101   else
2102     {
2103       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104                 _("Sending TCP probe message!\n"), &mybuf, port);
2105
2106       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2107       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2108       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2109       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2110       tcp_probe_ctx->plugin = plugin;
2111       tcp_probe_ctx->sock = sock;
2112       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2113                                                                  ntohs(tcp_probe_ctx->message.header.size),
2114                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2115                                                                  &notify_send_probe, tcp_probe_ctx);
2116
2117     }
2118
2119   /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2120   plugin->server_read_task =
2121       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2122                                       GNUNET_TIME_UNIT_FOREVER_REL,
2123                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2124 }
2125
2126 /**
2127  * Start the gnunet-nat-server process for users behind NAT.
2128  *
2129  * @param plugin the transport plugin
2130  *
2131  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2132  */
2133 static int
2134 tcp_transport_start_nat_server(struct Plugin *plugin)
2135 {
2136
2137   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2138   if (plugin->server_stdout == NULL)
2139     return GNUNET_SYSERR;
2140
2141 #if DEBUG_TCP_NAT
2142   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2144 #endif
2145   /* Start the server process */
2146   plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2147   if (plugin->server_pid == GNUNET_SYSERR)
2148     {
2149 #if DEBUG_TCP_NAT
2150     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151                      "Failed to start gnunet-nat-server process\n");
2152 #endif
2153       return GNUNET_SYSERR;
2154     }
2155   /* Close the write end of the read pipe */
2156   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2157
2158   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2159   plugin->server_read_task =
2160       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2161                                       GNUNET_TIME_UNIT_FOREVER_REL,
2162                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2163   return GNUNET_YES;
2164 }
2165
2166 /**
2167  * Return the actual path to a file found in the current
2168  * PATH environment variable.
2169  *
2170  * @param binary the name of the file to find
2171  */
2172 static char *
2173 get_path_from_PATH (char *binary)
2174 {
2175   char *path;
2176   char *pos;
2177   char *end;
2178   char *buf;
2179   const char *p;
2180
2181   p = getenv ("PATH");
2182   if (p == NULL)
2183     return NULL;
2184   path = GNUNET_strdup (p);     /* because we write on it */
2185   buf = GNUNET_malloc (strlen (path) + 20);
2186   pos = path;
2187
2188   while (NULL != (end = strchr (pos, ':')))
2189     {
2190       *end = '\0';
2191       sprintf (buf, "%s/%s", pos, binary);
2192       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2193         {
2194           GNUNET_free (path);
2195           return buf;
2196         }
2197       pos = end + 1;
2198     }
2199   sprintf (buf, "%s/%s", pos, binary);
2200   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2201     {
2202       GNUNET_free (path);
2203       return buf;
2204     }
2205   GNUNET_free (buf);
2206   GNUNET_free (path);
2207   return NULL;
2208 }
2209
2210 /**
2211  * Check whether the suid bit is set on a file.
2212  * Attempts to find the file using the current
2213  * PATH environment variable as a search path.
2214  *
2215  * @param binary the name of the file to check
2216  */
2217 static int
2218 check_gnunet_nat_binary(char *binary)
2219 {
2220   struct stat statbuf;
2221   char *p;
2222
2223   p = get_path_from_PATH (binary);
2224   if (p == NULL)
2225     return GNUNET_NO;
2226   if (0 != STAT (p, &statbuf))
2227     {
2228       GNUNET_free (p);
2229       return GNUNET_SYSERR;
2230     }
2231   GNUNET_free (p);
2232   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2233        (statbuf.st_uid == 0) )
2234     return GNUNET_YES;
2235   return GNUNET_NO;
2236 }
2237
2238 /**
2239  * Entry point for the plugin.
2240  *
2241  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2242  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2243  */
2244 void *
2245 libgnunet_plugin_transport_tcp_init (void *cls)
2246 {
2247   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2248     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2249      sizeof (struct WelcomeMessage)},
2250     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2251     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2252     {NULL, NULL, 0, 0}
2253   };
2254   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2255   struct GNUNET_TRANSPORT_PluginFunctions *api;
2256   struct Plugin *plugin;
2257   struct GNUNET_SERVICE_Context *service;
2258   unsigned long long aport;
2259   unsigned long long bport;
2260   unsigned int i;
2261   int behind_nat;
2262   int allow_nat;
2263   int only_nat_addresses;
2264   char *internal_address;
2265   char *external_address;
2266   struct sockaddr_in in_addr;
2267   struct IPv4TcpAddress t4;
2268
2269   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2270   if (service == NULL)
2271     {
2272       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2273                  _("Failed to start service for `%s' transport plugin.\n"),
2274                  "tcp");
2275       return NULL;
2276     }
2277
2278   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2279                                                            "transport-tcp",
2280                                                            "BEHIND_NAT"))
2281     {
2282       /* We are behind nat (according to the user) */
2283       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2284         {
2285           behind_nat = GNUNET_YES;
2286         }
2287       else
2288         {
2289           behind_nat = GNUNET_NO;
2290           GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you are behind a NAT, but gnunet-nat-server is not installed properly (suid bit not set)!\n");
2291         }
2292     }
2293   else
2294     behind_nat = GNUNET_NO; /* We are not behind nat! */
2295
2296   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2297                                                            "transport-tcp",
2298                                                            "ALLOW_NAT"))
2299     {
2300       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2301         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2302       else
2303       {
2304         allow_nat = GNUNET_NO;
2305         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Configuration specified you want to connect to NAT'd peers, but gnunet-nat-client is not installed properly (suid bit not set)!\n");
2306       }
2307     }
2308   else
2309     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2310
2311
2312   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2313                                                            "transport-tcp",
2314                                                            "ONLY_NAT_ADDRESSES"))
2315     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2316   else
2317     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2318
2319   external_address = NULL;
2320   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2321          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2322                                                 "transport-tcp",
2323                                                 "EXTERNAL_ADDRESS",
2324                                                 &external_address)))
2325     {
2326       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2327                        _
2328                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2329                        "transport-tcp");
2330       GNUNET_SERVICE_stop (service);
2331       return NULL;
2332     }
2333
2334   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2335     {
2336       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2337     }
2338
2339   internal_address = NULL;
2340   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2341          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2342                                                 "transport-tcp",
2343                                                 "INTERNAL_ADDRESS",
2344                                                 &internal_address)))
2345     {
2346       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2347                  _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2348                  "transport-tcp");
2349       GNUNET_SERVICE_stop (service);
2350       GNUNET_free_non_null(external_address);
2351       return NULL;
2352     }
2353
2354   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2355     {
2356       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2357     }
2358
2359   aport = 0;
2360   if ((GNUNET_OK !=
2361        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2362                                               "transport-tcp",
2363                                               "PORT",
2364                                               &bport)) ||
2365       (bport > 65535) ||
2366       ((GNUNET_OK ==
2367         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2368                                                "transport-tcp",
2369                                                "ADVERTISED-PORT",
2370                                                &aport)) && (aport > 65535)))
2371     {
2372       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2373                        _
2374                        ("Require valid port number for service `%s' in configuration!\n"),
2375                        "transport-tcp");
2376       GNUNET_free_non_null(external_address);
2377       GNUNET_free_non_null(internal_address);
2378       GNUNET_SERVICE_stop (service);
2379       return NULL;
2380     }
2381
2382   if (aport == 0)
2383     aport = bport;
2384   plugin = GNUNET_malloc (sizeof (struct Plugin));
2385   plugin->open_port = bport;
2386   plugin->adv_port = aport;
2387   plugin->external_address = external_address;
2388   plugin->internal_address = internal_address;
2389   plugin->behind_nat = behind_nat;
2390   plugin->allow_nat = allow_nat;
2391   plugin->only_nat_addresses = only_nat_addresses;
2392   plugin->env = env;
2393   plugin->lsock = NULL;
2394   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2395   api->cls = plugin;
2396   api->send = &tcp_plugin_send;
2397   api->disconnect = &tcp_plugin_disconnect;
2398   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2399   api->check_address = &tcp_plugin_check_address;
2400   api->address_to_string = &tcp_address_to_string;
2401   plugin->service = service;
2402   plugin->server = GNUNET_SERVICE_get_server (service);
2403   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2404   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2405   for (i = 0;
2406        i <
2407        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2408        i++)
2409     plugin->handlers[i].callback_cls = plugin;
2410   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2411
2412   if (plugin->behind_nat == GNUNET_YES)
2413     {
2414       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2415         {
2416           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2417
2418                            _
2419                            ("Failed to start %s required for NAT in %s!\n"),
2420                            "gnunet-nat-server"
2421                            "transport-tcp");
2422           GNUNET_free_non_null(external_address);
2423           GNUNET_free_non_null(internal_address);
2424           GNUNET_SERVICE_stop (service);
2425           GNUNET_free (api);
2426           return NULL;
2427         }
2428     }
2429
2430   if (allow_nat == GNUNET_YES)
2431     {
2432       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2433       GNUNET_assert(plugin->nat_wait_conns != NULL);
2434     }
2435
2436   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2437   if (aport != bport)
2438     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2439                      _("TCP transport advertises itself as being on port %llu\n"),
2440                      aport);
2441   GNUNET_SERVER_disconnect_notify (plugin->server,
2442                                    &disconnect_notify,
2443                                    plugin);
2444   GNUNET_CONFIGURATION_get_value_string(env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address);
2445
2446   if (plugin->behind_nat == GNUNET_NO)
2447     {
2448       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2449     }
2450
2451   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2452                                                            env->cfg,
2453                                                            AF_UNSPEC,
2454                                                            HOSTNAME_RESOLVE_TIMEOUT,
2455                                                            &process_hostname_ips,
2456                                                            plugin);
2457
2458   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2459     {
2460       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2461       t4.t_port = htons(0);
2462       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2463       plugin->env->notify_address (plugin->env->cls,
2464                                   "tcp",
2465                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2466     }
2467   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2468     {
2469       t4.t_port = htons(plugin->adv_port);
2470       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:%d\n", plugin->external_address, plugin->adv_port);
2471       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2472       plugin->env->notify_address (plugin->env->cls,
2473                                    "tcp",
2474                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2475     }
2476
2477   return api;
2478 }
2479
2480
2481 /**
2482  * Exit point from the plugin.
2483  */
2484 void *
2485 libgnunet_plugin_transport_tcp_done (void *cls)
2486 {
2487   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2488   struct Plugin *plugin = api->cls;
2489   struct Session *session;
2490   struct LocalAddrList *lal;
2491
2492   while (NULL != (session = plugin->sessions))
2493     disconnect_session (session);
2494   if (NULL != plugin->hostname_dns)
2495     {
2496       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2497       plugin->hostname_dns = NULL;
2498     }
2499   GNUNET_SERVICE_stop (plugin->service);
2500   GNUNET_free (plugin->handlers);
2501   while (NULL != (lal = plugin->lal_head))
2502     {
2503       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2504                                    plugin->lal_tail,
2505                                    lal);
2506       GNUNET_free (lal);
2507     }
2508
2509   if (plugin->behind_nat == GNUNET_YES)
2510     {
2511       if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2512         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2513       GNUNET_OS_process_wait (plugin->server_pid);
2514     }
2515   GNUNET_free_non_null(plugin->bind_address);
2516   GNUNET_free (plugin);
2517   GNUNET_free (api);
2518   return NULL;
2519 }
2520
2521 /* end of plugin_transport_tcp.c */