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