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