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