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