-indenting
[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 static 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 /**
1137  * Task cleaning up a NAT connection attempt after timeout
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 static int 
1356 session_disconnect_it (void *cls,
1357                        const GNUNET_HashCode * key,
1358                        void *value)
1359 {
1360   struct Session *session = value;
1361
1362   GNUNET_STATISTICS_update (session->plugin->env->stats,
1363                             gettext_noop
1364                             ("# transport-service disconnect requests for TCP"),
1365                             1, GNUNET_NO);
1366   disconnect_session (session);
1367   return GNUNET_YES;
1368 }
1369
1370 /**
1371  * Function that can be called to force a disconnect from the
1372  * specified neighbour.  This should also cancel all previously
1373  * scheduled transmissions.  Obviously the transmission may have been
1374  * partially completed already, which is OK.  The plugin is supposed
1375  * to close the connection (if applicable) and no longer call the
1376  * transmit continuation(s).
1377  *
1378  * Finally, plugin MUST NOT call the services's receive function to
1379  * notify the service that the connection to the specified target was
1380  * closed after a getting this call.
1381  *
1382  * @param cls closure
1383  * @param target peer for which the last transmission is
1384  *        to be cancelled
1385  */
1386 static void
1387 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1388 {
1389   struct Plugin *plugin = cls;
1390   struct Session *nat_session = NULL;
1391
1392   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1393                    "Disconnecting peer `%4s'\n", GNUNET_i2s (target));
1394
1395   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->sessionmap, &target->hashPubKey, session_disconnect_it, plugin);
1396
1397   nat_session = GNUNET_CONTAINER_multihashmap_get(plugin->nat_wait_conns, &target->hashPubKey);
1398   if (nat_session != NULL)
1399   {
1400     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1401                      "Cleaning up pending NAT session for peer `%4s'\n", GNUNET_i2s (target));
1402     disconnect_session (nat_session);
1403   }
1404 }
1405
1406
1407 /**
1408  * Context for address to string conversion.
1409  */
1410 struct PrettyPrinterContext
1411 {
1412   /**
1413    * Function to call with the result.
1414    */
1415   GNUNET_TRANSPORT_AddressStringCallback asc;
1416
1417   /**
1418    * Clsoure for 'asc'.
1419    */
1420   void *asc_cls;
1421
1422   /**
1423    * Port to add after the IP address.
1424    */
1425   uint16_t port;
1426
1427   int ipv6;
1428 };
1429
1430
1431 /**
1432  * Append our port and forward the result.
1433  *
1434  * @param cls the 'struct PrettyPrinterContext*'
1435  * @param hostname hostname part of the address
1436  */
1437 static void
1438 append_port (void *cls, const char *hostname)
1439 {
1440   struct PrettyPrinterContext *ppc = cls;
1441   char *ret;
1442
1443   if (hostname == NULL)
1444   {
1445     ppc->asc (ppc->asc_cls, NULL);
1446     GNUNET_free (ppc);
1447     return;
1448   }
1449   if (GNUNET_YES == ppc->ipv6)
1450     GNUNET_asprintf (&ret, "[%s]:%d", hostname, ppc->port);
1451   else
1452     GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1453   ppc->asc (ppc->asc_cls, ret);
1454   GNUNET_free (ret);
1455 }
1456
1457
1458 /**
1459  * Convert the transports address to a nice, human-readable
1460  * format.
1461  *
1462  * @param cls closure
1463  * @param type name of the transport that generated the address
1464  * @param addr one of the addresses of the host, NULL for the last address
1465  *        the specific address format depends on the transport
1466  * @param addrlen length of the address
1467  * @param numeric should (IP) addresses be displayed in numeric form?
1468  * @param timeout after how long should we give up?
1469  * @param asc function to call on each string
1470  * @param asc_cls closure for asc
1471  */
1472 static void
1473 tcp_plugin_address_pretty_printer (void *cls, const char *type,
1474                                    const void *addr, size_t addrlen,
1475                                    int numeric,
1476                                    struct GNUNET_TIME_Relative timeout,
1477                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1478                                    void *asc_cls)
1479 {
1480   struct PrettyPrinterContext *ppc;
1481   const void *sb;
1482   size_t sbs;
1483   struct sockaddr_in a4;
1484   struct sockaddr_in6 a6;
1485   const struct IPv4TcpAddress *t4;
1486   const struct IPv6TcpAddress *t6;
1487   uint16_t port;
1488
1489   if (addrlen == sizeof (struct IPv6TcpAddress))
1490   {
1491     t6 = addr;
1492     memset (&a6, 0, sizeof (a6));
1493     a6.sin6_family = AF_INET6;
1494     a6.sin6_port = t6->t6_port;
1495     memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof (struct in6_addr));
1496     port = ntohs (t6->t6_port);
1497     sb = &a6;
1498     sbs = sizeof (a6);
1499   }
1500   else if (addrlen == sizeof (struct IPv4TcpAddress))
1501   {
1502     t4 = addr;
1503     memset (&a4, 0, sizeof (a4));
1504     a4.sin_family = AF_INET;
1505     a4.sin_port = t4->t4_port;
1506     a4.sin_addr.s_addr = t4->ipv4_addr;
1507     port = ntohs (t4->t4_port);
1508     sb = &a4;
1509     sbs = sizeof (a4);
1510   }
1511   else if (0 == addrlen)
1512   {
1513     asc (asc_cls, "<inbound connection>");
1514     asc (asc_cls, NULL);
1515     return;
1516   }
1517   else
1518   {
1519     /* invalid address */
1520     GNUNET_break_op (0);
1521     asc (asc_cls, NULL);
1522     return;
1523   }
1524   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1525   if (addrlen == sizeof (struct IPv6TcpAddress))
1526     ppc->ipv6 = GNUNET_YES;
1527   else
1528     ppc->ipv6 = GNUNET_NO;
1529   ppc->asc = asc;
1530   ppc->asc_cls = asc_cls;
1531   ppc->port = port;
1532   GNUNET_RESOLVER_hostname_get (sb, sbs, !numeric, timeout, &append_port, ppc);
1533 }
1534
1535
1536 /**
1537  * Check if the given port is plausible (must be either our listen
1538  * port or our advertised port), or any port if we are behind NAT
1539  * and do not have a port open.  If it is neither, we return
1540  * GNUNET_SYSERR.
1541  *
1542  * @param plugin global variables
1543  * @param in_port port number to check
1544  * @return GNUNET_OK if port is either open_port or adv_port
1545  */
1546 static int
1547 check_port (struct Plugin *plugin, uint16_t in_port)
1548 {
1549   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1550     return GNUNET_OK;
1551   return GNUNET_SYSERR;
1552 }
1553
1554
1555 /**
1556  * Function that will be called to check if a binary address for this
1557  * plugin is well-formed and corresponds to an address for THIS peer
1558  * (as per our configuration).  Naturally, if absolutely necessary,
1559  * plugins can be a bit conservative in their answer, but in general
1560  * plugins should make sure that the address does not redirect
1561  * traffic to a 3rd party that might try to man-in-the-middle our
1562  * traffic.
1563  *
1564  * @param cls closure, our 'struct Plugin*'
1565  * @param addr pointer to the address
1566  * @param addrlen length of addr
1567  * @return GNUNET_OK if this is a plausible address for this peer
1568  *         and transport, GNUNET_SYSERR if not
1569  */
1570 static int
1571 tcp_plugin_check_address (void *cls, const void *addr, size_t addrlen)
1572 {
1573   struct Plugin *plugin = cls;
1574   struct IPv4TcpAddress *v4;
1575   struct IPv6TcpAddress *v6;
1576
1577   if ((addrlen != sizeof (struct IPv4TcpAddress)) &&
1578       (addrlen != sizeof (struct IPv6TcpAddress)))
1579   {
1580     GNUNET_break_op (0);
1581     return GNUNET_SYSERR;
1582   }
1583   if (addrlen == sizeof (struct IPv4TcpAddress))
1584   {
1585     v4 = (struct IPv4TcpAddress *) addr;
1586     if (GNUNET_OK != check_port (plugin, ntohs (v4->t4_port)))
1587       return GNUNET_SYSERR;
1588     if (GNUNET_OK !=
1589         GNUNET_NAT_test_address (plugin->nat, &v4->ipv4_addr,
1590                                  sizeof (struct in_addr)))
1591       return GNUNET_SYSERR;
1592   }
1593   else
1594   {
1595     v6 = (struct IPv6TcpAddress *) addr;
1596     if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1597     {
1598       GNUNET_break_op (0);
1599       return GNUNET_SYSERR;
1600     }
1601     if (GNUNET_OK != check_port (plugin, ntohs (v6->t6_port)))
1602       return GNUNET_SYSERR;
1603     if (GNUNET_OK !=
1604         GNUNET_NAT_test_address (plugin->nat, &v6->ipv6_addr,
1605                                  sizeof (struct in6_addr)))
1606       return GNUNET_SYSERR;
1607   }
1608   return GNUNET_OK;
1609 }
1610
1611
1612 /**
1613  * We've received a nat probe from this peer via TCP.  Finish
1614  * creating the client session and resume sending of queued
1615  * messages.
1616  *
1617  * @param cls closure
1618  * @param client identification of the client
1619  * @param message the actual message
1620  */
1621 static void
1622 handle_tcp_nat_probe (void *cls, struct GNUNET_SERVER_Client *client,
1623                       const struct GNUNET_MessageHeader *message)
1624 {
1625   struct Plugin *plugin = cls;
1626   struct Session *session;
1627   const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
1628   size_t alen;
1629   void *vaddr;
1630   struct IPv4TcpAddress *t4;
1631   struct IPv6TcpAddress *t6;
1632   const struct sockaddr_in *s4;
1633   const struct sockaddr_in6 *s6;
1634
1635   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "received NAT probe\n");
1636
1637   /* We have received a TCP NAT probe, meaning we (hopefully) initiated
1638    * a connection to this peer by running gnunet-nat-client.  This peer
1639    * received the punch message and now wants us to use the new connection
1640    * as the default for that peer.  Do so and then send a WELCOME message
1641    * so we can really be connected!
1642    */
1643   if (ntohs (message->size) != sizeof (struct TCP_NAT_ProbeMessage))
1644   {
1645     GNUNET_break_op (0);
1646     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1647     return;
1648   }
1649
1650   tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
1651   if (0 ==
1652       memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
1653               sizeof (struct GNUNET_PeerIdentity)))
1654   {
1655     /* refuse connections from ourselves */
1656     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1657     return;
1658   }
1659
1660   session =
1661       GNUNET_CONTAINER_multihashmap_get (plugin->nat_wait_conns,
1662                                          &tcp_nat_probe->
1663                                          clientIdentity.hashPubKey);
1664   if (session == NULL)
1665   {
1666     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1667                      "Did NOT find session for NAT probe!\n");
1668     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1669     return;
1670   }
1671   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1672                    "Found session for NAT probe!\n");
1673
1674   if (session->nat_connection_timeout != GNUNET_SCHEDULER_NO_TASK)
1675   {
1676     GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1677     session->nat_connection_timeout = GNUNET_SCHEDULER_NO_TASK;
1678   }
1679
1680   GNUNET_assert (GNUNET_CONTAINER_multihashmap_remove
1681                  (plugin->nat_wait_conns,
1682                   &tcp_nat_probe->clientIdentity.hashPubKey,
1683                   session) == GNUNET_YES);
1684   if (GNUNET_OK != GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1685   {
1686     GNUNET_break (0);
1687     GNUNET_free (session);
1688     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1689     return;
1690   }
1691
1692   GNUNET_SERVER_client_keep (client);
1693   session->client = client;
1694   session->last_activity = GNUNET_TIME_absolute_get ();
1695   session->inbound = GNUNET_NO;
1696   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1697                    "Found address `%s' for incoming connection\n",
1698                    GNUNET_a2s (vaddr, alen));
1699   switch (((const struct sockaddr *) vaddr)->sa_family)
1700   {
1701   case AF_INET:
1702     s4 = vaddr;
1703     t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1704     t4->t4_port = s4->sin_port;
1705     t4->ipv4_addr = s4->sin_addr.s_addr;
1706     session->addr = t4;
1707     session->addrlen = sizeof (struct IPv4TcpAddress);
1708     break;
1709   case AF_INET6:
1710     s6 = vaddr;
1711     t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1712     t6->t6_port = s6->sin6_port;
1713     memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1714     session->addr = t6;
1715     session->addrlen = sizeof (struct IPv6TcpAddress);
1716     break;
1717   default:
1718     GNUNET_break_op (0);
1719
1720     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1721                      "Bad address for incoming connection!\n");
1722     GNUNET_free (vaddr);
1723
1724     GNUNET_SERVER_client_drop (client);
1725     GNUNET_free (session);
1726     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1727     return;
1728   }
1729   GNUNET_free (vaddr);
1730
1731   GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &session->target.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1732   inc_sessions (plugin, session, __LINE__);
1733   GNUNET_STATISTICS_update (plugin->env->stats,
1734                             gettext_noop ("# TCP sessions active"), 1,
1735                             GNUNET_NO);
1736   process_pending_messages (session);
1737   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1738 }
1739
1740
1741 /**
1742  * We've received a welcome from this peer via TCP.  Possibly create a
1743  * fresh client record and send back our welcome.
1744  *
1745  * @param cls closure
1746  * @param client identification of the client
1747  * @param message the actual message
1748  */
1749 static void
1750 handle_tcp_welcome (void *cls, struct GNUNET_SERVER_Client *client,
1751                     const struct GNUNET_MessageHeader *message)
1752 {
1753   struct Plugin *plugin = cls;
1754   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1755   struct Session *session;
1756   size_t alen;
1757   void *vaddr;
1758   struct IPv4TcpAddress *t4;
1759   struct IPv6TcpAddress *t6;
1760   const struct sockaddr_in *s4;
1761   const struct sockaddr_in6 *s6;
1762
1763   if (0 ==
1764       memcmp (&wm->clientIdentity, plugin->env->my_identity,
1765               sizeof (struct GNUNET_PeerIdentity)))
1766   {
1767     /* refuse connections from ourselves */
1768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1769     return;
1770   }
1771
1772   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1773                    "Received %s message from `%4s'\n", "WELCOME",
1774                    GNUNET_i2s (&wm->clientIdentity));
1775   GNUNET_STATISTICS_update (plugin->env->stats,
1776                             gettext_noop ("# TCP WELCOME messages received"), 1,
1777                             GNUNET_NO);
1778
1779   session = lookup_session_by_client (plugin, client);
1780   if (session != NULL)
1781   {
1782     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1783     {
1784       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1785                        "Found existing session %p for peer `%s'\n",
1786                        session,
1787                        GNUNET_a2s (vaddr, alen));
1788       GNUNET_free (vaddr);
1789     }
1790   }
1791   else
1792   {
1793     GNUNET_SERVER_client_keep (client);
1794     session = create_session (plugin, &wm->clientIdentity, client, GNUNET_NO);
1795     session->inbound = GNUNET_YES;
1796
1797     if (GNUNET_OK == GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1798     {
1799       if (alen == sizeof (struct sockaddr_in))
1800       {
1801         s4 = vaddr;
1802         t4 = GNUNET_malloc (sizeof (struct IPv4TcpAddress));
1803         t4->t4_port = s4->sin_port;
1804         t4->ipv4_addr = s4->sin_addr.s_addr;
1805         session->addr = t4;
1806         session->addrlen = sizeof (struct IPv4TcpAddress);
1807       }
1808       else if (alen == sizeof (struct sockaddr_in6))
1809       {
1810         s6 = vaddr;
1811         t6 = GNUNET_malloc (sizeof (struct IPv6TcpAddress));
1812         t6->t6_port = s6->sin6_port;
1813         memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof (struct in6_addr));
1814         session->addr = t6;
1815         session->addrlen = sizeof (struct IPv6TcpAddress);
1816       }
1817
1818       struct GNUNET_ATS_Information ats;
1819       ats = plugin->env->get_address_type (plugin->env->cls, vaddr ,alen);
1820       session->ats_address_network_type = ats.value;
1821
1822       GNUNET_free (vaddr);
1823     }
1824     else
1825     {
1826       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1827                        "Did not obtain TCP socket address for incoming connection\n");
1828     }
1829     GNUNET_CONTAINER_multihashmap_put(plugin->sessionmap, &wm->clientIdentity.hashPubKey, session, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1830     inc_sessions (plugin, session, __LINE__);
1831   }
1832
1833   if (session->expecting_welcome != GNUNET_YES)
1834   {
1835     GNUNET_break_op (0);
1836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1837     return;
1838   }
1839   session->last_activity = GNUNET_TIME_absolute_get ();
1840   session->expecting_welcome = GNUNET_NO;
1841
1842
1843   process_pending_messages (session);
1844
1845   GNUNET_SERVER_client_set_timeout (client,
1846                                     GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1847   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1848 }
1849
1850
1851 /**
1852  * Task to signal the server that we can continue
1853  * receiving from the TCP client now.
1854  *
1855  * @param cls the 'struct Session*'
1856  * @param tc task context (unused)
1857  */
1858 static void
1859 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1860 {
1861   struct Session *session = cls;
1862   struct GNUNET_TIME_Relative delay;
1863   struct GNUNET_ATS_Information ats;
1864
1865   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1866   delay =
1867       session->plugin->env->receive (session->plugin->env->cls,
1868                                      &session->target, NULL, &ats, 0, session,
1869                                      NULL, 0);
1870   if (delay.rel_value == 0)
1871     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1872   else
1873     session->receive_delay_task =
1874         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1875 }
1876
1877
1878 /**
1879  * We've received data for this peer via TCP.  Unbox,
1880  * compute latency and forward.
1881  *
1882  * @param cls closure
1883  * @param client identification of the client
1884  * @param message the actual message
1885  */
1886 static void
1887 handle_tcp_data (void *cls, struct GNUNET_SERVER_Client *client,
1888                  const struct GNUNET_MessageHeader *message)
1889 {
1890   struct Plugin *plugin = cls;
1891   struct Session *session;
1892   struct GNUNET_TIME_Relative delay;
1893   uint16_t type;
1894
1895   type = ntohs (message->type);
1896   if ((GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
1897       (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type))
1898   {
1899     /* We don't want to propagate WELCOME and NAT Probe messages up! */
1900     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1901     return;
1902   }
1903   session = lookup_session_by_client (plugin, client);
1904   if (NULL == session)
1905   {
1906     /* No inbound session found */
1907     void *vaddr;
1908     size_t alen;
1909     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1910     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1911                      "Received unexpected %u bytes of type %u from `%s'\n",
1912                      (unsigned int) ntohs (message->size),
1913                      (unsigned int) ntohs (message->type),
1914                      GNUNET_a2s(vaddr, alen));
1915     GNUNET_break_op (0);
1916     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1917     GNUNET_free_non_null(vaddr);
1918     return;
1919   }
1920   else if (GNUNET_YES == session->expecting_welcome)
1921   {
1922     /* Session is expecting WELCOME message */
1923     void *vaddr;
1924     size_t alen;
1925     GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1926     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
1927                      "Received unexpected %u bytes of type %u from `%s'\n",
1928                      (unsigned int) ntohs (message->size),
1929                      (unsigned int) ntohs (message->type),
1930                      GNUNET_a2s(vaddr, alen));
1931     GNUNET_break_op (0);
1932     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1933     GNUNET_free_non_null(vaddr);
1934     return;
1935   }
1936
1937   session->last_activity = GNUNET_TIME_absolute_get ();
1938
1939   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1940                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1941                    (unsigned int) ntohs (message->size),
1942                    (unsigned int) ntohs (message->type),
1943                    GNUNET_i2s (&session->target));
1944
1945   GNUNET_STATISTICS_update (plugin->env->stats,
1946                             gettext_noop ("# bytes received via TCP"),
1947                             ntohs (message->size), GNUNET_NO);
1948   struct GNUNET_ATS_Information distance[2];
1949
1950   distance[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1951   distance[0].value = htonl (1);
1952   distance[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1953   distance[1].value = session->ats_address_network_type;
1954   GNUNET_break (ntohl(session->ats_address_network_type) != GNUNET_ATS_NET_UNSPECIFIED);
1955
1956   delay = plugin->env->receive (plugin->env->cls,
1957                                 &session->target,
1958                                 message,
1959                                 (const struct GNUNET_ATS_Information *) &distance,
1960                                 1, session,
1961                                 (GNUNET_YES == session->inbound) ? NULL : session->addr,
1962                                 (GNUNET_YES == session->inbound) ? 0 : session->addrlen);
1963   if (delay.rel_value == 0)
1964   {
1965     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1966   }
1967   else
1968   {
1969     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
1970                      "Throttling receiving from `%s' for %llu ms\n",
1971                      GNUNET_i2s (&session->target),
1972                      (unsigned long long) delay.rel_value);
1973     GNUNET_SERVER_disable_receive_done_warning (client);
1974     session->receive_delay_task =
1975         GNUNET_SCHEDULER_add_delayed (delay, &delayed_done, session);
1976   }
1977 }
1978
1979
1980 /**
1981  * Functions with this signature are called whenever a peer
1982  * is disconnected on the network level.
1983  *
1984  * @param cls closure
1985  * @param client identification of the client
1986  */
1987 static void
1988 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1989 {
1990   struct Plugin *plugin = cls;
1991   struct Session *session;
1992
1993   if (client == NULL)
1994     return;
1995   plugin->max_connections++;
1996   session = lookup_session_by_client (plugin, client);
1997   if (session == NULL)
1998     return;                     /* unknown, nothing to do */
1999   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp",
2000                    "Destroying session of `%4s' with %s due to network-level disconnect.\n",
2001                    GNUNET_i2s (&session->target),
2002                    (session->addr !=
2003                     NULL) ? tcp_address_to_string (session->plugin,
2004                                                    session->addr,
2005                                                    session->addrlen) :
2006                    "*");
2007   GNUNET_STATISTICS_update (session->plugin->env->stats,
2008                             gettext_noop
2009                             ("# network-level TCP disconnect events"), 1,
2010                             GNUNET_NO);
2011   disconnect_session (session);
2012 }
2013
2014
2015 /**
2016  * We can now send a probe message, copy into buffer to really send.
2017  *
2018  * @param cls closure, a struct TCPProbeContext
2019  * @param size max size to copy
2020  * @param buf buffer to copy message to
2021  * @return number of bytes copied into buf
2022  */
2023 static size_t
2024 notify_send_probe (void *cls, size_t size, void *buf)
2025 {
2026   struct TCPProbeContext *tcp_probe_ctx = cls;
2027   struct Plugin *plugin = tcp_probe_ctx->plugin;
2028   size_t ret;
2029
2030   tcp_probe_ctx->transmit_handle = NULL;
2031   GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2032                                tcp_probe_ctx);
2033   if (buf == NULL)
2034   {
2035     GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
2036     GNUNET_free (tcp_probe_ctx);
2037     return 0;
2038   }
2039   GNUNET_assert (size >= sizeof (tcp_probe_ctx->message));
2040   memcpy (buf, &tcp_probe_ctx->message, sizeof (tcp_probe_ctx->message));
2041   GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
2042                                 tcp_probe_ctx->sock);
2043   ret = sizeof (tcp_probe_ctx->message);
2044   GNUNET_free (tcp_probe_ctx);
2045   return ret;
2046 }
2047
2048
2049 /**
2050  * Function called by the NAT subsystem suggesting another peer wants
2051  * to connect to us via connection reversal.  Try to connect back to the
2052  * given IP.
2053  *
2054  * @param cls closure
2055  * @param addr address to try
2056  * @param addrlen number of bytes in addr
2057  */
2058 static void
2059 try_connection_reversal (void *cls, const struct sockaddr *addr,
2060                          socklen_t addrlen)
2061 {
2062   struct Plugin *plugin = cls;
2063   struct GNUNET_CONNECTION_Handle *sock;
2064   struct TCPProbeContext *tcp_probe_ctx;
2065
2066   /**
2067    * We have received an ICMP response, ostensibly from a peer
2068    * that wants to connect to us! Send a message to establish a connection.
2069    */
2070   sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
2071   if (sock == NULL)
2072   {
2073     /* failed for some odd reason (out of sockets?); ignore attempt */
2074     return;
2075   }
2076
2077   /* FIXME: do we need to track these probe context objects so that
2078    * we can clean them up on plugin unload? */
2079   tcp_probe_ctx = GNUNET_malloc (sizeof (struct TCPProbeContext));
2080   tcp_probe_ctx->message.header.size =
2081       htons (sizeof (struct TCP_NAT_ProbeMessage));
2082   tcp_probe_ctx->message.header.type =
2083       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
2084   memcpy (&tcp_probe_ctx->message.clientIdentity, plugin->env->my_identity,
2085           sizeof (struct GNUNET_PeerIdentity));
2086   tcp_probe_ctx->plugin = plugin;
2087   tcp_probe_ctx->sock = sock;
2088   GNUNET_CONTAINER_DLL_insert (plugin->probe_head, plugin->probe_tail,
2089                                tcp_probe_ctx);
2090   tcp_probe_ctx->transmit_handle =
2091       GNUNET_CONNECTION_notify_transmit_ready (sock,
2092                                                ntohs (tcp_probe_ctx->
2093                                                       message.header.size),
2094                                                GNUNET_TIME_UNIT_FOREVER_REL,
2095                                                &notify_send_probe,
2096                                                tcp_probe_ctx);
2097
2098 }
2099
2100
2101 /**
2102  * Entry point for the plugin.
2103  *
2104  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
2105  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
2106  */
2107 void *
2108 libgnunet_plugin_transport_tcp_init (void *cls)
2109 {
2110   static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
2111     {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
2112      sizeof (struct WelcomeMessage)},
2113     {&handle_tcp_nat_probe, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
2114      sizeof (struct TCP_NAT_ProbeMessage)},
2115     {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
2116     {NULL, NULL, 0, 0}
2117   };
2118   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2119   struct GNUNET_TRANSPORT_PluginFunctions *api;
2120   struct Plugin *plugin;
2121   struct GNUNET_SERVICE_Context *service;
2122   unsigned long long aport;
2123   unsigned long long bport;
2124   unsigned long long max_connections;
2125   unsigned int i;
2126   struct GNUNET_TIME_Relative idle_timeout;
2127   int ret;
2128   struct sockaddr **addrs;
2129   socklen_t *addrlens;
2130
2131   if (NULL == env->receive)
2132   {
2133     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2134        initialze the plugin or the API */
2135     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2136     api->cls = NULL;
2137     api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2138     api->address_to_string = &tcp_address_to_string;
2139     api->string_to_address = &tcp_string_to_address;
2140     return api;
2141   }
2142
2143   if (GNUNET_OK !=
2144       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2145                                              "MAX_CONNECTIONS",
2146                                              &max_connections))
2147     max_connections = 128;
2148
2149   aport = 0;
2150   if ((GNUNET_OK !=
2151        GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp", "PORT",
2152                                               &bport)) || (bport > 65535) ||
2153       ((GNUNET_OK ==
2154         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
2155                                                "ADVERTISED-PORT", &aport)) &&
2156        (aport > 65535)))
2157   {
2158     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2159                      _
2160                      ("Require valid port number for service `%s' in configuration!\n"),
2161                      "transport-tcp");
2162     return NULL;
2163   }
2164   if (aport == 0)
2165     aport = bport;
2166   if (bport == 0)
2167     aport = 0;
2168   if (bport != 0)
2169   {
2170     service = GNUNET_SERVICE_start ("transport-tcp", env->cfg, GNUNET_SERVICE_OPTION_NONE);
2171     if (service == NULL)
2172     {
2173       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "tcp",
2174                        _("Failed to start service.\n"));
2175       return NULL;
2176     }
2177   }
2178   else
2179     service = NULL;
2180
2181   plugin = GNUNET_malloc (sizeof (struct Plugin));
2182   plugin->sessionmap = GNUNET_CONTAINER_multihashmap_create(max_connections);
2183   plugin->max_connections = max_connections;
2184   plugin->open_port = bport;
2185   plugin->adv_port = aport;
2186   plugin->env = env;
2187   plugin->lsock = NULL;
2188   if ((service != NULL) &&
2189       (GNUNET_SYSERR !=
2190        (ret =
2191         GNUNET_SERVICE_get_server_addresses ("transport-tcp", env->cfg, &addrs,
2192                                              &addrlens))))
2193   {
2194     plugin->nat =
2195         GNUNET_NAT_register (env->cfg, GNUNET_YES, aport, (unsigned int) ret,
2196                              (const struct sockaddr **) addrs, addrlens,
2197                              &tcp_nat_port_map_callback,
2198                              &try_connection_reversal, plugin);
2199     while (ret > 0)
2200     {
2201       ret--;
2202       GNUNET_assert (addrs[ret] != NULL);
2203       GNUNET_free (addrs[ret]);
2204     }
2205     GNUNET_free_non_null (addrs);
2206     GNUNET_free_non_null (addrlens);
2207   }
2208   else
2209   {
2210     plugin->nat =
2211         GNUNET_NAT_register (env->cfg, GNUNET_YES, 0, 0, NULL, NULL, NULL,
2212                              &try_connection_reversal, plugin);
2213   }
2214   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2215   api->cls = plugin;
2216   api->send = &tcp_plugin_send;
2217   api->get_session = &tcp_plugin_get_session;
2218
2219   api->disconnect = &tcp_plugin_disconnect;
2220   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2221   api->check_address = &tcp_plugin_check_address;
2222   api->address_to_string = &tcp_address_to_string;
2223   api->string_to_address = &tcp_string_to_address;
2224   plugin->service = service;
2225   if (service != NULL)
2226   {
2227     plugin->server = GNUNET_SERVICE_get_server (service);
2228   }
2229   else
2230   {
2231     if (GNUNET_OK !=
2232         GNUNET_CONFIGURATION_get_value_time (env->cfg, "transport-tcp",
2233                                              "TIMEOUT", &idle_timeout))
2234     {
2235       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "tcp",
2236                        _("Failed to find option %s in section %s!\n"),
2237                        "TIMEOUT", "transport-tcp");
2238       if (plugin->nat != NULL)
2239         GNUNET_NAT_unregister (plugin->nat);
2240       GNUNET_free (plugin);
2241       GNUNET_free (api);
2242       return NULL;
2243     }
2244     plugin->server =
2245         GNUNET_SERVER_create_with_sockets (&plugin_tcp_access_check, plugin,
2246                                            NULL, idle_timeout, GNUNET_YES);
2247   }
2248   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
2249   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
2250   for (i = 0;
2251        i < sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
2252        i++)
2253     plugin->handlers[i].callback_cls = plugin;
2254   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
2255   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify, plugin);
2256   plugin->nat_wait_conns = GNUNET_CONTAINER_multihashmap_create (16);
2257   if (bport != 0)
2258     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2259                      _("TCP transport listening on port %llu\n"), bport);
2260   else
2261     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2262                      _
2263                      ("TCP transport not listening on any port (client only)\n"));
2264   if (aport != bport)
2265     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "tcp",
2266                      _
2267                      ("TCP transport advertises itself as being on port %llu\n"),
2268                      aport);
2269   /* Initially set connections to 0 */
2270   GNUNET_STATISTICS_set(plugin->env->stats,
2271                         gettext_noop ("# TCP sessions active"), 0,
2272                         GNUNET_NO);
2273   return api;
2274 }
2275
2276
2277 /**
2278  * Exit point from the plugin.
2279  */
2280 void *
2281 libgnunet_plugin_transport_tcp_done (void *cls)
2282 {
2283   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2284   struct Plugin *plugin = api->cls;
2285   struct TCPProbeContext *tcp_probe;
2286
2287   if (NULL == plugin)
2288   {
2289     GNUNET_free (api);
2290     return NULL;
2291   }
2292   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "tcp", "Shutting down TCP plugin\n");
2293
2294   /* Removing leftover sessions */
2295   GNUNET_CONTAINER_multihashmap_iterate(plugin->sessionmap, &session_disconnect_it, NULL);
2296   /* Removing leftover NAT sessions */
2297   GNUNET_CONTAINER_multihashmap_iterate(plugin->nat_wait_conns, &session_disconnect_it, NULL);
2298
2299   if (plugin->service != NULL)
2300     GNUNET_SERVICE_stop (plugin->service);
2301   else
2302     GNUNET_SERVER_destroy (plugin->server);
2303   GNUNET_free (plugin->handlers);
2304   if (plugin->nat != NULL)
2305     GNUNET_NAT_unregister (plugin->nat);
2306   while (NULL != (tcp_probe = plugin->probe_head))
2307   {
2308     GNUNET_CONTAINER_DLL_remove (plugin->probe_head, plugin->probe_tail,
2309                                  tcp_probe);
2310     GNUNET_CONNECTION_destroy (tcp_probe->sock);
2311     GNUNET_free (tcp_probe);
2312   }
2313   GNUNET_CONTAINER_multihashmap_destroy (plugin->nat_wait_conns);
2314   GNUNET_CONTAINER_multihashmap_destroy (plugin->sessionmap);
2315   GNUNET_free (plugin);
2316   GNUNET_free (api);
2317   return NULL;
2318 }
2319
2320 /* end of plugin_transport_tcp.c */