fix
[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 "gnunet_transport_plugin.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->receive_delay_task);
896       if (session->client != NULL)
897         GNUNET_SERVER_receive_done (session->client,
898                                     GNUNET_SYSERR);     
899     }
900   if (session->client != NULL)  
901     GNUNET_SERVER_client_drop (session->client);
902   GNUNET_STATISTICS_update (session->plugin->env->stats,
903                             gettext_noop ("# TCP sessions active"),
904                             -1,
905                             GNUNET_NO);
906   GNUNET_free_non_null (session->connect_addr);
907   GNUNET_free (session);
908 }
909
910
911 /**
912  * Given two otherwise equivalent sessions, pick the better one.
913  *
914  * @param s1 one session (also default)
915  * @param s2 other session
916  * @return "better" session (more active)
917  */
918 static struct Session *
919 select_better_session (struct Session *s1,
920                        struct Session *s2)
921 {
922   if (s1 == NULL)
923     return s2;
924   if (s2 == NULL)
925     return s1;
926   if ( (s1->expecting_welcome == GNUNET_NO) &&
927        (s2->expecting_welcome == GNUNET_YES) )
928     return s1;
929   if ( (s1->expecting_welcome == GNUNET_YES) &&
930        (s2->expecting_welcome == GNUNET_NO) )
931     return s2;
932   if (s1->last_activity.abs_value < s2->last_activity.abs_value)
933     return s2;
934   if (s1->last_activity.abs_value > s2->last_activity.abs_value)
935     return s1;
936   if ( (GNUNET_YES == s1->inbound) &&
937        (GNUNET_NO  == s2->inbound) )
938     return s1;
939   if ( (GNUNET_NO  == s1->inbound) &&
940        (GNUNET_YES == s2->inbound) )
941     return s2;
942   return s1;
943 }
944
945
946 /**
947  * We learned about a peer (possibly behind NAT) so run the
948  * gnunet-nat-client to send dummy ICMP responses
949  *
950  * @param plugin the plugin for this transport
951  * @param addr the address of the peer
952  * @param addrlen the length of the address
953  */
954 void
955 run_gnunet_nat_client (struct Plugin *plugin, const char *addr, size_t addrlen)
956 {
957   char inet4[INET_ADDRSTRLEN];
958   char *address_as_string;
959   char *port_as_string;
960   struct GNUNET_OS_Process *proc;
961   const struct sockaddr *sa = (const struct sockaddr *)addr;
962
963 #if DEBUG_TCP_NAT
964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965                   _("called run_gnunet_nat_client addrlen %d others are %d and %d\n"), addrlen, sizeof (struct sockaddr), sizeof (struct sockaddr_in));
966 #endif
967
968   if (addrlen < sizeof (struct sockaddr))
969     return;
970
971   switch (sa->sa_family)
972     {
973     case AF_INET:
974       if (addrlen != sizeof (struct sockaddr_in))
975         return;
976       if (NULL == inet_ntop (AF_INET,
977                              &((struct sockaddr_in *) sa)->sin_addr,
978                              inet4, INET_ADDRSTRLEN))
979         {
980           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop");
981           return;
982         }
983       address_as_string = GNUNET_strdup (inet4);
984       break;
985     case AF_INET6:
986     default:
987       return;
988     }
989
990   GNUNET_asprintf(&port_as_string, "%d", plugin->adv_port);
991 #if DEBUG_TCP_NAT
992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993                   _("Running gnunet-nat-client with arguments: %s %s %d\n"), plugin->external_address, address_as_string, plugin->adv_port);
994 #endif
995
996   /* Start the client process */
997   proc = GNUNET_OS_start_process(NULL, NULL, "gnunet-nat-client", "gnunet-nat-client", plugin->external_address, address_as_string, port_as_string, NULL);
998   GNUNET_free(address_as_string);
999   GNUNET_free(port_as_string);
1000   GNUNET_OS_process_wait (proc);
1001   GNUNET_OS_process_close (proc);
1002   proc = NULL;
1003 }
1004
1005
1006 /**
1007  * Function that can be used by the transport service to transmit
1008  * a message using the plugin.   Note that in the case of a
1009  * peer disconnecting, the continuation MUST be called
1010  * prior to the disconnect notification itself.  This function
1011  * will be called with this peer's HELLO message to initiate
1012  * a fresh connection to another peer.
1013  *
1014  * @param cls closure
1015  * @param target who should receive this message
1016  * @param msg the message to transmit
1017  * @param msgbuf_size number of bytes in 'msg'
1018  * @param priority how important is the message (most plugins will
1019  *                 ignore message priority and just FIFO)
1020  * @param timeout how long to wait at most for the transmission (does not
1021  *                require plugins to discard the message after the timeout,
1022  *                just advisory for the desired delay; most plugins will ignore
1023  *                this as well)
1024  * @param session which session must be used (or NULL for "any")
1025  * @param addr the address to use (can be NULL if the plugin
1026  *                is "on its own" (i.e. re-use existing TCP connection))
1027  * @param addrlen length of the address in bytes
1028  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1029  *                GNUNET_NO means the plugin may use any other address and
1030  *                GNUNET_SYSERR means that only reliable existing
1031  *                bi-directional connections should be used (regardless
1032  *                of address)
1033  * @param cont continuation to call once the message has
1034  *        been transmitted (or if the transport is ready
1035  *        for the next transmission call; or if the
1036  *        peer disconnected...); can be NULL
1037  * @param cont_cls closure for cont
1038  * @return number of bytes used (on the physical network, with overheads);
1039  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1040  *         and does NOT mean that the message was not transmitted (DV and NAT)
1041  */
1042 static ssize_t
1043 tcp_plugin_send (void *cls,
1044                  const struct GNUNET_PeerIdentity *target,
1045                  const char *msg,
1046                  size_t msgbuf_size,
1047                  uint32_t priority,
1048                  struct GNUNET_TIME_Relative timeout,
1049                  struct Session *session,
1050                  const void *addr,
1051                  size_t addrlen,
1052                  int force_address,
1053                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1054 {
1055   struct Plugin *plugin = cls;
1056   struct Session *cand_session;
1057   struct Session *next;
1058   struct PendingMessage *pm;
1059   struct GNUNET_CONNECTION_Handle *sa;
1060   int af;
1061   const void *sb;
1062   size_t sbs;
1063   struct sockaddr_in a4;
1064   struct sockaddr_in6 a6;
1065   const struct IPv4TcpAddress *t4;
1066   const struct IPv6TcpAddress *t6;
1067   unsigned int is_natd;
1068
1069   GNUNET_STATISTICS_update (plugin->env->stats,
1070                             gettext_noop ("# bytes TCP was asked to transmit"),
1071                             msgbuf_size,
1072                             GNUNET_NO);
1073   /* FIXME: we could do this cheaper with a hash table
1074      where we could restrict the iteration to entries that match
1075      the target peer... */
1076   is_natd = GNUNET_NO;
1077   if (session == NULL)
1078     {
1079       cand_session = NULL;
1080       next = plugin->sessions;
1081       while (NULL != (session = next))
1082         {
1083           next = session->next;
1084           GNUNET_assert (session->client != NULL);
1085           if (0 != memcmp (target,
1086                            &session->target,
1087                            sizeof (struct GNUNET_PeerIdentity)))
1088             continue;
1089           if ( ( (GNUNET_SYSERR == force_address) &&
1090                  (session->expecting_welcome == GNUNET_NO) ) ||
1091                (GNUNET_NO == force_address) )
1092             {
1093               cand_session = select_better_session (cand_session,
1094                                                     session);
1095               continue;
1096             }
1097           if (GNUNET_SYSERR == force_address)
1098             continue;
1099           GNUNET_break (GNUNET_YES == force_address);
1100           if (addr == NULL)
1101             {
1102               GNUNET_break (0);
1103               break;
1104             }
1105 #if IGNORE_INBOUND
1106           if (session->inbound == GNUNET_YES) /* FIXME: why do we ignore inbound sessions? */
1107             {
1108               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Ignoring inbound session\n");
1109               continue;
1110             }
1111 #endif
1112           if ((addrlen != session->connect_alen) && (session->is_nat == GNUNET_NO))
1113             continue;
1114           if ((0 != memcmp (session->connect_addr,
1115                            addr,
1116                            addrlen)) && (session->is_nat == GNUNET_NO))
1117             continue;
1118           cand_session = select_better_session (cand_session,
1119                                                 session);       
1120         }
1121       session = cand_session;
1122     }
1123   if ( (session == NULL) &&
1124        (addr == NULL) )
1125     {
1126 #if DEBUG_TCP
1127       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1128                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
1129                        GNUNET_i2s (target));
1130 #endif
1131       GNUNET_STATISTICS_update (plugin->env->stats,
1132                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
1133                                 msgbuf_size,
1134                                 GNUNET_NO);
1135       return -1;
1136     }
1137   if (session == NULL)
1138     {
1139       if (addrlen == sizeof (struct IPv6TcpAddress))
1140         {
1141           t6 = addr;
1142           af = AF_INET6;
1143           memset (&a6, 0, sizeof (a6));
1144 #if HAVE_SOCKADDR_IN_SIN_LEN
1145           a6.sin6_len = sizeof (a6);
1146 #endif
1147           a6.sin6_family = AF_INET6;
1148           a6.sin6_port = t6->t6_port;
1149           if (t6->t6_port == 0)
1150             is_natd = GNUNET_YES;
1151           memcpy (&a6.sin6_addr,
1152                   &t6->ipv6_addr,
1153                   sizeof (struct in6_addr));
1154           sb = &a6;
1155           sbs = sizeof (a6);
1156         }
1157       else if (addrlen == sizeof (struct IPv4TcpAddress))
1158         {
1159           t4 = addr;
1160           af = AF_INET;
1161           memset (&a4, 0, sizeof (a4));
1162 #if HAVE_SOCKADDR_IN_SIN_LEN
1163           a4.sin_len = sizeof (a4);
1164 #endif
1165           a4.sin_family = AF_INET;
1166           a4.sin_port = t4->t_port;
1167           if (t4->t_port == 0)
1168             is_natd = GNUNET_YES;
1169           a4.sin_addr.s_addr = t4->ipv4_addr;
1170           sb = &a4;
1171           sbs = sizeof (a4);
1172         }
1173       else
1174         {
1175           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1176                            _("Address of unexpected length: %u\n"),
1177                            addrlen);
1178           GNUNET_break (0);
1179           return -1;
1180         }
1181
1182       if ((is_natd == GNUNET_YES) && (addrlen == sizeof (struct IPv6TcpAddress)))
1183         return -1; /* NAT client only works with IPv4 addresses */
1184
1185
1186       if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) &&
1187            (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1188         {
1189 #if DEBUG_TCP_NAT
1190           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1191                            _("Found valid IPv4 NAT address (creating session)!\n"));
1192 #endif
1193           session = create_session (plugin,
1194                                     target,
1195                                     NULL, is_natd);
1196
1197           /* create new message entry */
1198           pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1199           /* FIXME: the memset of this malloc can be up to 2% of our total runtime */
1200           pm->msg = (const char*) &pm[1];
1201           memcpy (&pm[1], msg, msgbuf_size);
1202           /* FIXME: this memcpy can be up to 7% of our total run-time
1203              (for transport service) */
1204           pm->message_size = msgbuf_size;
1205           pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1206           pm->transmit_cont = cont;
1207           pm->transmit_cont_cls = cont_cls;
1208
1209           /* append pm to pending_messages list */
1210           GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1211                                              session->pending_messages_tail,
1212                                              session->pending_messages_tail,
1213                                              pm);
1214
1215           GNUNET_assert(GNUNET_CONTAINER_multihashmap_put(plugin->nat_wait_conns, &target->hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) == GNUNET_OK);
1216 #if DEBUG_TCP_NAT
1217           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1218                            "Created NAT WAIT connection to `%4s' at `%s'\n",
1219                            GNUNET_i2s (target),
1220                            GNUNET_a2s (sb, sbs));
1221 #endif
1222           run_gnunet_nat_client (plugin, sb, sbs);
1223           return 0;
1224         }
1225       else if ((plugin->allow_nat == GNUNET_YES) && (is_natd == GNUNET_YES) && (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &target->hashPubKey)))
1226         {
1227           /* Only do one NAT punch attempt per peer identity */
1228           return -1;
1229         }
1230       sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
1231       if (sa == NULL)
1232         {
1233 #if DEBUG_TCP
1234           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235                            "Failed to create connection to `%4s' at `%s'\n",
1236                            GNUNET_i2s (target),
1237                            GNUNET_a2s (sb, sbs));
1238 #endif
1239           GNUNET_STATISTICS_update (plugin->env->stats,
1240                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
1241                                     msgbuf_size,
1242                                     GNUNET_NO);
1243           return -1;
1244         }
1245 #if DEBUG_TCP_NAT
1246       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1247                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
1248                        GNUNET_i2s (target),
1249                        GNUNET_a2s (sb, sbs));
1250 #endif
1251       session = create_session (plugin,
1252                                 target,
1253                                 GNUNET_SERVER_connect_socket (plugin->server,
1254                                                               sa), is_natd);
1255       session->connect_addr = GNUNET_malloc (addrlen);
1256       memcpy (session->connect_addr,
1257               addr,
1258               addrlen);
1259       session->connect_alen = addrlen;
1260     }
1261   GNUNET_assert (session != NULL);
1262   GNUNET_assert (session->client != NULL);
1263   GNUNET_STATISTICS_update (plugin->env->stats,
1264                             gettext_noop ("# bytes currently in TCP buffers"),
1265                             msgbuf_size,
1266                             GNUNET_NO);
1267   /* create new message entry */
1268   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
1269   pm->msg = (const char*) &pm[1];
1270   memcpy (&pm[1], msg, msgbuf_size);
1271   pm->message_size = msgbuf_size;
1272   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1273   pm->transmit_cont = cont;
1274   pm->transmit_cont_cls = cont_cls;
1275
1276   /* append pm to pending_messages list */
1277   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
1278                                      session->pending_messages_tail,
1279                                      session->pending_messages_tail,
1280                                      pm);
1281 #if DEBUG_TCP
1282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283                    "Asked to transmit %u bytes to `%s', added message to list.\n",
1284                    msgbuf_size,
1285                    GNUNET_i2s (target));
1286 #endif
1287   process_pending_messages (session);
1288   return msgbuf_size;
1289 }
1290
1291
1292 /**
1293  * Function that can be called to force a disconnect from the
1294  * specified neighbour.  This should also cancel all previously
1295  * scheduled transmissions.  Obviously the transmission may have been
1296  * partially completed already, which is OK.  The plugin is supposed
1297  * to close the connection (if applicable) and no longer call the
1298  * transmit continuation(s).
1299  *
1300  * Finally, plugin MUST NOT call the services's receive function to
1301  * notify the service that the connection to the specified target was
1302  * closed after a getting this call.
1303  *
1304  * @param cls closure
1305  * @param target peer for which the last transmission is
1306  *        to be cancelled
1307  */
1308 static void
1309 tcp_plugin_disconnect (void *cls,
1310                        const struct GNUNET_PeerIdentity *target)
1311 {
1312   struct Plugin *plugin = cls;
1313   struct Session *session;
1314   struct Session *next;
1315   struct PendingMessage *pm;
1316
1317 #if DEBUG_TCP
1318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319                    "Asked to cancel session with `%4s'\n",
1320                    GNUNET_i2s (target));
1321 #endif
1322   next = plugin->sessions;
1323   while (NULL != (session = next))
1324     {
1325       next = session->next;
1326       if (0 != memcmp (target,
1327                        &session->target,
1328                        sizeof (struct GNUNET_PeerIdentity)))
1329         continue;
1330       pm = session->pending_messages_head;
1331       while (pm != NULL)
1332         {
1333           pm->transmit_cont = NULL;
1334           pm->transmit_cont_cls = NULL;
1335           pm = pm->next;
1336         }
1337       disconnect_session (session);
1338     }
1339 }
1340
1341
1342 /**
1343  * Context for address to string conversion.
1344  */
1345 struct PrettyPrinterContext
1346 {
1347   /**
1348    * Function to call with the result.
1349    */
1350   GNUNET_TRANSPORT_AddressStringCallback asc;
1351
1352   /**
1353    * Clsoure for 'asc'.
1354    */
1355   void *asc_cls;
1356
1357   /**
1358    * Port to add after the IP address.
1359    */
1360   uint16_t port;
1361 };
1362
1363
1364 /**
1365  * Append our port and forward the result.
1366  *
1367  * @param cls the 'struct PrettyPrinterContext*'
1368  * @param hostname hostname part of the address
1369  */
1370 static void
1371 append_port (void *cls, const char *hostname)
1372 {
1373   struct PrettyPrinterContext *ppc = cls;
1374   char *ret;
1375
1376   if (hostname == NULL)
1377     {
1378       ppc->asc (ppc->asc_cls, NULL);
1379       GNUNET_free (ppc);
1380       return;
1381     }
1382   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1383   ppc->asc (ppc->asc_cls, ret);
1384   GNUNET_free (ret);
1385 }
1386
1387
1388 /**
1389  * Convert the transports address to a nice, human-readable
1390  * format.
1391  *
1392  * @param cls closure
1393  * @param type name of the transport that generated the address
1394  * @param addr one of the addresses of the host, NULL for the last address
1395  *        the specific address format depends on the transport
1396  * @param addrlen length of the address
1397  * @param numeric should (IP) addresses be displayed in numeric form?
1398  * @param timeout after how long should we give up?
1399  * @param asc function to call on each string
1400  * @param asc_cls closure for asc
1401  */
1402 static void
1403 tcp_plugin_address_pretty_printer (void *cls,
1404                                    const char *type,
1405                                    const void *addr,
1406                                    size_t addrlen,
1407                                    int numeric,
1408                                    struct GNUNET_TIME_Relative timeout,
1409                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1410                                    void *asc_cls)
1411 {
1412   struct Plugin *plugin = cls;
1413   struct PrettyPrinterContext *ppc;
1414   const void *sb;
1415   size_t sbs;
1416   struct sockaddr_in a4;
1417   struct sockaddr_in6 a6;
1418   const struct IPv4TcpAddress *t4;
1419   const struct IPv6TcpAddress *t6;
1420   uint16_t port;
1421
1422   if (addrlen == sizeof (struct IPv6TcpAddress))
1423     {
1424       t6 = addr;
1425       memset (&a6, 0, sizeof (a6));
1426       a6.sin6_family = AF_INET6;
1427       a6.sin6_port = t6->t6_port;
1428       memcpy (&a6.sin6_addr,
1429               &t6->ipv6_addr,
1430               sizeof (struct in6_addr));
1431       port = ntohs (t6->t6_port);
1432       sb = &a6;
1433       sbs = sizeof (a6);
1434     }
1435   else if (addrlen == sizeof (struct IPv4TcpAddress))
1436     {
1437       t4 = addr;
1438       memset (&a4, 0, sizeof (a4));
1439       a4.sin_family = AF_INET;
1440       a4.sin_port = t4->t_port;
1441       a4.sin_addr.s_addr = t4->ipv4_addr;
1442       port = ntohs (t4->t_port);
1443       sb = &a4;
1444       sbs = sizeof (a4);
1445     }
1446   else
1447     {
1448       /* invalid address */
1449       GNUNET_break_op (0);
1450       asc (asc_cls, NULL);
1451       return;
1452     }
1453   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1454   ppc->asc = asc;
1455   ppc->asc_cls = asc_cls;
1456   ppc->port = port;
1457   GNUNET_RESOLVER_hostname_get (plugin->env->cfg,
1458                                 sb,
1459                                 sbs,
1460                                 !numeric, timeout, &append_port, ppc);
1461 }
1462
1463
1464 /**
1465  * Check if the given port is plausible (must be either
1466  * our listen port or our advertised port).  If it is
1467  * neither, we return GNUNET_SYSERR.
1468  *
1469  * @param plugin global variables
1470  * @param in_port port number to check
1471  * @return GNUNET_OK if port is either open_port or adv_port
1472  */
1473 static int
1474 check_port (struct Plugin *plugin, uint16_t in_port)
1475 {
1476   if ( (plugin->behind_nat == GNUNET_YES) && (in_port == 0) )
1477     return GNUNET_OK;
1478   if ( (plugin->only_nat_addresses == GNUNET_YES) &&
1479        (plugin->behind_nat == GNUNET_YES) )
1480     {
1481       return GNUNET_SYSERR; /* odd case... */
1482     }
1483   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1484     return GNUNET_OK;
1485   return GNUNET_SYSERR;
1486 }
1487
1488
1489 /**
1490  * Function that will be called to check if a binary address for this
1491  * plugin is well-formed and corresponds to an address for THIS peer
1492  * (as per our configuration).  Naturally, if absolutely necessary,
1493  * plugins can be a bit conservative in their answer, but in general
1494  * plugins should make sure that the address does not redirect
1495  * traffic to a 3rd party that might try to man-in-the-middle our
1496  * traffic.
1497  *
1498  * @param cls closure, our 'struct Plugin*'
1499  * @param addr pointer to the address
1500  * @param addrlen length of addr
1501  * @return GNUNET_OK if this is a plausible address for this peer
1502  *         and transport, GNUNET_SYSERR if not
1503  */
1504 static int
1505 tcp_plugin_check_address (void *cls,
1506                           const void *addr,
1507                           size_t addrlen)
1508 {
1509   struct Plugin *plugin = cls;
1510   struct IPv4TcpAddress *v4;
1511   struct IPv6TcpAddress *v6;
1512
1513   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1514       (addrlen != sizeof (struct IPv6TcpAddress)))
1515     {
1516       GNUNET_break_op (0);
1517       return GNUNET_SYSERR;
1518     }
1519   if (addrlen == sizeof (struct IPv4TcpAddress))
1520     {
1521       v4 = (struct IPv4TcpAddress *) addr;
1522       if (GNUNET_OK !=
1523           check_port (plugin, ntohs (v4->t_port)))
1524         return GNUNET_SYSERR;
1525       if (GNUNET_OK !=
1526           check_local_addr (plugin, &v4->ipv4_addr, sizeof (uint32_t)))
1527         {
1528           return GNUNET_SYSERR;
1529         }
1530     }
1531   else
1532     {
1533       v6 = (struct IPv6TcpAddress *) addr;
1534       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1535         {
1536           GNUNET_break_op (0);
1537           return GNUNET_SYSERR;
1538         }
1539       if (GNUNET_OK !=
1540           check_port (plugin, ntohs (v6->t6_port)))
1541         return GNUNET_SYSERR;
1542       if (GNUNET_OK !=
1543           check_local_addr (plugin, &v6->ipv6_addr, sizeof (struct in6_addr)))
1544         {
1545           return GNUNET_SYSERR;
1546         }
1547     }
1548   return GNUNET_OK;
1549 }
1550
1551 /**
1552  * We've received a nat probe from this peer via TCP.  Finish
1553  * creating the client session and resume sending of queued
1554  * messages.
1555  *
1556  * @param cls closure
1557  * @param client identification of the client
1558  * @param message the actual message
1559  */
1560 static void
1561 handle_tcp_nat_probe (void *cls,
1562                      struct GNUNET_SERVER_Client *client,
1563                      const struct GNUNET_MessageHeader *message)
1564 {
1565   struct Plugin *plugin = cls;
1566   struct Session *session;
1567   struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1568   size_t alen;
1569   void *vaddr;
1570   struct IPv4TcpAddress *t4;
1571   struct IPv6TcpAddress *t6;
1572   const struct sockaddr_in *s4;
1573   const struct sockaddr_in6 *s6;
1574
1575 #if DEBUG_TCP_NAT
1576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received tcp NAT probe\n");
1577 #endif
1578   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1579    * a connection to this peer by running gnunet-nat-client.  This peer
1580    * received the punch message and now wants us to use the new connection
1581    * as the default for that peer.  Do so and then send a WELCOME message
1582    * so we can really be connected!
1583    */
1584   if (ntohs(message->size) != sizeof(struct TCP_NAT_ProbeMessage))
1585     {
1586 #if DEBUG_TCP_NAT
1587       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));
1588 #endif
1589       GNUNET_break_op(0);
1590       return;
1591     }
1592   tcp_nat_probe = (struct TCP_NAT_ProbeMessage *)message;
1593
1594   if (GNUNET_CONTAINER_multihashmap_contains(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey) == GNUNET_YES)
1595     {
1596 #if DEBUG_TCP_NAT
1597       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found session for NAT probe!\n");
1598 #endif
1599       session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey);
1600       GNUNET_assert(session != NULL);
1601       GNUNET_assert(GNUNET_CONTAINER_multihashmap_remove(plugin->nat_wait_conns, &tcp_nat_probe->clientIdentity.hashPubKey, session) == GNUNET_YES);
1602       GNUNET_SERVER_client_keep (client);
1603       session->client = client;
1604       session->last_activity = GNUNET_TIME_absolute_get ();
1605       session->inbound = GNUNET_NO;
1606
1607       if (GNUNET_OK ==
1608           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1609         {
1610 #if DEBUG_TCP_NAT
1611           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1612                            "handle_tcp_nat_probe Found address `%s' for incoming connection %p\n",
1613                            GNUNET_a2s (vaddr, alen),
1614                            client);
1615 #endif
1616           if (((const struct sockaddr *)vaddr)->sa_family == AF_INET)
1617             {
1618               s4 = vaddr;
1619               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1620               t4->t_port = s4->sin_port;
1621               t4->ipv4_addr = s4->sin_addr.s_addr;
1622               session->connect_addr = t4;
1623               session->connect_alen = sizeof (struct IPv4TcpAddress);
1624             }
1625           else if (((const struct sockaddr *)vaddr)->sa_family == AF_INET6)
1626             {
1627               s6 = vaddr;
1628               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1629               t6->t6_port = s6->sin6_port;
1630               memcpy (&t6->ipv6_addr,
1631                       &s6->sin6_addr,
1632                       sizeof (struct in6_addr));
1633               session->connect_addr = t6;
1634               session->connect_alen = sizeof (struct IPv6TcpAddress);
1635             }
1636           else
1637             {
1638 #if DEBUG_TCP_NAT
1639               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1640                           "Bad address for incoming connection!\n");
1641 #endif
1642             }
1643           GNUNET_free (vaddr);
1644         }
1645
1646       session->next = plugin->sessions;
1647       plugin->sessions = session;
1648       GNUNET_STATISTICS_update (plugin->env->stats,
1649                                 gettext_noop ("# TCP sessions active"),
1650                                 1,
1651                                 GNUNET_NO);
1652       process_pending_messages (session);
1653     }
1654   else
1655     {
1656 #if DEBUG_TCP_NAT
1657       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Did NOT find session for NAT probe!\n");
1658 #endif
1659     }
1660
1661   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1662 }
1663
1664 /**
1665  * We've received a welcome from this peer via TCP.  Possibly create a
1666  * fresh client record and send back our welcome.
1667  *
1668  * @param cls closure
1669  * @param client identification of the client
1670  * @param message the actual message
1671  */
1672 static void
1673 handle_tcp_welcome (void *cls,
1674                     struct GNUNET_SERVER_Client *client,
1675                     const struct GNUNET_MessageHeader *message)
1676 {
1677   struct Plugin *plugin = cls;
1678   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1679   struct Session *session;
1680   size_t alen;
1681   void *vaddr;
1682   struct IPv4TcpAddress *t4;
1683   struct IPv6TcpAddress *t6;
1684   const struct sockaddr_in *s4;
1685   const struct sockaddr_in6 *s6;
1686
1687 #if DEBUG_TCP
1688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689                    "Received %s message from a `%4s/%p'.\n",
1690                    "WELCOME",
1691                    GNUNET_i2s (&wm->clientIdentity), client);
1692 #endif
1693   GNUNET_STATISTICS_update (plugin->env->stats,
1694                             gettext_noop ("# TCP WELCOME messages received"),
1695                             1,
1696                             GNUNET_NO);
1697 #if MULTIPLE_PEER_SESSIONS
1698   session = find_session_by_client (plugin, client);
1699 #else
1700   session = find_session_by_id(plugin, &wm->clientIdentity);
1701 #endif
1702
1703   if (session == NULL)
1704     {
1705       GNUNET_SERVER_client_keep (client);
1706 #if DEBUG_TCP_NAT
1707       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1708                        "Received %s message from a `%4s/%p', creating session\n",
1709                        "WELCOME",
1710                        GNUNET_i2s (&wm->clientIdentity), client);
1711 #endif
1712       session = create_session (plugin,
1713                                 &wm->clientIdentity, client, GNUNET_NO);
1714       session->inbound = GNUNET_YES;
1715       if (GNUNET_OK ==
1716           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1717         {
1718 #if DEBUG_TCP_NAT
1719           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1720                            "Found address `%s' for incoming connection %p\n",
1721                            GNUNET_a2s (vaddr, alen),
1722                            client);
1723 #endif
1724           if (alen == sizeof (struct sockaddr_in))
1725             {
1726               s4 = vaddr;
1727               t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1728               t4->t_port = s4->sin_port;
1729               t4->ipv4_addr = s4->sin_addr.s_addr;
1730               session->connect_addr = t4;
1731               session->connect_alen = sizeof (struct IPv4TcpAddress);
1732             }
1733           else if (alen == sizeof (struct sockaddr_in6))
1734             {
1735               s6 = vaddr;
1736               t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1737               t6->t6_port = s6->sin6_port;
1738               memcpy (&t6->ipv6_addr,
1739                       &s6->sin6_addr,
1740                       sizeof (struct in6_addr));
1741               session->connect_addr = t6;
1742               session->connect_alen = sizeof (struct IPv6TcpAddress);
1743             }
1744
1745           GNUNET_free (vaddr);
1746         }
1747       else
1748         {
1749 #if DEBUG_TCP
1750           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1751                            "Did not obtain TCP socket address for incoming connection\n");
1752 #endif
1753         }
1754 #if DEBUG_TCP
1755       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1756                        "Creating new session %p for connection %p\n",
1757                        session, client);
1758 #endif
1759       process_pending_messages (session);
1760     }
1761   else
1762     {
1763 #if DEBUG_TCP_NAT
1764     if (GNUNET_OK ==
1765         GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1766       {
1767         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1768                     "Found address `%s' (already have session) for incoming connection %p\n",
1769                     GNUNET_a2s (vaddr, alen),
1770                     client);
1771       }
1772 #endif
1773     }
1774
1775 #if MULTIPLE_PEER_SESSIONS
1776   if (session->expecting_welcome != GNUNET_YES)
1777     {
1778       GNUNET_break_op (0);
1779       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1780       return;
1781     }
1782 #endif
1783   session->last_activity = GNUNET_TIME_absolute_get ();
1784   session->expecting_welcome = GNUNET_NO;
1785   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1786 }
1787
1788
1789 /**
1790  * Task to signal the server that we can continue
1791  * receiving from the TCP client now.
1792  *
1793  * @param cls the 'struct Session*'
1794  * @param tc task context (unused)
1795  */
1796 static void
1797 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1798 {
1799   struct Session *session = cls;
1800   struct GNUNET_TIME_Relative delay;
1801
1802   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1803   delay = session->plugin->env->receive (session->plugin->env->cls,
1804                                          &session->target,
1805                                          NULL, 0,
1806                                          session,
1807                                          NULL, 0);
1808   if (delay.rel_value == 0)
1809     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1810   else
1811     session->receive_delay_task =
1812       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1813 }
1814
1815
1816 /**
1817  * We've received data for this peer via TCP.  Unbox,
1818  * compute latency and forward.
1819  *
1820  * @param cls closure
1821  * @param client identification of the client
1822  * @param message the actual message
1823  */
1824 static void
1825 handle_tcp_data (void *cls,
1826                  struct GNUNET_SERVER_Client *client,
1827                  const struct GNUNET_MessageHeader *message)
1828 {
1829   struct Plugin *plugin = cls;
1830   struct Session *session;
1831   struct GNUNET_TIME_Relative delay;
1832
1833   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type)) || (ntohs(message->type) == GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE))
1834     {
1835       /* We don't want to propagate WELCOME and NAT Probe messages up! */
1836       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1837       return;
1838     }
1839   session = find_session_by_client (plugin, client);
1840   if ( (NULL == session) || (GNUNET_YES == session->expecting_welcome))
1841     {
1842       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1843       return;
1844     }
1845   session->last_activity = GNUNET_TIME_absolute_get ();
1846 #if DEBUG_TCP > 1
1847   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1848                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1849                    (unsigned int) ntohs (message->size),
1850                    (unsigned int) ntohs (message->type),
1851                    GNUNET_i2s (&session->target));
1852 #endif
1853   GNUNET_STATISTICS_update (plugin->env->stats,
1854                             gettext_noop ("# bytes received via TCP"),
1855                             ntohs (message->size),
1856                             GNUNET_NO);
1857   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1858                                 session,
1859                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1860                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1861   if (delay.rel_value == 0)
1862     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1863   else
1864     session->receive_delay_task =
1865       GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1866 }
1867
1868
1869 /**
1870  * Functions with this signature are called whenever a peer
1871  * is disconnected on the network level.
1872  *
1873  * @param cls closure
1874  * @param client identification of the client
1875  */
1876 static void
1877 disconnect_notify (void *cls,
1878                    struct GNUNET_SERVER_Client *client)
1879 {
1880   struct Plugin *plugin = cls;
1881   struct Session *session;
1882
1883   if (client == NULL)
1884     return;
1885   session = find_session_by_client (plugin, client);
1886   if (session == NULL)
1887     return;                     /* unknown, nothing to do */
1888 #if DEBUG_TCP
1889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1890                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1891                    GNUNET_i2s (&session->target),
1892                    (session->connect_addr != NULL) ?
1893                    tcp_address_to_string (session->plugin,
1894                                           session->connect_addr,
1895                                           session->connect_alen) : "*",
1896                    client);
1897 #endif
1898   disconnect_session (session);
1899 }
1900
1901
1902 /**
1903  * Add the IP of our network interface to the list of
1904  * our external IP addresses.
1905  *
1906  * @param cls the 'struct Plugin*'
1907  * @param name name of the interface
1908  * @param isDefault do we think this may be our default interface
1909  * @param addr address of the interface
1910  * @param addrlen number of bytes in addr
1911  * @return GNUNET_OK to continue iterating
1912  */
1913 static int
1914 process_interfaces (void *cls,
1915                     const char *name,
1916                     int isDefault,
1917                     const struct sockaddr *addr, socklen_t addrlen)
1918 {
1919   struct Plugin *plugin = cls;
1920   int af;
1921   struct IPv4TcpAddress t4;
1922   struct IPv6TcpAddress t6;
1923   struct IPv4TcpAddress t4_nat;
1924   struct IPv6TcpAddress t6_nat;
1925   void *arg;
1926   uint16_t args;
1927   void *arg_nat;
1928   char buf[INET_ADDRSTRLEN];
1929
1930   af = addr->sa_family;
1931   arg_nat = NULL;
1932   if (af == AF_INET)
1933     {
1934       t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1935       GNUNET_assert(NULL != inet_ntop(AF_INET, &t4.ipv4_addr, &buf[0], INET_ADDRSTRLEN));
1936       if ((plugin->bind_address != NULL) && (0 != strcmp(buf, plugin->bind_address)))
1937         {
1938           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s: Not notifying transport of address %s\n", "TCP", GNUNET_a2s (addr, addrlen));
1939           return GNUNET_OK;
1940         }
1941       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
1942       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1943         t4.t_port = htons(0);
1944       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1945         {
1946           t4_nat.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1947           t4_nat.t_port = htons(plugin->adv_port);
1948           arg_nat = &t4_nat;
1949         }
1950       else
1951         t4.t_port = htons (plugin->adv_port);
1952       arg = &t4;
1953       args = sizeof (t4);
1954     }
1955   else if (af == AF_INET6)
1956     {
1957       if ((IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr)) || (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(plugin->env->cfg, "transport-tcp", "disablev6")))
1958         {
1959           /* skip link local addresses */
1960           return GNUNET_OK;
1961         }
1962       memcpy (&t6.ipv6_addr,
1963               &((struct sockaddr_in6 *) addr)->sin6_addr,
1964               sizeof (struct in6_addr));
1965       add_to_address_list (plugin, &t6.ipv6_addr, sizeof (struct in6_addr));
1966       if ((plugin->behind_nat == GNUNET_YES) && (plugin->only_nat_addresses == GNUNET_YES))
1967         t6.t6_port = htons(0);
1968       else if (plugin->behind_nat == GNUNET_YES) /* We are behind NAT, but will advertise NAT and normal addresses */
1969         {
1970           memcpy (&t6_nat.ipv6_addr,
1971                   &((struct sockaddr_in6 *) addr)->sin6_addr,
1972                   sizeof (struct in6_addr));
1973           t6_nat.t6_port = htons(plugin->adv_port);
1974           arg_nat = &t6;
1975         }
1976       else
1977         t6.t6_port = htons (plugin->adv_port);
1978       arg = &t6;
1979       args = sizeof (t6);
1980     }
1981   else
1982     {
1983       GNUNET_break (0);
1984       return GNUNET_OK;
1985     }
1986   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1987                    _("Found address `%s' (%s) len %d\n"),
1988                    GNUNET_a2s (addr, addrlen), name, args);
1989
1990   plugin->env->notify_address (plugin->env->cls,
1991                                "tcp",
1992                                arg, args, GNUNET_TIME_UNIT_FOREVER_REL);
1993
1994   if (arg_nat != NULL)
1995     {
1996       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1997                       _("Found address `%s' (%s) len %d\n"),
1998                       GNUNET_a2s (addr, addrlen), name, args);
1999       plugin->env->notify_address (plugin->env->cls,
2000                                    "tcp",
2001                                    arg_nat, args, GNUNET_TIME_UNIT_FOREVER_REL);
2002     }
2003
2004   return GNUNET_OK;
2005 }
2006
2007
2008 /**
2009  * Function called by the resolver for each address obtained from DNS
2010  * for our own hostname.  Add the addresses to the list of our
2011  * external IP addresses.
2012  *
2013  * @param cls closure
2014  * @param addr one of the addresses of the host, NULL for the last address
2015  * @param addrlen length of the address
2016  */
2017 static void
2018 process_hostname_ips (void *cls,
2019                       const struct sockaddr *addr, socklen_t addrlen)
2020 {
2021   struct Plugin *plugin = cls;
2022
2023   if (addr == NULL)
2024     {
2025       plugin->hostname_dns = NULL;
2026       return;
2027     }
2028   /* FIXME: Can we figure out our external address here so it doesn't need to be user specified? */
2029   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
2030 }
2031
2032 /**
2033  * We can now send a probe message, copy into buffer to really send.
2034  *
2035  * @param cls closure, a struct TCPProbeContext
2036  * @param size max size to copy
2037  * @param buf buffer to copy message to
2038  */
2039 static size_t notify_send_probe (void *cls,
2040                                  size_t size, void *buf)
2041 {
2042   struct TCPProbeContext *tcp_probe_ctx = cls;
2043
2044   if (buf == NULL)
2045     {
2046       return 0;
2047     }
2048
2049   GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
2050   memcpy(buf, &tcp_probe_ctx->message, sizeof(tcp_probe_ctx->message));
2051   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2052                                 tcp_probe_ctx->sock);
2053
2054   GNUNET_free(tcp_probe_ctx);
2055   return sizeof(tcp_probe_ctx->message);
2056 }
2057
2058 /*
2059  * @param cls the plugin handle
2060  * @param tc the scheduling context (for rescheduling this function again)
2061  *
2062  * We have been notified that gnunet-nat-server has written something to stdout.
2063  * Handle the output, then reschedule this function to be called again once
2064  * more is available.
2065  *
2066  */
2067 static void
2068 tcp_plugin_server_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2069 {
2070   struct Plugin *plugin = cls;
2071   char mybuf[40];
2072   ssize_t bytes;
2073   memset(&mybuf, 0, sizeof(mybuf));
2074   int i;
2075   int port;
2076   char *port_start;
2077   struct sockaddr_in in_addr;
2078   struct TCPProbeContext *tcp_probe_ctx;
2079   struct GNUNET_CONNECTION_Handle *sock;
2080
2081   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2082     return;
2083
2084   bytes = GNUNET_DISK_file_read(plugin->server_stdout_handle, &mybuf, sizeof(mybuf));
2085
2086   if (bytes < 1)
2087     {
2088 #if DEBUG_TCP_NAT
2089       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2090                       _("Finished reading from server stdout with code: %d\n"), bytes);
2091 #endif
2092       return;
2093     }
2094
2095   port_start = NULL;
2096   for (i = 0; i < sizeof(mybuf); i++)
2097     {
2098       if (mybuf[i] == '\n')
2099         mybuf[i] = '\0';
2100
2101       if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf)))
2102         {
2103           mybuf[i] = '\0';
2104           port_start = &mybuf[i + 1];
2105         }
2106     }
2107
2108   if (port_start != NULL)
2109     port = atoi(port_start);
2110   else
2111     {
2112       plugin->server_read_task =
2113            GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2114                                            plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2115       return;
2116     }
2117
2118 #if DEBUG_TCP_NAT
2119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120                   _("nat-server-read read: %s port %d\n"), &mybuf, port);
2121 #endif
2122
2123
2124   if (inet_pton(AF_INET, &mybuf[0], &in_addr.sin_addr) != 1)
2125     {
2126
2127       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2128                   _("nat-server-read malformed address\n"), &mybuf, port);
2129
2130       plugin->server_read_task =
2131           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2132                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2133       return;
2134     }
2135
2136   in_addr.sin_family = AF_INET;
2137   in_addr.sin_port = htons(port);
2138   /**
2139    * We have received an ICMP response, ostensibly from a non-NAT'd peer
2140    *  that wants to connect to us! Send a message to establish a connection.
2141    */
2142   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, (struct sockaddr *)&in_addr,
2143                                                  sizeof(in_addr));
2144
2145
2146   if (sock == NULL)
2147     {
2148       plugin->server_read_task =
2149           GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2150                                           plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2151       return;
2152     }
2153   else
2154     {
2155       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156                 _("Sending TCP probe message!\n"), &mybuf, port);
2157
2158       tcp_probe_ctx = GNUNET_malloc(sizeof(struct TCPProbeContext));
2159       tcp_probe_ctx->message.header.size = htons(sizeof(struct TCP_NAT_ProbeMessage));
2160       tcp_probe_ctx->message.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2161       memcpy(&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity, sizeof(struct GNUNET_PeerIdentity));
2162       tcp_probe_ctx->plugin = plugin;
2163       tcp_probe_ctx->sock = sock;
2164       tcp_probe_ctx->transmit_handle = GNUNET_CONNECTION_notify_transmit_ready (sock,
2165                                                                  ntohs(tcp_probe_ctx->message.header.size),
2166                                                                  GNUNET_TIME_UNIT_FOREVER_REL,
2167                                                                  &notify_send_probe, tcp_probe_ctx);
2168
2169     }
2170
2171   /*GNUNET_SERVER_connect_socket(plugin->server, sock);*/
2172   plugin->server_read_task =
2173       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2174                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2175 }
2176
2177 /**
2178  * Start the gnunet-nat-server process for users behind NAT.
2179  *
2180  * @param plugin the transport plugin
2181  *
2182  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
2183  */
2184 static int
2185 tcp_transport_start_nat_server(struct Plugin *plugin)
2186 {
2187
2188   plugin->server_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_NO, GNUNET_YES);
2189   if (plugin->server_stdout == NULL)
2190     return GNUNET_SYSERR;
2191
2192 #if DEBUG_TCP_NAT
2193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194                    "Starting gnunet-nat-server process cmd: %s %s\n", "gnunet-nat-server", plugin->internal_address);
2195 #endif
2196   /* Start the server process */
2197   plugin->server_proc = GNUNET_OS_start_process(NULL, plugin->server_stdout, "gnunet-nat-server", "gnunet-nat-server", plugin->internal_address, NULL);
2198   if (plugin->server_proc == NULL)
2199     {
2200 #if DEBUG_TCP_NAT
2201     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2202                      "Failed to start gnunet-nat-server process\n");
2203 #endif
2204       return GNUNET_SYSERR;
2205     }
2206   /* Close the write end of the read pipe */
2207   GNUNET_DISK_pipe_close_end(plugin->server_stdout, GNUNET_DISK_PIPE_END_WRITE);
2208
2209   plugin->server_stdout_handle = GNUNET_DISK_pipe_handle(plugin->server_stdout, GNUNET_DISK_PIPE_END_READ);
2210   plugin->server_read_task =
2211       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
2212                                       plugin->server_stdout_handle, &tcp_plugin_server_read, plugin);
2213   return GNUNET_YES;
2214 }
2215
2216
2217 /**
2218  * Return the actual path to a file found in the current
2219  * PATH environment variable.
2220  *
2221  * @param binary the name of the file to find
2222  */
2223 static char *
2224 get_path_from_PATH (char *binary)
2225 {
2226   char *path;
2227   char *pos;
2228   char *end;
2229   char *buf;
2230   const char *p;
2231
2232   p = getenv ("PATH");
2233   if (p == NULL)
2234     {
2235       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2236                   _("PATH environment variable is unset.\n"));
2237       return NULL;
2238     }
2239   path = GNUNET_strdup (p);     /* because we write on it */
2240   buf = GNUNET_malloc (strlen (path) + 20);
2241   pos = path;
2242
2243   while (NULL != (end = strchr (pos, PATH_SEPARATOR)))
2244     {
2245       *end = '\0';
2246       sprintf (buf, "%s/%s", pos, binary);
2247       if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2248         {
2249           GNUNET_free (path);
2250           return buf;
2251         }
2252       pos = end + 1;
2253     }
2254   sprintf (buf, "%s/%s", pos, binary);
2255   if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
2256     {
2257       GNUNET_free (path);
2258       return buf;
2259     }
2260   GNUNET_free (buf);
2261   GNUNET_free (path);
2262   return NULL;
2263 }
2264
2265 /**
2266  * Check whether the suid bit is set on a file.
2267  * Attempts to find the file using the current
2268  * PATH environment variable as a search path.
2269  *
2270  * @param binary the name of the file to check
2271  */
2272 static int
2273 check_gnunet_nat_binary(char *binary)
2274 {
2275   struct stat statbuf;
2276   char *p;
2277 #ifdef MINGW
2278   SOCKET rawsock;
2279 #endif
2280
2281 #ifdef MINGW
2282   char *binaryexe;
2283   GNUNET_asprintf (&binaryexe, "%s.exe", binary);
2284   p = get_path_from_PATH (binaryexe);
2285   free (binaryexe);
2286 #else
2287   p = get_path_from_PATH (binary);
2288 #endif
2289   if (p == NULL)
2290     {
2291       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2292                   _("Could not find binary `%s' in PATH!\n"),
2293                   binary);
2294       return GNUNET_NO;
2295     }
2296   if (0 != STAT (p, &statbuf))
2297     {
2298       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
2299                   _("stat (%s) failed: %s\n"), 
2300                   p,
2301                   STRERROR (errno));
2302       GNUNET_free (p);
2303       return GNUNET_SYSERR;
2304     }
2305   GNUNET_free (p);
2306 #ifndef MINGW
2307   if ( (0 != (statbuf.st_mode & S_ISUID)) &&
2308        (statbuf.st_uid == 0) )
2309     return GNUNET_YES;
2310   return GNUNET_NO;
2311 #else
2312   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
2313   if (INVALID_SOCKET == rawsock)
2314     {
2315       DWORD err = GetLastError ();
2316       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
2317                   "socket (AF_INET, SOCK_RAW, IPPROTO_ICMP) have failed! GLE = %d\n", err);
2318       return GNUNET_NO; /* not running as administrator */
2319     }
2320   closesocket (rawsock);
2321   return GNUNET_YES;
2322 #endif
2323 }
2324
2325 /**
2326  * Entry point for the plugin.
2327  *
2328  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2329  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2330  */
2331 void *
2332 libgnunet_plugin_transport_tcp_init (void *cls)
2333 {
2334   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2335     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2336      sizeof (struct WelcomeMessage)},
2337     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE, sizeof (struct TCP_NAT_ProbeMessage)},
2338     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2339     {NULL, NULL, 0, 0}
2340   };
2341   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2342   struct GNUNET_TRANSPORT_PluginFunctions *api;
2343   struct Plugin *plugin;
2344   struct GNUNET_SERVICE_Context *service;
2345   unsigned long long aport;
2346   unsigned long long bport;
2347   unsigned int i;
2348   int behind_nat;
2349   int allow_nat;
2350   int only_nat_addresses;
2351   char *internal_address;
2352   char *external_address;
2353   struct sockaddr_in in_addr;
2354   struct IPv4TcpAddress t4;
2355
2356   service = GNUNET_SERVICE_start ("transport-tcp", env->cfg);
2357   if (service == NULL)
2358     {
2359       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2360                  _("Failed to start service for `%s' transport plugin.\n"),
2361                  "tcp");
2362       return NULL;
2363     }
2364
2365   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2366                                                            "transport-tcp",
2367                                                            "BEHIND_NAT"))
2368     {
2369       /* We are behind nat (according to the user) */
2370       if (check_gnunet_nat_binary("gnunet-nat-server") == GNUNET_YES)
2371         {
2372           behind_nat = GNUNET_YES;
2373         }
2374       else
2375         {
2376           behind_nat = GNUNET_NO;
2377           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");
2378         }
2379     }
2380   else
2381     behind_nat = GNUNET_NO; /* We are not behind nat! */
2382
2383   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2384                                                            "transport-tcp",
2385                                                            "ALLOW_NAT"))
2386     {
2387       if (check_gnunet_nat_binary("gnunet-nat-client") == GNUNET_YES)
2388         allow_nat = GNUNET_YES; /* We will try to connect to NAT'd peers */
2389       else
2390       {
2391         allow_nat = GNUNET_NO;
2392         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");
2393       }
2394     }
2395   else
2396     allow_nat = GNUNET_NO; /* We don't want to try to help NAT'd peers */
2397
2398
2399   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2400                                                            "transport-tcp",
2401                                                            "ONLY_NAT_ADDRESSES"))
2402     only_nat_addresses = GNUNET_YES; /* We will only report our addresses as NAT'd */
2403   else
2404     only_nat_addresses = GNUNET_NO; /* We will report our addresses as NAT'd and non-NAT'd */
2405
2406   external_address = NULL;
2407   if (((GNUNET_YES == behind_nat) || (GNUNET_YES == allow_nat)) && (GNUNET_OK !=
2408          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2409                                                 "transport-tcp",
2410                                                 "EXTERNAL_ADDRESS",
2411                                                 &external_address)))
2412     {
2413       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2414                        _
2415                        ("Require EXTERNAL_ADDRESS for service `%s' in configuration (either BEHIND_NAT or ALLOW_NAT set to YES)!\n"),
2416                        "transport-tcp");
2417       GNUNET_SERVICE_stop (service);
2418       return NULL;
2419     }
2420
2421   if ((external_address != NULL) && (inet_pton(AF_INET, external_address, &in_addr.sin_addr) != 1))
2422     {
2423       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed EXTERNAL_ADDRESS %s given in configuration!\n", external_address);
2424     }
2425
2426   internal_address = NULL;
2427   if ((GNUNET_YES == behind_nat) && (GNUNET_OK !=
2428          GNUNET_CONFIGURATION_get_value_string (env->cfg,
2429                                                 "transport-tcp",
2430                                                 "INTERNAL_ADDRESS",
2431                                                 &internal_address)))
2432     {
2433       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2434                  _("Require INTERNAL_ADDRESS for service `%s' in configuration!\n"),
2435                  "transport-tcp");
2436       GNUNET_SERVICE_stop (service);
2437       GNUNET_free_non_null(external_address);
2438       return NULL;
2439     }
2440
2441   if ((internal_address != NULL) && (inet_pton(AF_INET, internal_address, &in_addr.sin_addr) != 1))
2442     {
2443       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Malformed INTERNAL_ADDRESS %s given in configuration!\n", internal_address);
2444     }
2445
2446   aport = 0;
2447   if ((GNUNET_OK !=
2448        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2449                                               "transport-tcp",
2450                                               "PORT",
2451                                               &bport)) ||
2452       (bport > 65535) ||
2453       ((GNUNET_OK ==
2454         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2455                                                "transport-tcp",
2456                                                "ADVERTISED-PORT",
2457                                                &aport)) && (aport > 65535)))
2458     {
2459       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2460                        _
2461                        ("Require valid port number for service `%s' in configuration!\n"),
2462                        "transport-tcp");
2463       GNUNET_free_non_null(external_address);
2464       GNUNET_free_non_null(internal_address);
2465       GNUNET_SERVICE_stop (service);
2466       return NULL;
2467     }
2468
2469   if (aport == 0)
2470     aport = bport;
2471   plugin = GNUNET_malloc (sizeof (struct Plugin));
2472   plugin->open_port = bport;
2473   plugin->adv_port = aport;
2474   plugin->external_address = external_address;
2475   plugin->internal_address = internal_address;
2476   plugin->behind_nat = behind_nat;
2477   plugin->allow_nat = allow_nat;
2478   plugin->only_nat_addresses = only_nat_addresses;
2479   plugin->env = env;
2480   plugin->lsock = NULL;
2481   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2482   api->cls = plugin;
2483   api->send = &tcp_plugin_send;
2484   api->disconnect = &tcp_plugin_disconnect;
2485   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2486   api->check_address = &tcp_plugin_check_address;
2487   api->address_to_string = &tcp_address_to_string;
2488   plugin->service = service;
2489   plugin->server = GNUNET_SERVICE_get_server (service);
2490   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2491   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2492   for (i = 0;
2493        i <
2494        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2495        i++)
2496     plugin->handlers[i].callback_cls = plugin;
2497   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2498
2499   if (plugin->behind_nat == GNUNET_YES)
2500     {
2501       if (GNUNET_YES != tcp_transport_start_nat_server(plugin))
2502         {
2503           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2504
2505                            _
2506                            ("Failed to start %s required for NAT in %s!\n"),
2507                            "gnunet-nat-server"
2508                            "transport-tcp");
2509           GNUNET_free_non_null(external_address);
2510           GNUNET_free_non_null(internal_address);
2511           GNUNET_SERVICE_stop (service);
2512           GNUNET_free (api);
2513           return NULL;
2514         }
2515     }
2516
2517   if (allow_nat == GNUNET_YES)
2518     {
2519       plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create(100);
2520       GNUNET_assert(plugin->nat_wait_conns != NULL);
2521     }
2522
2523   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("TCP transport listening on port %llu\n"), bport);
2524   if (aport != bport)
2525     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2526                      _("TCP transport advertises itself as being on port %llu\n"),
2527                      aport);
2528   GNUNET_SERVER_disconnect_notify (plugin->server,
2529                                    &disconnect_notify,
2530                                    plugin);
2531
2532   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (env->cfg, "transport-tcp", "BINDTO", &plugin->bind_address))
2533     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Binding tcp plugin to specific address: `%s'\n", plugin->bind_address);
2534
2535   if (plugin->behind_nat == GNUNET_NO)
2536     {
2537       GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2538     }
2539
2540   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->cfg,
2541                                                            AF_UNSPEC,
2542                                                            HOSTNAME_RESOLVE_TIMEOUT,
2543                                                            &process_hostname_ips,
2544                                                            plugin);
2545
2546   if ((plugin->behind_nat == GNUNET_YES) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2547     {
2548       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:0\n", plugin->external_address);
2549       t4.t_port = htons(0);
2550       add_to_address_list (plugin, &t4.ipv4_addr, sizeof (uint32_t));
2551       plugin->env->notify_address (plugin->env->cls,
2552                                   "tcp",
2553                                    &t4, sizeof(t4), GNUNET_TIME_UNIT_FOREVER_REL);
2554     }
2555   else if ((plugin->external_address != NULL) && (inet_pton(AF_INET, plugin->external_address, &t4.ipv4_addr) == 1))
2556     {
2557       t4.t_port = htons(plugin->adv_port);
2558       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Notifying transport of address %s:%d\n", plugin->external_address, plugin->adv_port);
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
2565   return api;
2566 }
2567
2568
2569 /**
2570  * Exit point from the plugin.
2571  */
2572 void *
2573 libgnunet_plugin_transport_tcp_done (void *cls)
2574 {
2575   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2576   struct Plugin *plugin = api->cls;
2577   struct Session *session;
2578   struct LocalAddrList *lal;
2579
2580   while (NULL != (session = plugin->sessions))
2581     disconnect_session (session);
2582   if (NULL != plugin->hostname_dns)
2583     {
2584       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2585       plugin->hostname_dns = NULL;
2586     }
2587   GNUNET_SERVICE_stop (plugin->service);
2588   GNUNET_free (plugin->handlers);
2589   while (NULL != (lal = plugin->lal_head))
2590     {
2591       GNUNET_CONTAINER_DLL_remove (plugin->lal_head,
2592                                    plugin->lal_tail,
2593                                    lal);
2594       GNUNET_free (lal);
2595     }
2596
2597   if (plugin->behind_nat == GNUNET_YES)
2598     {
2599       if (0 != GNUNET_OS_process_kill (plugin->server_proc, SIGTERM))
2600         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill");
2601       GNUNET_OS_process_wait (plugin->server_proc);
2602       GNUNET_OS_process_close (plugin->server_proc);
2603       plugin->server_proc = NULL;
2604     }
2605   GNUNET_free_non_null(plugin->bind_address);
2606   GNUNET_free (plugin);
2607   GNUNET_free (api);
2608   return NULL;
2609 }
2610
2611 /* end of plugin_transport_tcp.c */