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