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