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