f38c08c654399a497e1a263b858d9fc5185c411d
[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       /* FIXME: Should this be inbound or outbound?
1577        * I think it should be outbound because we technically
1578        * initiated it... But something goes wrong somewhere. */
1579       /* session->inbound = GNUNET_YES; */
1580       session->inbound = GNUNET_YES;
1581
1582       if (GNUNET_OK ==
1583           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1584         {
1585 #if DEBUG_TCP_NAT
1586           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1587                            "Found address `%s' for incoming connection %p\n",
1588                            GNUNET_a2s (vaddr, alen),
1589                            client);
1590 #endif
1591           if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1592             {
1593               s4 = vaddr;
1594               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1595               t4->t_port = s4->sin_port;
1596               t4->ipv4_addr = s4->sin_addr.s_addr;
1597               session->connect_addr = t4;
1598               session->connect_alen = sizeof (struct IPv4TcpAddress);
1599             }
1600           else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1601             {
1602               s6 = vaddr;
1603               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1604               t6->t6_port = s6->sin6_port;
1605               memcpy (&t6->ipv6_addr,
1606                       &s6->sin6_addr,
1607                       sizeof (struct in6_addr));
1608               session->connect_addr = t6;
1609               session->connect_alen = sizeof (struct IPv6TcpAddress);
1610             }
1611           else
1612             {
1613 #if DEBUG_TCP_NAT
1614               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1615                           "Bad address for incoming connection!\n");
1616 #endif
1617             }
1618           GNUNET_free (vaddr);
1619         }
1620
1621       session->next = plugin->sessions;
1622       plugin->sessions = session;
1623       GNUNET_STATISTICS_update (plugin->env->stats,
1624                                 gettext_noop ("# TCP sessions active"),
1625                                 1,
1626                                 GNUNET_NO);
1627       process_pending_messages (session);
1628     }
1629   else
1630     {
1631 #if DEBUG_TCP_NAT
1632       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1633 #endif
1634     }
1635
1636   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1637 }
1638
1639 /**
1640  * We've received a welcome from this peer via TCP.  Possibly create a
1641  * fresh client record and send back our welcome.
1642  *
1643  * @param cls closure
1644  * @param client identification of the client
1645  * @param message the actual message
1646  */
1647 static void
1648 handle_tcp_welcome (void *cls,
1649                     struct GNUNET_SERVER_Client *client,
1650                     const struct GNUNET_MessageHeader *message)
1651 {
1652   struct Plugin *plugin = cls;
1653   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1654   struct Session *session;
1655   size_t alen;
1656   void *vaddr;
1657   struct IPv4TcpAddress *t4;
1658   struct IPv6TcpAddress *t6;
1659   const struct sockaddr_in *s4;
1660   const struct sockaddr_in6 *s6;
1661
1662 #if DEBUG_TCP
1663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1664                    "Received %s message from a `%4s/%p'.\n", 
1665                    "WELCOME",
1666                    GNUNET_i2s (&wm->clientIdentity), client);
1667 #endif
1668   GNUNET_STATISTICS_update (plugin->env->stats,
1669                             gettext_noop ("# TCP WELCOME messages received"),
1670                             1,
1671                             GNUNET_NO);      
1672   session = find_session_by_client (plugin, client);
1673   if (session == NULL)
1674     {
1675       GNUNET_SERVER_client_keep (client);
1676       session = create_session (plugin,
1677                                 &wm->clientIdentity, client, GNUNET_NO);
1678       session->inbound = GNUNET_YES;
1679       if (GNUNET_OK ==
1680           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1681         {
1682 #if DEBUG_TCP
1683           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684                            "Found address `%s' for incoming connection %p\n",
1685                            GNUNET_a2s (vaddr, alen),
1686                            client);
1687 #endif
1688           if (alen == sizeof (struct sockaddr_in))
1689             {
1690               s4 = vaddr;
1691               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1692               t4->t_port = s4->sin_port;
1693               t4->ipv4_addr = s4->sin_addr.s_addr;
1694               session->connect_addr = t4;
1695               session->connect_alen = sizeof (struct IPv4TcpAddress);
1696             }
1697           else if (alen == sizeof (struct sockaddr_in6))
1698             {
1699               s6 = vaddr;
1700               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1701               t6->t6_port = s6->sin6_port;
1702               memcpy (&t6->ipv6_addr,
1703                       &s6->sin6_addr,
1704                       sizeof (struct in6_addr));
1705               session->connect_addr = t6;
1706               session->connect_alen = sizeof (struct IPv6TcpAddress);
1707             }
1708           GNUNET_free (vaddr);
1709         }
1710       else
1711         {
1712 #if DEBUG_TCP
1713           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714                            "Did not obtain TCP socket address for incoming connection\n");
1715 #endif
1716         }
1717 #if DEBUG_TCP
1718       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719                        "Creating new session %p for connection %p\n",
1720                        session, client);
1721 #endif
1722       process_pending_messages (session);
1723     }
1724   if (session->expecting_welcome != GNUNET_YES)
1725     {
1726       GNUNET_break_op (0);
1727       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1728       return;
1729     }
1730   session->last_activity = GNUNET_TIME_absolute_get ();
1731   session->expecting_welcome = GNUNET_NO;
1732   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1733 }
1734
1735
1736 /**
1737  * Task to signal the server that we can continue
1738  * receiving from the TCP client now.
1739  *
1740  * @param cls the 'struct Session*'
1741  * @param tc task context (unused)
1742  */
1743 static void
1744 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1745 {
1746   struct Session *session = cls;
1747   struct GNUNET_TIME_Relative delay;
1748
1749   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1750   delay = session->plugin->env->receive (session->plugin->env->cls,
1751                                          &session->target,
1752                                          NULL, 0, 
1753                                          session,
1754                                          NULL, 0);
1755   if (delay.value == 0)
1756     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1757   else
1758     session->receive_delay_task = 
1759       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1760                                     delay, &delayed_done, session);
1761 }
1762
1763
1764 /**
1765  * We've received data for this peer via TCP.  Unbox,
1766  * compute latency and forward.
1767  *
1768  * @param cls closure
1769  * @param client identification of the client
1770  * @param message the actual message
1771  */
1772 static void
1773 handle_tcp_data (void *cls,
1774                  struct GNUNET_SERVER_Client *client,
1775                  const struct GNUNET_MessageHeader *message)
1776 {
1777   struct Plugin *plugin = cls;
1778   struct Session *session;
1779   struct GNUNET_TIME_Relative delay;
1780
1781   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1782     {
1783       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1784       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1785       return; 
1786     }    
1787   session = find_session_by_client (plugin, client);
1788   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1789     {
1790       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1791       return;
1792     }
1793   session->last_activity = GNUNET_TIME_absolute_get ();
1794 #if DEBUG_TCP
1795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1796                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1797                    (unsigned int) ntohs (message->size), 
1798                    (unsigned int) ntohs (message->type),
1799                    GNUNET_i2s (&session->target));
1800 #endif
1801   GNUNET_STATISTICS_update (plugin->env->stats,
1802                             gettext_noop ("# bytes received via TCP"),
1803                             ntohs (message->size),
1804                             GNUNET_NO); 
1805   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1806                                 session, 
1807                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1808                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1809   if (delay.value == 0)
1810     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1811   else
1812     session->receive_delay_task = 
1813       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1814                                     delay, &delayed_done, session);
1815 }
1816
1817
1818 /**
1819  * Functions with this signature are called whenever a peer
1820  * is disconnected on the network level.
1821  *
1822  * @param cls closure
1823  * @param client identification of the client
1824  */
1825 static void
1826 disconnect_notify (void *cls, 
1827                    struct GNUNET_SERVER_Client *client)
1828 {
1829   struct Plugin *plugin = cls;
1830   struct Session *session;
1831
1832   if (client == NULL)
1833     return;
1834   session = find_session_by_client (plugin, client);
1835   if (session == NULL)
1836     return;                     /* unknown, nothing to do */
1837 #if DEBUG_TCP
1838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1840                    GNUNET_i2s (&session->target),
1841                    (session->connect_addr != NULL) ?
1842                    tcp_address_to_string (session->plugin,
1843                                           session->connect_addr,
1844                                           session->connect_alen) : "*",
1845                    client);
1846 #endif
1847   disconnect_session (session);
1848 }
1849
1850
1851 /**
1852  * Add the IP of our network interface to the list of
1853  * our external IP addresses.
1854  *
1855  * @param cls the 'struct Plugin*'
1856  * @param name name of the interface
1857  * @param isDefault do we think this may be our default interface
1858  * @param addr address of the interface
1859  * @param addrlen number of bytes in addr
1860  * @return GNUNET_OK to continue iterating
1861  */
1862 static int
1863 process_interfaces (void *cls,
1864                     const char *name,
1865                     int isDefault,
1866                     const struct sockaddr *addr, socklen_t addrlen)
1867 {
1868   struct Plugin *plugin = cls;
1869   int af;
1870   struct IPv4TcpAddress t4;
1871   struct IPv6TcpAddress t6;
1872   struct IPv4TcpAddress t4_nat;
1873   struct IPv6TcpAddress t6_nat;
1874   void *arg;
1875   uint16_t args;
1876   void *arg_nat;
1877   char buf[INET_ADDRSTRLEN];
1878
1879   af = addr->sa_family;
1880   arg_nat = NULL;
1881   if (af == AF_INET)
1882     {
1883       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1884       GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1885       if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1886         {
1887           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1888           return GNUNET_OK;
1889         }
1890       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1891       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1892         t4.t_port = htons(0);
1893       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1894         {
1895           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1896           t4_nat.t_port = htons(plugin->adv_port);
1897           arg_nat = &t4_nat;
1898         }
1899       else
1900         t4.t_port = htons (plugin->adv_port);
1901       arg = &t4;
1902       args = sizeof (t4);
1903     }
1904   else if (af == AF_INET6)
1905     {
1906       if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1907         {
1908           /* skip link local addresses */
1909           return GNUNET_OK;
1910         }
1911       memcpy (&t6.ipv6_addr,
1912               &((struct sockaddr_in6 *) addr)->sin6_addr,
1913               sizeof (struct in6_addr));
1914       add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1915       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1916         t6.t6_port = htons(0);
1917       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1918         {
1919           memcpy (&t6_nat.ipv6_addr,
1920                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1921                   sizeof (struct in6_addr));
1922           t6_nat.t6_port = htons(plugin->adv_port);
1923           arg_nat = &t6;
1924         }
1925       else
1926         t6.t6_port = htons (plugin->adv_port);
1927       arg = &t6;
1928       args = sizeof (t6);
1929     }
1930   else
1931     {
1932       GNUNET_break (0);
1933       return GNUNET_OK;
1934     }
1935   GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1936                    GNUNET_ERROR_TYPE_BULK,
1937                    _("Found address `%s' (%s)\n"),
1938                    GNUNET_a2s (addr, addrlen), name);
1939
1940   plugin->env->notify_address (plugin->env->cls,
1941                                "tcp",
1942                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1943
1944   if (arg_nat != NULL)
1945     {
1946       GNUNET_log (GNUNET_ERROR_TYPE_INFO |
1947                        GNUNET_ERROR_TYPE_BULK,
1948                       _("Found address `%s' (%s)\n"),
1949                       GNUNET_a2s (addr, addrlen), name);
1950       plugin->env->notify_address (plugin->env->cls,
1951                                    "tcp",
1952                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
1953     }
1954
1955   return GNUNET_OK;
1956 }
1957
1958
1959 /**
1960  * Function called by the resolver for each address obtained from DNS
1961  * for our own hostname.  Add the addresses to the list of our
1962  * external IP addresses.
1963  *
1964  * @param cls closure
1965  * @param addr one of the addresses of the host, NULL for the last address
1966  * @param addrlen length of the address
1967  */
1968 static void
1969 process_hostname_ips (void *cls,
1970                       const struct sockaddr *addr, socklen_t addrlen)
1971 {
1972   struct Plugin *plugin = cls;
1973
1974   if (addr == NULL)
1975     {
1976       plugin->hostname_dns = NULL;
1977       return;
1978     }
1979   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
1980   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1981 }
1982
1983 /**
1984  * We can now send a probe message, copy into buffer to really send.
1985  *
1986  * @param cls closure, a struct TCPProbeContext
1987  * @param size max size to copy
1988  * @param buf buffer to copy message to
1989  */
1990 static size_t notify_send_probe (void *cls,
1991                                  size_t size, void *buf)
1992 {
1993   struct TCPProbeContext *tcp_probe_ctx = cls;
1994
1995   if (buf == NULL)
1996     {
1997       return 0;
1998     }
1999
2000   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2001   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2002   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2003                                 tcp_probe_ctx->sock);
2004
2005   GNUNET_free(tcp_probe_ctx);
2006   return sizeof(tcp_probe_ctx->message);
2007 }
2008
2009 /*
2010  * @param cls the plugin handle
2011  * @param tc the scheduling context (for rescheduling this function again)
2012  *
2013  * We have been notified that gnunet-nat-server has written something to stdout.
2014  * Handle the output, then reschedule this function to be called again once
2015  * more is available.
2016  *
2017  */
2018 static void
2019 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2020 {
2021   struct Plugin *plugin = cls;
2022   char mybuf[40];
2023   ssize_t bytes;
2024   memset(&mybuf, 0, sizeof(mybuf));
2025   int i;
2026   int port;
2027   char *port_start;
2028   struct sockaddr_in in_addr;
2029   struct TCPProbeContext *tcp_probe_ctx;
2030   struct GNUNET_CONNECTION_Handle *sock;
2031
2032   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2033     return;
2034
2035   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2036
2037   if (bytes < 1)
2038     {
2039 #if DEBUG_TCP_NAT
2040       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2041                       _("Finished reading from server stdout with code: %d\n"), bytes);
2042 #endif
2043       return;
2044     }
2045
2046   port = 0;
2047   port_start = NULL;
2048   for (i = 0; i < sizeof(mybuf); i++)
2049     {
2050       if (mybuf[i] == '\n')
2051         mybuf[i] = '\0';
2052
2053       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2054         {
2055           mybuf[i] = '\0';
2056           port_start = &mybuf[i + 1];
2057         }
2058     }
2059
2060   if (port_start != NULL)
2061     port = atoi(port_start);
2062   else
2063     {
2064       plugin->server_read_task =
2065            GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2066                                            GNUNET_TIME_UNIT_FOREVER_REL,
2067                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2068       return;
2069     }
2070
2071 #if DEBUG_TCP_NAT
2072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2073                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
2074 #endif
2075
2076
2077   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2078     {
2079
2080       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2081                   _("nat-server-read malformed address\n"), &mybuf, port);
2082
2083       plugin->server_read_task =
2084           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2085                                           GNUNET_TIME_UNIT_FOREVER_REL,
2086                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2087       return;
2088     }
2089
2090   in_addr.sin_family = AF_INET;
2091   in_addr.sin_port = htons(port);
2092   /**
2093    * We have received an ICMP response, ostensibly from a non-NAT'd peer
2094    *  that wants to connect to us! Send a message to establish a connection.
2095    */
2096   sock = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched, AF_INET, (struct sockaddr *)&in_addr,
2097                                                  sizeof(in_addr));
2098
2099
2100   if (sock == NULL)
2101     {
2102       plugin->server_read_task =
2103           GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2104                                           GNUNET_TIME_UNIT_FOREVER_REL,
2105                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2106       return;
2107     }
2108   else
2109     {
2110       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111                 _("Sending TCP probe message!\n"), &mybuf, port);
2112
2113       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2114       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2115       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2116       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2117       tcp_probe_ctx->plugin = plugin;
2118       tcp_probe_ctx->sock = sock;
2119       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2120                                                                  ntohs(tcp_probe_ctx->message.header.size),
2121                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2122                                                                  &notify_send_probe, tcp_probe_ctx);
2123
2124     }
2125
2126   /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2127   plugin->server_read_task =
2128       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2129                                       GNUNET_TIME_UNIT_FOREVER_REL,
2130                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2131 }
2132
2133 /**
2134  * Start the gnunet-nat-server process for users behind NAT.
2135  *
2136  * @param plugin the transport plugin
2137  *
2138  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2139  */
2140 static int
2141 tcp_transport_start_nat_server(struct Plugin *plugin)
2142 {
2143
2144   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES);
2145   if (plugin->server_stdout == NULL)
2146     return GNUNET_SYSERR;
2147
2148 #if DEBUG_TCP_NAT
2149   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2151 #endif
2152   /* Start the server process */
2153   plugin->server_pid = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2154   if (plugin->server_pid == GNUNET_SYSERR)
2155     {
2156 #if DEBUG_TCP_NAT
2157     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158                      "Failed to start gnunet-nat-server process\n");
2159 #endif
2160       return GNUNET_SYSERR;
2161     }
2162   /* Close the write end of the read pipe */
2163   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2164
2165   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2166   plugin->server_read_task =
2167       GNUNET_SCHEDULER_add_read_file (plugin->env->sched,
2168                                       GNUNET_TIME_UNIT_FOREVER_REL,
2169                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2170   return GNUNET_YES;
2171 }
2172
2173 /**
2174  * Return the actual path to a file found in the current
2175  * PATH environment variable.
2176  *
2177  * @param binary the name of the file to find
2178  */
2179 static char *
2180 get_path_from_PATH (char *binary)
2181 {
2182   char *path;
2183   char *pos;
2184   char *end;
2185   char *buf;
2186   const char *p;
2187
2188   p = getenv ("PATH");
2189   if (p == NULL)
2190     return NULL;
2191   path = GNUNET_strdup (p);     /* because we write on it */
2192   buf = GNUNET_malloc (strlen (path) + 20);
2193   pos = path;
2194
2195   while (NULL != (end = strchr (pos, ':')))
2196     {
2197       *end = '\0';
2198       sprintf (buf, "%s/%s", pos, binary);
2199       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2200         {
2201           GNUNET_free (path);
2202           return buf;
2203         }
2204       pos = end + 1;
2205     }
2206   sprintf (buf, "%s/%s", pos, binary);
2207   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2208     {
2209       GNUNET_free (path);
2210       return buf;
2211     }
2212   GNUNET_free (buf);
2213   GNUNET_free (path);
2214   return NULL;
2215 }
2216
2217 /**
2218  * Check whether the suid bit is set on a file.
2219  * Attempts to find the file using the current
2220  * PATH environment variable as a search path.
2221  *
2222  * @param binary the name of the file to check
2223  */
2224 static int
2225 check_gnunet_nat_binary(char *binary)
2226 {
2227   struct stat statbuf;
2228   char *p;
2229
2230   p = get_path_from_PATH (binary);
2231   if (p == NULL)
2232     return GNUNET_NO;
2233   if (0 != STAT (p, &statbuf))
2234     {
2235       GNUNET_free (p);
2236       return GNUNET_SYSERR;
2237     }
2238   GNUNET_free (p);
2239   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2240        (statbuf.st_uid == 0) )
2241     return GNUNET_YES;
2242   return GNUNET_NO;
2243 }
2244
2245 /**
2246  * Entry point for the plugin.
2247  *
2248  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2249  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2250  */
2251 void *
2252 libgnunet_plugin_transport_tcp_init (void *cls)
2253 {
2254   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2255     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2256      sizeof (struct WelcomeMessage)},
2257     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2258     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2259     {NULL, NULL, 0, 0}
2260   };
2261   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2262   struct GNUNET_TRANSPORT_PluginFunctions *api;
2263   struct Plugin *plugin;
2264   struct GNUNET_SERVICE_Context *service;
2265   unsigned long long aport;
2266   unsigned long long bport;
2267   unsigned int i;
2268   int behind_nat;
2269   int allow_nat;
2270   int only_nat_addresses;
2271   char *internal_address;
2272   char *external_address;
2273   struct sockaddr_in in_addr;
2274   struct IPv4TcpAddress t4;
2275
2276   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2277   if (service == NULL)
2278     {
2279       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2280                  _("Failed to start service for `%s' transport plugin.\n"),
2281                  "tcp");
2282       return NULL;
2283     }
2284
2285   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2286                                                            "transport-tcp",
2287                                                            "BEHIND_NAT"))
2288     {
2289       /* We are behind nat (according to the user) */
2290       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2291         {
2292           behind_nat = GNUNET_YES;
2293         }
2294       else
2295         {
2296           behind_nat = GNUNET_NO;
2297           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");
2298         }
2299     }
2300   else
2301     behind_nat = GNUNET_NO; /* We are not behind nat! */
2302
2303   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2304                                                            "transport-tcp",
2305                                                            "ALLOW_NAT"))
2306     {
2307       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2308         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2309       else
2310       {
2311         allow_nat = GNUNET_NO;
2312         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");
2313       }
2314     }
2315   else
2316     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2317
2318
2319   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2320                                                            "transport-tcp",
2321                                                            "ONLY_NAT_ADDRESSES"))
2322     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2323   else
2324     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2325
2326   external_address = NULL;
2327   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2328          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2329                                                 "transport-tcp",
2330                                                 "EXTERNAL_ADDRESS",
2331                                                 &external_address)))
2332     {
2333       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2334                        _
2335                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2336                        "transport-tcp");
2337       GNUNET_SERVICE_stop (service);
2338       return NULL;
2339     }
2340
2341   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2342     {
2343       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2344     }
2345
2346   internal_address = NULL;
2347   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2348          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2349                                                 "transport-tcp",
2350                                                 "INTERNAL_ADDRESS",
2351                                                 &internal_address)))
2352     {
2353       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2354                  _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2355                  "transport-tcp");
2356       GNUNET_SERVICE_stop (service);
2357       GNUNET_free_non_null(external_address);
2358       return NULL;
2359     }
2360
2361   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2362     {
2363       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2364     }
2365
2366   aport = 0;
2367   if ((GNUNET_OK !=
2368        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2369                                               "transport-tcp",
2370                                               "PORT",
2371                                               &bport)) ||
2372       (bport > 65535) ||
2373       ((GNUNET_OK ==
2374         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2375                                                "transport-tcp",
2376                                                "ADVERTISED-PORT",
2377                                                &aport)) && (aport > 65535)))
2378     {
2379       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2380                        _
2381                        ("Require valid port number for service `%s' in configuration!\n"),
2382                        "transport-tcp");
2383       GNUNET_free_non_null(external_address);
2384       GNUNET_free_non_null(internal_address);
2385       GNUNET_SERVICE_stop (service);
2386       return NULL;
2387     }
2388
2389   if (aport == 0)
2390     aport = bport;
2391   plugin = GNUNET_malloc (sizeof (struct Plugin));
2392   plugin->open_port = bport;
2393   plugin->adv_port = aport;
2394   plugin->external_address = external_address;
2395   plugin->internal_address = internal_address;
2396   plugin->behind_nat = behind_nat;
2397   plugin->allow_nat = allow_nat;
2398   plugin->only_nat_addresses = only_nat_addresses;
2399   plugin->env = env;
2400   plugin->lsock = NULL;
2401   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2402   api->cls = plugin;
2403   api->send = &tcp_plugin_send;
2404   api->disconnect = &tcp_plugin_disconnect;
2405   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2406   api->check_address = &tcp_plugin_check_address;
2407   api->address_to_string = &tcp_address_to_string;
2408   plugin->service = service;
2409   plugin->server = GNUNET_SERVICE_get_server (service);
2410   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2411   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2412   for (i = 0;
2413        i <
2414        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2415        i++)
2416     plugin->handlers[i].callback_cls = plugin;
2417   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2418
2419   if (plugin->behind_nat == GNUNET_YES)
2420     {
2421       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2422         {
2423           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2424
2425                            _
2426                            ("Failed to start %s required for NAT in %s!\n"),
2427                            "gnunet-nat-server"
2428                            "transport-tcp");
2429           GNUNET_free_non_null(external_address);
2430           GNUNET_free_non_null(internal_address);
2431           GNUNET_SERVICE_stop (service);
2432           GNUNET_free (api);
2433           return NULL;
2434         }
2435     }
2436
2437   if (allow_nat == GNUNET_YES)
2438     {
2439       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2440       GNUNET_assert(plugin->nat_wait_conns != NULL);
2441     }
2442
2443   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2444   if (aport != bport)
2445     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2446                      _("TCP transport advertises itself as being on port %llu\n"),
2447                      aport);
2448   GNUNET_SERVER_disconnect_notify (plugin->server, 
2449                                    &disconnect_notify,
2450                                    plugin);
2451   GNUNET_CONFIGURATION_get_value_string(env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address);
2452
2453   if (plugin->behind_nat == GNUNET_NO)
2454     {
2455       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2456     }
2457
2458   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2459                                                            env->cfg,
2460                                                            AF_UNSPEC,
2461                                                            HOSTNAME_RESOLVE_TIMEOUT,
2462                                                            &process_hostname_ips,
2463                                                            plugin);
2464
2465   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2466     {
2467       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2468       t4.t_port = htons(0);
2469       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2470       plugin->env->notify_address (plugin->env->cls,
2471                                   "tcp",
2472                                   &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2473     }
2474   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2475     {
2476       t4.t_port = htons(plugin->adv_port);
2477       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2478       plugin->env->notify_address (plugin->env->cls,
2479                                    "tcp",
2480                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2481     }
2482
2483   return api;
2484 }
2485
2486
2487 /**
2488  * Exit point from the plugin.
2489  */
2490 void *
2491 libgnunet_plugin_transport_tcp_done (void *cls)
2492 {
2493   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2494   struct Plugin *plugin = api->cls;
2495   struct Session *session;
2496   struct LocalAddrList *lal;
2497
2498   while (NULL != (session = plugin->sessions))
2499     disconnect_session (session);
2500   if (NULL != plugin->hostname_dns)
2501     {
2502       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2503       plugin->hostname_dns = NULL;
2504     }
2505   GNUNET_SERVICE_stop (plugin->service);
2506   GNUNET_free (plugin->handlers);
2507   while (NULL != (lal = plugin->lal_head))
2508     {
2509       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2510                                    plugin->lal_tail,
2511                                    lal);
2512       GNUNET_free (lal);
2513     }
2514
2515   if (plugin->behind_nat == GNUNET_YES)
2516     {
2517       if (0 != PLIBC_KILL (plugin->server_pid, SIGTERM))
2518         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2519       GNUNET_OS_process_wait (plugin->server_pid);
2520     }
2521   GNUNET_free_non_null(plugin->bind_address);
2522   GNUNET_free (plugin);
2523   GNUNET_free (api);
2524   return NULL;
2525 }
2526
2527 /* end of plugin_transport_tcp.c */