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