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