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